diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..fdf84c7 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,14 @@ +root = true + +[*] +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +charset = utf-8 + +[*.lua] +indent_style = space +indent_size = 4 + +[Makefile] +indent_style = tab diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f637c51 --- /dev/null +++ b/.gitignore @@ -0,0 +1,17 @@ +/proxy_temp/ +/scgi_temp/ +/uwsgi_temp/ +.idea/ +*.log +.un~ +nginx.pid +t/servroot +conf/app-dev.json +#deps + +.travis/ +!.travis/ASF-Release.cfg +bin/lj-releng + +benchmark/out/ +!benchmark/server/conf/nginx.conf diff --git a/.luacheckrc b/.luacheckrc new file mode 100644 index 0000000..6b3ce04 --- /dev/null +++ b/.luacheckrc @@ -0,0 +1,4 @@ +std = "ngx_lua" +unused_args = false +redefined = false +max_line_length = 100 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..74e56d0 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,22 @@ +FROM openresty/openresty:1.19.3.1-1-centos AS last-stage + +MAINTAINER "shenshuo<191715030@qq.com>" + +## 设置编码 +ENV LANG en_US.UTF-8 +# 同步时间 +ENV TZ=Asia/Shanghai +RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone + +COPY . /usr/local/openresty/nginx/ + +WORKDIR /usr/local/openresty/nginx/ +VOLUME /usr/local/openresty/nginx/logs/ + +EXPOSE 8888 11000 + +CMD ["/usr/bin/openresty", "-g", "daemon off;"] + +STOPSIGNAL SIGQUIT + +# docker build . -t tianmen2_image diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + 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/Makefile b/Makefile new file mode 100644 index 0000000..7248077 --- /dev/null +++ b/Makefile @@ -0,0 +1,211 @@ +INST_PREFIX ?= /usr +INST_LIBDIR ?= $(INST_PREFIX)/lib64/lua/5.1 +INST_LUADIR ?= $(INST_PREFIX)/share/lua/5.1 +INST_BINDIR ?= /usr/bin +INSTALL ?= install +UNAME ?= $(shell uname) +OR_EXEC ?= $(shell which openresty) +LUAROCKS_VER ?= $(shell luarocks --version | grep -E -o "luarocks [0-9]+.") + +SHELL := /bin/bash -o pipefail + +VERSION ?= latest +RELEASE_SRC = apache-apisix-${VERSION}-src + +.PHONY: default +default: +ifeq ($(OR_EXEC), ) +ifeq ("$(wildcard /usr/local/openresty-debug/bin/openresty)", "") + @echo "ERROR: OpenResty not found. You have to install OpenResty and add the binary file to PATH before install Apache APISIX." + exit 1 +endif +endif + +LUAJIT_DIR ?= $(shell ${OR_EXEC} -V 2>&1 | grep prefix | grep -Eo 'prefix=(.*)/nginx\s+--' | grep -Eo '/.*/')luajit + +### help: Show Makefile rules +.PHONY: help +help: default + @echo Makefile rules: + @echo + @grep -E '^### [-A-Za-z0-9_]+:' Makefile | sed 's/###/ /' + + +### deps: Installation dependencies +.PHONY: deps +deps: default +ifeq ($(LUAROCKS_VER),luarocks 3.) + luarocks install --lua-dir=$(LUAJIT_DIR) rockspec/tm-master-0.rockspec --tree=deps --only-deps --local +else + luarocks install rockspec/tm-master-0.rockspec --tree=deps --only-deps --local +endif + + +### utils: Installation tools +.PHONY: utils +utils: +ifeq ("$(wildcard utils/lj-releng)", "") + wget -P utils https://raw.githubusercontent.com/iresty/openresty-devel-utils/master/lj-releng + chmod a+x utils/lj-releng +endif + + +### lint: Lint Lua source code +.PHONY: lint +lint: utils + ./utils/check-lua-code-style.sh + + +### init: Initialize the runtime environment +.PHONY: init +init: default + ./bin/apisix init + ./bin/apisix init_etcd + + +### run: Start the apisix server +.PHONY: run +run: default +ifeq ("$(wildcard logs/nginx.pid)", "") + mkdir -p logs + $(OR_EXEC) -p $$PWD/ -c $$PWD/conf/nginx.conf +else + @echo "APISIX is running..." +endif + + +### stop: Stop the apisix server +.PHONY: stop +stop: default + $(OR_EXEC) -p $$PWD/ -c $$PWD/conf/nginx.conf -s stop + + +### verify: Verify the configuration of apisix server +.PHONY: verify +verify: default + $(OR_EXEC) -p $$PWD/ -c $$PWD/conf/nginx.conf -t + + +### clean: Remove generated files +.PHONY: clean +clean: + rm -rf logs/ + + +### reload: Reload the apisix server +.PHONY: reload +reload: default + $(OR_EXEC) -p $$PWD/ -c $$PWD/conf/nginx.conf -s reload + + +### install: Install the apisix (only for luarocks) +.PHONY: install +install: default + $(INSTALL) -d /usr/local/apisix/ + $(INSTALL) -d /usr/local/apisix/logs/ + $(INSTALL) -d /usr/local/apisix/conf/cert + $(INSTALL) conf/mime.types /usr/local/apisix/conf/mime.types + $(INSTALL) conf/config.yaml /usr/local/apisix/conf/config.yaml + $(INSTALL) conf/config-default.yaml /usr/local/apisix/conf/config-default.yaml + + $(INSTALL) -d $(INST_LUADIR)/apisix + $(INSTALL) apisix/*.lua $(INST_LUADIR)/apisix/ + + $(INSTALL) -d $(INST_LUADIR)/apisix/admin + $(INSTALL) apisix/admin/*.lua $(INST_LUADIR)/apisix/admin/ + + $(INSTALL) -d $(INST_LUADIR)/apisix/balancer + $(INSTALL) apisix/balancer/*.lua $(INST_LUADIR)/apisix/balancer/ + + $(INSTALL) -d $(INST_LUADIR)/apisix/core + $(INSTALL) apisix/core/*.lua $(INST_LUADIR)/apisix/core/ + + $(INSTALL) -d $(INST_LUADIR)/apisix/cli + $(INSTALL) apisix/cli/*.lua $(INST_LUADIR)/apisix/cli/ + + $(INSTALL) -d $(INST_LUADIR)/apisix/discovery + $(INSTALL) apisix/discovery/*.lua $(INST_LUADIR)/apisix/discovery/ + + $(INSTALL) -d $(INST_LUADIR)/apisix/http + $(INSTALL) apisix/http/*.lua $(INST_LUADIR)/apisix/http/ + + $(INSTALL) -d $(INST_LUADIR)/apisix/http/router + $(INSTALL) apisix/http/router/*.lua $(INST_LUADIR)/apisix/http/router/ + + $(INSTALL) -d $(INST_LUADIR)/apisix/plugins + $(INSTALL) apisix/plugins/*.lua $(INST_LUADIR)/apisix/plugins/ + + $(INSTALL) -d $(INST_LUADIR)/apisix/plugins/grpc-transcode + $(INSTALL) apisix/plugins/grpc-transcode/*.lua $(INST_LUADIR)/apisix/plugins/grpc-transcode/ + + $(INSTALL) -d $(INST_LUADIR)/apisix/plugins/limit-count + $(INSTALL) apisix/plugins/limit-count/*.lua $(INST_LUADIR)/apisix/plugins/limit-count/ + + $(INSTALL) -d $(INST_LUADIR)/apisix/plugins/prometheus + $(INSTALL) apisix/plugins/prometheus/*.lua $(INST_LUADIR)/apisix/plugins/prometheus/ + + $(INSTALL) -d $(INST_LUADIR)/apisix/plugins/serverless + $(INSTALL) apisix/plugins/serverless/*.lua $(INST_LUADIR)/apisix/plugins/serverless/ + + $(INSTALL) -d $(INST_LUADIR)/apisix/plugins/zipkin + $(INSTALL) apisix/plugins/zipkin/*.lua $(INST_LUADIR)/apisix/plugins/zipkin/ + + $(INSTALL) -d $(INST_LUADIR)/apisix/ssl/router + $(INSTALL) apisix/ssl/router/*.lua $(INST_LUADIR)/apisix/ssl/router/ + + $(INSTALL) -d $(INST_LUADIR)/apisix/stream/plugins + $(INSTALL) apisix/stream/plugins/*.lua $(INST_LUADIR)/apisix/stream/plugins/ + + $(INSTALL) -d $(INST_LUADIR)/apisix/stream/router + $(INSTALL) apisix/stream/router/*.lua $(INST_LUADIR)/apisix/stream/router/ + + $(INSTALL) -d $(INST_LUADIR)/apisix/utils + $(INSTALL) apisix/utils/*.lua $(INST_LUADIR)/apisix/utils/ + + $(INSTALL) README.md $(INST_CONFDIR)/README.md + $(INSTALL) bin/apisix $(INST_BINDIR)/apisix + + $(INSTALL) -d $(INST_LUADIR)/apisix/plugins/slslog + $(INSTALL) apisix/plugins/slslog/*.lua $(INST_LUADIR)/apisix/plugins/slslog/ + + +### test: Run the test case +test: + git submodule update --init --recursive + prove -I../test-nginx/lib -I./ -r -s t/ + +### license-check: Check Lua source code for Apache License +.PHONY: license-check +license-check: +ifeq ("$(wildcard .travis/openwhisk-utilities/scancode/scanCode.py)", "") + git clone https://github.com/apache/openwhisk-utilities.git .travis/openwhisk-utilities + cp .travis/ASF* .travis/openwhisk-utilities/scancode/ +endif + .travis/openwhisk-utilities/scancode/scanCode.py --config .travis/ASF-Release.cfg ./ + +release-src: + tar -zcvf $(RELEASE_SRC).tgz \ + --exclude .github \ + --exclude .git \ + --exclude .gitattributes \ + --exclude .idea \ + --exclude .travis \ + --exclude .gitignore \ + --exclude .DS_Store \ + --exclude benchmark \ + --exclude doc \ + --exclude kubernetes \ + --exclude logos \ + --exclude deps \ + --exclude logs \ + --exclude t \ + --exclude release \ + . + + gpg --batch --yes --armor --detach-sig $(RELEASE_SRC).tgz + shasum -a 512 $(RELEASE_SRC).tgz > $(RELEASE_SRC).tgz.sha512 + + mkdir -p release + mv $(RELEASE_SRC).tgz release/$(RELEASE_SRC).tgz + mv $(RELEASE_SRC).tgz.asc release/$(RELEASE_SRC).tgz.asc + mv $(RELEASE_SRC).tgz.sha512 release/$(RELEASE_SRC).tgz.sha512 diff --git a/README.md b/README.md new file mode 100644 index 0000000..a71e177 --- /dev/null +++ b/README.md @@ -0,0 +1,227 @@ +# 天门 + +借鉴 apisix 实现的轻量级网关服务 + + +## 简介。 + +项目中参考和引用了[ws-cloud-gateway](https://github.com/tech-microworld/ws-cloud-gateway)和[apisix](https://github.com/apache/apisix)的源码。 +对codo所使用的api网关进行优化 + +## 目录 + +- [特性](#特性) +- [文档](#文档) +- [立刻开始](#立刻开始) +- [性能测试](#性能测试) +- [社区](#社区) +- [视频和文章](#视频和文章) +- [全景图](#全景图) +- [贡献](#贡献) +- [致谢](#致谢) +- [协议](#协议) +- + +## 特性 + +你可以当做流量入口,来处理所有的业务数据,包括动态路由、动态上游、动态证书、 +A/B 测试、金丝雀发布(灰度发布)、蓝绿部署、限流限速、抵御恶意攻击、监控报警、服务可观测性、服务治理等。 + + +插件文档待完善 + +- **全平台** + + - 云原生: 平台无关,没有供应商锁定,无论裸机还是 Kubernetes,APISIX 都可以运行。 + - 运行环境: OpenResty + - +- **多协议** + - [gRPC 代理](doc/zh-cn/grpc-proxy.md):通过 APISIX 代理 gRPC 连接,并使用 APISIX 的大部分特性管理你的 gRPC 服务。 + - [gRPC 协议转换](doc/zh-cn/plugins/grpc-transcode.md):支持协议的转换,这样客户端可以通过 HTTP/JSON 来访问你的 gRPC API。 + - Websocket 代理 + - Proxy Protocol + - HTTP(S) 反向代理 + - [SSL](doc/zh-cn/https.md):动态加载 SSL 证书 + - +- **全动态能力** +- **精细化路由** +- **安全防护** +- **运维友好** +- **高度可扩展** + +## 性能测试 + +## 文档 +[文档索引](doc/README.md) + +## 更新日志 +[更新日志](doc/README.md) + +## 立刻开始 +### 编译和安装 + +准备在以下操作系统中可顺利安装并做过测试: + +CentOS 7, Ubuntu 16.04, Ubuntu 18.04, Debian 9, Debian 10, macOS + +有以下几种方式来安装Release 版本: + +1. 源码编译(适用所有系统) + - 安装运行时依赖:OpenResty 和 etcd,以及编译的依赖:luarocks。参考[依赖安装文档](https://github.com/apache/apisix/blob/master/doc/zh-cn/install-dependencies.md) + + - 下载最新的源码发布包: + + ```shell + git clone xxx.git + ``` + + + + - 编译部署 + + ```shell + $ cd api-gateway + # 安装运行时依赖的 Lua 库: + $ make deps + $ \cp -arp . + /usr/local/openresty/nginx/ + ``` + + + + - 启动 : + ```shell + $ /bin/systemctl start openresty.service + ``` +2. Docker 镜像(适用所有系统) + + 默认会拉取最新的发布包: + + ```shell + $ docker build . -t gateway_image + $ docker-compose up -d + ``` + +### 针对开发者 +> 开发者去看apisix的文档,写的比较完整 + +#### 检查 +``` +#安装 +$ luarocks install luacheck +$ luacheck -q gateway +``` + +## 性能测试 + +### wrk 测试 + +```bash +# 安装wrk +$ git clone https://github.com/wg/wrk.git +$ cd wrk && make +$ cp wrk /bin/ +$ sh benchmark/run-wrk.sh + +``` + +### AB 测试 + +AB测试 1核心 RPS 14000 4核心24000 ,token和rbac验证RPS分别为 10000 24000 + +![1核心 无token](docs/images/abtest_1core.png) + +![4核心 无token](./docs/images/abtest_4core.png) + +![1核心 token鉴权](./docs/images/abtest_all_plugins_1core.png) + +![4核心 token鉴权](./docs/images/abtest_all_plugins_4core.png) + + + +## 整体架构 + + +## 服务发现 +服务启动时,将自己的节点信息注册到etcd,包括:服务名称、ip、端口 + +网关服务从 etcd 监听服务节点信息,保存到缓存中,从客户端请求的url中提取服务名称,通过服务名称查找节点信息,将请求转发到后端服务 + + +## 插件功能列表 + +- [x] 服务发现,动态路由 +- [x] 自动生成 requestId,方便链路跟踪 +- [x] 控制面板 +- [x] gRPC 代理 +- [x] jwt 用户登录认证 +- [x] rbac 用户登录认证鉴权 +- [ ] 动态ip防火墙 +- [x] 限流器 +- [x] referer限制 +- [x] IP黑白名单 +- [x] cors跨域 +- [ ] 接口协议加解密 +- [ ] 统一配置管理 +- [ ] 外部日志记录 + + +##### 限流器 +**属性** + + | 名称 | 类型 | 必选项 | 默认值 | 有效值 | 描述 | + | ------------- | ------- | ------ | ------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------- | + | limit_req_rate | integer | 必须 | | limit_req_rate > 0 | 指定的请求速率(以秒为单位),请求速率超过 `rate` 但没有超过 (`rate` + `brust`)的请求会被加上延时。 | + | limit_req_burst| integer | 必须 | | limit_req_burst >= 0 | 请求速率超过 (`rate` + `brust`)的请求会被直接拒绝。| + +##### referer限制 +**属性** + +| 参数名 | 类型 | 可选项 | 默认值 | 有效值 | 描述 | +| --------- | ------------- | ------ | ------ | ------ | -------------------------------- | +| referer_whitelist | array[string] | 必须 | | | 域名列表。域名开头可以用'*'作为通配符 | +| referer_bypass_missing | boolean | 可选 | false | | 当 Referer 不存在或格式有误时,是否绕过检查 | + +##### IP黑白名单 +`ip-restriction` 可以通过以下方式限制对服务或路线的访问,将 IP 地址列入白名单或黑名单。 单个 IP 地址,多个 IP 地址 或 CIDR 范围,可以使用类似 10.10.10.0/24 的 CIDR 表示法。 + +**属性** + +| 参数名 | 类型 | 可选项 | 默认值 | 有效值 | 描述 | +| --------- | ------------- | ------ | ------ | ------ | -------------------------------- | +| ip_whitelist | array[string] | 可选 | | | 加入白名单的 IP 地址或 CIDR 范围 | +| ip_blacklist | array[string] | 可选 | | | 加入黑名单的 IP 地址或 CIDR 范围 | + +只能单独启用白名单或黑名单,两个不能一起使用。 +详细参考文档和代码 `https://github.com/apache/apisix/edit/master/docs/zh/latest/plugins/ip-restriction.md` + +##### cors跨域处理 +**属性** + +| 名称 | 类型 | 可选项 | 默认值 | 有效值 | 描述 | +| ---------------- | ------- | ------ | ------ | ------ | ------------------------------------------------------------ | +| allow_origins | string | 可选 | "*" | | 允许跨域访问的 Origin,格式如:`scheme`://`host`:`port`,比如: https://somehost.com:8081 。多个值使用 `,` 分割,`allow_credential` 为 `false` 时可以使用 `*` 来表示所有 Origin 均允许通过。你也可以在启用了 `allow_credential` 后使用 `**` 强制允许所有 Origin 都通过,但请注意这样存在安全隐患。 | +| allow_methods | string | 可选 | "*" | | 允许跨域访问的 Method,比如: `GET`,`POST`等。多个值使用 `,` 分割,`allow_credential` 为 `false` 时可以使用 `*` 来表示所有 Origin 均允许通过。你也可以在启用了 `allow_credential` 后使用 `**` 强制允许所有 Method 都通过,但请注意这样存在安全隐患。 | +| allow_headers | string | 可选 | "*" | | 允许跨域访问时请求方携带哪些非 `CORS规范` 以外的 Header, 多个值使用 `,` 分割,`allow_credential` 为 `false` 时可以使用 `*` 来表示所 有 Header 均允许通过。你也可以在启用了 `allow_credential` 后使用 `**` 强制允许所有 Method 都通过,但请注意这样存在安全隐患。 | +| expose_headers | string | 可选 | "*" | | 允许跨域访问时响应方携带哪些非 `CORS规范` 以外的 Header, 多个值使用 `,` 分割。 | +| max_age | integer | 可选 | 600 | | 浏览器缓存 CORS 结果的最大时间,单位为秒,在这个时间范围内浏览器会复用上一次的检查结果,`-1` 表示不缓存。请注意各个浏览器允许的的最大时间不同,详情请参考 [MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age#Directives)。 | +| allow_credential | boolean | 可选 | false | | 是否允许跨域访问的请求方携带凭据(如 Cookie 等)。根据 CORS 规范,如果设置该选项为 `true`,那么将不能在其他选项中使用 `*`。 | + +> **提示** +> +> 请注意 `allow_credential` 是一个很敏感的选项,谨慎选择开启。开启之后,其他参数默认的 `*` 将失效,你必须显式指定它们的值。 +> 使用 `**` 时要充分理解它引入了一些安全隐患,比如 CSRF,所以确保这样的安全等级符合自己预期再使用。 +参考文档和代码 `https://github.com/apache/apisix/blob/master/docs/zh/latest/plugins/cors.md` + +## 控制面板 +http://localhost:8888/dashboard + + +## 鸣谢 + +- [ws-cloud-gateway](https://github.com/tech-microworld/ws-cloud-gateway) +- [apisix](https://github.com/apache/apisix) + +## 协议 + +[GPL v3.0](https://www.gnu.org/licenses/gpl-3.0.html). diff --git a/benchmark/flame.sh b/benchmark/flame.sh new file mode 100644 index 0000000..2c0bf62 --- /dev/null +++ b/benchmark/flame.sh @@ -0,0 +1,46 @@ +#! /bin/bash -x + +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + + +home=$(dirname $(pwd)) + +echo $home + +stapxx_home=$home/.travis/stapxx +flame_graph_home=$home/.travis/FlameGraph +toolkit_home=$home/.travis/openresty-systemtap-toolkit + +export PATH=${stapxx_home}:${flame_graph_home}:${toolkit_home}:$PATH + +pid=$(ps -ef | grep nginx | grep 'worker process' | awk 'NR==1{print $2}') + +out=out + +mkdir -p $out + +$stapxx_home/samples/lj-lua-stacks.sxx --arg time=5 --skip-badvars -x $pid > $out/tmp.bt +# 处理 lj-lua-stacks.sxx 的输出,使其可读性更佳 +$toolkit_home/fix-lua-bt $out/tmp.bt > $out/flame.bt + +$flame_graph_home/stackcollapse-stap.pl $out/flame.bt > $out/flame.cbt + +$flame_graph_home/flamegraph.pl --encoding="ISO-8859-1" \ + --title="Lua-land on-CPU flamegraph" \ + $out/flame.cbt > $out/flame.svg + diff --git a/benchmark/run-wrk.sh b/benchmark/run-wrk.sh new file mode 100644 index 0000000..a36bf57 --- /dev/null +++ b/benchmark/run-wrk.sh @@ -0,0 +1,46 @@ +#! /bin/bash -x + +sleep 1 + +token=e09d6153f1c15395397be3639d144794 + +curl http://127.0.0.1:8888/admin/routes/save -H "X-Api-Token: ${token}" -X POST -d ' +{ + "key": "/innerapi/hello/*", + "protocol": "http", + "remark": "", + "prefix": "/innerapi/hello/*", + "service_name": "hello", + "status": 1, + "plugins": [ + "discovery", + "tracing", + "rewrite" + ], + "props": { + "rewrite_url_regex": "^/innerapi/(.*)/", + "rewrite_replace": "/" + } +}' + +echo + +curl http://127.0.0.1:8888/admin/services/save -H "X-Api-Token: ${token}" -X POST -d ' +{ + "key": "/hello/127.0.0.1:8080", + "service_name": "hello", + "upstream": "127.0.0.1:8080", + "weight": 1, + "status": 1 +}' + +echo + +sleep 2 +echo 'benchmark start' + +mkdir -p out +wrk -d 5 -c 16 --latency http://127.0.0.1:8888/innerapi/hello/api > out/wrk.out + +cat out/wrk.out +echo 'benchmark end' diff --git a/benchmark/server/conf/nginx.conf b/benchmark/server/conf/nginx.conf new file mode 100644 index 0000000..2359e9a --- /dev/null +++ b/benchmark/server/conf/nginx.conf @@ -0,0 +1,97 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +master_process on; + +worker_processes 1; + +error_log logs/error.log error; +pid logs/nginx.pid; + +worker_rlimit_nofile 20480; + +events { + accept_mutex off; + worker_connections 10620; +} + +worker_shutdown_timeout 3; + +http { + server { + listen 8080; + access_log off; + location / { + echo "benchmark server"; + } + } + + server { + listen 1024; + server_name _; + + location ~ ^/openapi/(.*) { + echo "demo1 service 1024 open-api"; + } + + location / { + echo "demo1 service 1024 inner-api"; + } + } + + server { + listen 1025; + server_name _; + + location ~ ^/openapi/(.*) { + echo "demo1 service 1025 open-api"; + } + + location / { + echo "demo1 service 1025 inner-api"; + } + + } + + server { + listen 1026; + server_name _; + + location ~ ^/openapi/(.*) { + echo "demo2 service 1026 open-api"; + } + + location / { + echo "demo2 service 1026 inner-api"; + } + + } + + server { + listen 1027; + server_name _; + + location ~ ^/openapi/(.*) { + echo "demo2 service 1027 open-api"; + } + + location / { + echo "demo2 service 1027 inner-api"; + } + + } + +} diff --git a/bin/check-lua-code-style.sh b/bin/check-lua-code-style.sh new file mode 100644 index 0000000..48bffb1 --- /dev/null +++ b/bin/check-lua-code-style.sh @@ -0,0 +1,37 @@ +#!/bin/sh + +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +set -ex + +luacheck -q gateway + +./bin/lj-releng \ + gateway/admin/*.lua \ + gateway/app/core/*.lua \ + gateway/app/plugins/*.lua \ + gateway/app/store/*.lua \ + gateway/app/utils/*.lua > \ + /tmp/check.log 2>&1 || (cat /tmp/check.log && exit 1) + +grep -E "ERROR.*.lua:" /tmp/check.log > /tmp/error.log | true +if [ -s /tmp/error.log ]; then + echo "=====bad style=====" + cat /tmp/check.log + exit 1 +fi diff --git a/bin/init_app.sh b/bin/init_app.sh new file mode 100644 index 0000000..d4942ef --- /dev/null +++ b/bin/init_app.sh @@ -0,0 +1,116 @@ +#! /bin/bash -x + +sleep 1 + +token=e09d6153f1c15395397be3639d144794 +mg_addr='127.0.0.1:8010' +## 管理后台 + + +echo +curl http://127.0.0.1:8888/api/admin/routes/save -H "X-Api-Token: ${token}" -X POST -d ' +{ + "key": "/api/mg/*", + "protocol": "http", + "remark": "", + "prefix": "/api/mg/*", + "service_name": "mg", + "status": 1, + "plugins": [ + "discovery", + "tracing", + "rewrite" + ], + "props": { + "rewrite_url_regex": "^/api/mg/", + "rewrite_replace": "/" + } +}' +### 鉴权 +curl http://127.0.0.1:8888/api/admin/routes/save -H "X-Api-Token: ${token}" -X POST -d ' +{ + "key": "/api/accounts/authorization/", + "protocol": "http", + "remark": "鉴权", + "prefix": "/api/accounts/authorization/", + "service_name": "mg", + "status": 1, + "plugins": [ + "discovery", + "tracing", + "limit-req", + "rewrite" + ], + "props": { + "limit_req_rate": 5, + "rewrite_replace": "/", + "rewrite_url_regex": "^/api/", + "limit_req_burst": 5 + } +}' + +echo + +### 登录 +curl http://127.0.0.1:8888/api/admin/routes/save -H "X-Api-Token: ${token}" -X POST -d ' +{ + "key": "/api/accounts/login/", + "protocol": "http", + "remark": "登录", + "prefix": "/api/accounts/login/", + "service_name": "mg", + "status": 1, + "plugins": [ + "discovery", + "tracing", + "limit-req", + "rewrite" + ], + "props": { + "limit_req_rate": 5, + "rewrite_replace": "/", + "rewrite_url_regex": "^/api/", + "limit_req_burst": 5 + } +}' + +echo + + + +echo + + + +curl http://127.0.0.1:8888/api/admin/routes/save -H "X-Api-Token: ${token}" -X POST -d ' +{ + "key": "/api/mg/*", + "protocol": "http", + "remark": "", + "prefix": "/api/mg/*", + "service_name": "mg", + "status": 1, + "plugins": [ + "discovery", + "tracing", + "rewrite", + "auth-rbac" + ], + "props": { + "rewrite_url_regex": "^/api/mg/", + "rewrite_replace": "/" + } +}' + +echo + + +curl http://127.0.0.1:8888/api/admin/services/save -H "X-Api-Token: ${token}" -X POST -d " +{ + \"key\": \"/mg/${mg_addr}\", + \"service_name\": \"mg\", + \"upstream\": \"${mg_addr}\", + \"weight\": 1, + \"status\": 1 +}" +echo diff --git a/bin/init_etcd.sh b/bin/init_etcd.sh new file mode 100644 index 0000000..92437c2 --- /dev/null +++ b/bin/init_etcd.sh @@ -0,0 +1,4 @@ +#!/bin/bash + +value='{"status":1,"key":"\/api\/p\/*","props":{"rewrite_url_regex":"^\/api\/p\/","rewrite_replace":"\/"},"service_name":"mg","time":1694490078055,"protocol":"http","_rowKey":13,"remark":"PAAS平台","plugins":["discovery","rewrite","redis-logger","CRBAC"],"prefix":"\/api\/p\/*","propsData":{"rewrite_url_regex":"^\/api\/p\/","rewrite_replace":"\/"}}' +etcdctl put '/my2/gw/routes/api/p/*' "$value" diff --git a/bin/travis-runner.sh b/bin/travis-runner.sh new file mode 100644 index 0000000..f413088 --- /dev/null +++ b/bin/travis-runner.sh @@ -0,0 +1,155 @@ +#! /bin/bash + +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +set -ex + +export_or_prefix() { + export OPENRESTY_PREFIX="/usr/local/openresty-debug" + export PATH=$OPENRESTY_PREFIX/nginx/sbin:$OPENRESTY_PREFIX/luajit/bin:$OPENRESTY_PREFIX/bin:$PATH + export GO111MOUDULE=on + export ETCDCTL_API=3 + export ETCD_BUILD_DIR=build-cache/etcd + export ETCD_BIN_DIR=${ETCD_BUILD_DIR}/bin + echo $PATH + echo $GOPATH + echo $GOROOT +} + +show_server_info() { + lscpu + free -h +} + +install_etcd() { + export_or_prefix + ETCD_VER=v3.4.14 + + if [ ! -f "${ETCD_BIN_DIR}/etcd" ]; then + mkdir -p ${ETCD_BIN_DIR} + # choose either URL + # GOOGLE_URL=https://storage.googleapis.com/etcd + GITHUB_URL=https://github.com/etcd-io/etcd/releases/download + DOWNLOAD_URL=${GITHUB_URL} + + curl -L ${DOWNLOAD_URL}/${ETCD_VER}/etcd-${ETCD_VER}-linux-amd64.tar.gz -o ${BUILD_DIR}/etcd-${ETCD_VER}-linux-amd64.tar.gz + tar xzvf $ETCD_BUILD_DIR/etcd-${ETCD_VER}-linux-amd64.tar.gz -C ${ETCD_BIN_DIR} --strip-components=1 + rm -f $ETCD_BUILD_DIR/etcd-${ETCD_VER}-linux-amd64.tar.gz + fi + + ${ETCD_BIN_DIR}/etcd --version + ${ETCD_BIN_DIR}/etcdctl version + # start etcd server + nohup ${ETCD_BIN_DIR}/etcd > etcd.log 2>&1 & + sleep 3 + + ${ETCD_BIN_DIR}/etcdctl --endpoints=localhost:2379 put foo bar + ${ETCD_BIN_DIR}/etcdctl --endpoints=localhost:2379 get foo +} + + +install_lua_deps() { + export_or_prefix + echo "install lua deps" + + make deps + luarocks install luacov-coveralls --tree=deps --local > build.log 2>&1 || (cat build.log && exit 1) + +} + +before_install() { + show_server_info + sudo cpanm --notest Test::Nginx >build.log 2>&1 || (cat build.log && exit 1) + sleep 1 +} + +do_install() { + wget -qO - https://openresty.org/package/pubkey.gpg | sudo apt-key add - + sudo apt-get -y update --fix-missing + sudo apt-get -y install software-properties-common + sudo add-apt-repository -y "deb http://openresty.org/package/ubuntu $(lsb_release -sc) main" + sudo add-apt-repository -y ppa:longsleep/golang-backports + sudo apt-get update + sudo apt-get install openresty-debug openresty-resty golang-go + + lua_version=lua-5.3.5 + if [ ! -f "build-cache/${lua_version}" ]; then + cd build-cache + curl -R -O http://www.lua.org/ftp/${lua_version}.tar.gz + tar -zxf ${lua_version}.tar.gz + cd .. + fi + cd build-cache/${lua_version} + make linux test + sudo make install + cd ../../ + + luarocks_version=luarocks-3.3.1 + if [ ! -f "build-cache/${luarocks_version}" ]; then + cd build-cache + wget https://luarocks.org/releases/${luarocks_version}.tar.gz + tar zxpf ${luarocks_version}.tar.gz + cd .. + fi + cd build-cache/${luarocks_version} + ./configure --prefix=/usr > build.log 2>&1 || (cat build.log && exit 1) + make build > build.log 2>&1 || (cat build.log && exit 1) + sudo make install > build.log 2>&1 || (cat build.log && exit 1) + cd ../../ + + sudo luarocks install luacheck > build.log 2>&1 || (cat build.log && exit 1) + + install_etcd + install_lua_deps + +} + +script() { + export_or_prefix + + make clean + make verify + sleep 1 + make benchmark + ${ETCD_BIN_DIR}/etcdctl --endpoints=localhost:2379 get '/my/cloud' --prefix +} + +after_success() { + # cat luacov.stats.out + # luacov-coveralls + # cat logs/error.log + tail -n50 logs/error.log +} + +case_opt=$1 +shift + +case ${case_opt} in +before_install) + before_install "$@" + ;; +do_install) + do_install "$@" + ;; +script) + script "$@" + ;; +after_success) + after_success "$@" + ;; +esac diff --git a/conf/app.json b/conf/app.json new file mode 100644 index 0000000..e234b94 --- /dev/null +++ b/conf/app.json @@ -0,0 +1,60 @@ +{ + "appName": "codo-gateway", + "env": "prod", + "etcd": { + "http_host": "http://127.0.0.1:2379", + "data_prefix": "/codo/gw/" + }, + "jwt_auth": { + "key": "auth_key", + "token_secret": "yxLxQ0jGtmAhRT4RMMxRrXf" + }, + "codo_rbac": { + "key": "auth_key", + "token_secret": "yxLxQ0jGtmAhRT4RMMxRrXf" + }, + "plugins": [ + "default_plugin", + "discovery_plugin", + "tracing_plugin", + "rewrite_plugin", + "jwt_plugin", + "codo_rbac_plugin", + "kafka-logger", + "redis-logger", + "limit-req", + "referer-restriction", + "ip-restriction", + "cors_plugin" + ], + "plugins_config": { + "redis-logger": { + "host": "127.0.0.1", + "port": 6379, + "auth_pwd": "PuiJUnyKCSLhhRT4RMMxR", + "db": 11, + "alive_time": 604800, + "channel": "gw", + "full_log": "no" + } + }, + "admin": { + "jwt_secret": "yxLxQ0jGtmAhRT4RMMxRrXf", + "account": { + "admin": { + "password": "tainiubile", + "info": { + "roles": ["admin"], + "introduction": "I am a super administrator", + "avatar": "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif", + "name": "管理员" + } + } + } + }, + "tokens": { + "e09d6153f1c15395144794GtmAhRT4": { + "desc": "系统默认 api token" + } + } +} diff --git a/conf/common/gzip.conf b/conf/common/gzip.conf new file mode 100644 index 0000000..a530e4c --- /dev/null +++ b/conf/common/gzip.conf @@ -0,0 +1,8 @@ +gzip on; +gzip_min_length 1024; +gzip_comp_level 5; +gzip_buffers 8 16k; +gzip_http_version 1.0; +gzip_proxied any; +gzip_types text/plain application/javascript text/javascript application/x-javascript text/css; +gzip_vary on; \ No newline at end of file diff --git a/conf/common/logformat.conf b/conf/common/logformat.conf new file mode 100644 index 0000000..d130a32 --- /dev/null +++ b/conf/common/logformat.conf @@ -0,0 +1,13 @@ +log_format json_log '{"@timestamp":"$time_iso8601","domain":"$host","method":"$request_method",' + '"upstream-cache-status":"$upstream_cache_status",' + '"uri":"$uri","origin-uri":"$origin_uri","querystring":"$args","protocol":"$server_protocol","httpcode":$status,' + '"bytes":$body_bytes_sent,"referer":"$http_referer","useragent":"$http_user_agent",' + '"xff":"$http_x_forwarded_for","client":"$remote_addr","upstream":"$upstream_addr","trace-id":"$http_x_trace_id",' + '"upstream-status":"$upstream_status","upstream-time":"$upstream_response_time","response-time":$request_time,"service":"$target_service_name"}'; + +log_format admin_log '{"@timestamp":"$time_iso8601","domain":"$host","method":"$request_method",' + '"upstream-cache-status":"$upstream_cache_status",' + '"uri":"$uri","querystring":"$args","protocol":"$server_protocol","httpcode":$status,' + '"bytes":$body_bytes_sent,"referer":"$http_referer","useragent":"$http_user_agent",' + '"xff":"$http_x_forwarded_for","client":"$remote_addr","upstream":"$upstream_addr",' + '"upstream-status":"$upstream_status","upstream-time":"$upstream_response_time","response-time":$request_time}'; diff --git a/conf/common/phase.conf b/conf/common/phase.conf new file mode 100644 index 0000000..26575d3 --- /dev/null +++ b/conf/common/phase.conf @@ -0,0 +1,20 @@ +access_by_lua_block { + local app = require("app") + app.http_access() +} +content_by_lua_block { + local app = require("app") + app.http_content() +} +header_filter_by_lua_block { + local app = require("app") + app.http_header_filter() +} +body_filter_by_lua_block { + local app = require("app") + app.http_body_filter() +} +log_by_lua_block { + local app = require("app") + app.http_log() +} diff --git a/conf/common/proxy.conf b/conf/common/proxy.conf new file mode 100644 index 0000000..c1fc777 --- /dev/null +++ b/conf/common/proxy.conf @@ -0,0 +1,30 @@ +proxy_http_version 1.1; +proxy_set_header Upgrade $http_upgrade; +proxy_set_header Connection "upgrade"; +### 跨域 +#add_header Access-Control-Allow-Methods *; +#add_header Access-Control-Max-Age 3600; +#add_header Access-Control-Allow-Credentials true; +#add_header Access-Control-Allow-Origin * always; +#add_header Access-Control-Allow-Headers $http_access_control_request_headers; +#if ($request_method = OPTIONS){ +# return 204;} +### +proxy_redirect off; +proxy_set_header Host $host; +proxy_set_header X-Real-IP $remote_addr; +proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; +proxy_set_header X-Forwarded-Proto $scheme; +proxy_set_header Accept-Encoding 'gzip'; +client_max_body_size 500m; +client_body_buffer_size 512k; +proxy_connect_timeout 500; +proxy_send_timeout 2000; +proxy_read_timeout 2000; +proxy_ignore_client_abort on; + +proxy_buffer_size 128k; +proxy_buffers 4 256k; +proxy_busy_buffers_size 256k; +proxy_temp_file_write_size 256k; + diff --git a/conf/mime.types b/conf/mime.types new file mode 100644 index 0000000..3437f2f --- /dev/null +++ b/conf/mime.types @@ -0,0 +1,89 @@ + +types { + text/html html htm shtml; + text/css css; + text/xml xml; + image/gif gif; + image/jpeg jpeg jpg; + application/javascript js; + application/atom+xml atom; + application/rss+xml rss; + + text/mathml mml; + text/plain txt; + text/vnd.sun.j2me.app-descriptor jad; + text/vnd.wap.wml wml; + text/x-component htc; + + image/png png; + image/tiff tif tiff; + image/vnd.wap.wbmp wbmp; + image/x-icon ico; + image/x-jng jng; + image/x-ms-bmp bmp; + image/svg+xml svg svgz; + image/webp webp; + + application/font-woff woff; + application/java-archive jar war ear; + application/json json; + application/mac-binhex40 hqx; + application/msword doc; + application/pdf pdf; + application/postscript ps eps ai; + application/rtf rtf; + application/vnd.apple.mpegurl m3u8; + application/vnd.ms-excel xls; + application/vnd.ms-fontobject eot; + application/vnd.ms-powerpoint ppt; + application/vnd.wap.wmlc wmlc; + application/vnd.google-earth.kml+xml kml; + application/vnd.google-earth.kmz kmz; + application/x-7z-compressed 7z; + application/x-cocoa cco; + application/x-java-archive-diff jardiff; + application/x-java-jnlp-file jnlp; + application/x-makeself run; + application/x-perl pl pm; + application/x-pilot prc pdb; + application/x-rar-compressed rar; + application/x-redhat-package-manager rpm; + application/x-sea sea; + application/x-shockwave-flash swf; + application/x-stuffit sit; + application/x-tcl tcl tk; + application/x-x509-ca-cert der pem crt; + application/x-xpinstall xpi; + application/xhtml+xml xhtml; + application/xspf+xml xspf; + application/zip zip; + + application/octet-stream bin exe dll; + application/octet-stream deb; + application/octet-stream dmg; + application/octet-stream iso img; + application/octet-stream msi msp msm; + + application/vnd.openxmlformats-officedocument.wordprocessingml.document docx; + application/vnd.openxmlformats-officedocument.spreadsheetml.sheet xlsx; + application/vnd.openxmlformats-officedocument.presentationml.presentation pptx; + + audio/midi mid midi kar; + audio/mpeg mp3; + audio/ogg ogg; + audio/x-m4a m4a; + audio/x-realaudio ra; + + video/3gpp 3gpp 3gp; + video/mp2t ts; + video/mp4 mp4; + video/mpeg mpeg mpg; + video/quicktime mov; + video/webm webm; + video/x-flv flv; + video/x-m4v m4v; + video/x-mng mng; + video/x-ms-asf asx asf; + video/x-ms-wmv wmv; + video/x-msvideo avi; +} \ No newline at end of file diff --git a/conf/nginx.conf b/conf/nginx.conf new file mode 100644 index 0000000..0b18b4d --- /dev/null +++ b/conf/nginx.conf @@ -0,0 +1,78 @@ +# nginx + +pid logs/nginx.pid; +# 开发时可以设置成 debug +error_log logs/error.log error; + +master_process on; + +# 生产环境设置成 auto +worker_processes 4; + +# 最大文件描述符数量 +worker_rlimit_nofile 20240; +worker_rlimit_core 4G; +# 工作进程关闭超时时间 +worker_shutdown_timeout 3; + +events { + accept_mutex off; + worker_connections 20240; +} + +http { + + include mime.types; + default_type application/json; + + include common/logformat.conf; + + server_tokens off; + more_set_headers 'Server: CODO-GateWay'; + + sendfile on; + tcp_nopush on; + # aio on; + + #keepalive_timeout 0; + client_max_body_size 0; + keepalive_timeout 60s; + client_header_timeout 60s; + client_body_timeout 60s; + send_timeout 10s; + + # 避免正则回溯问题 + lua_regex_match_limit 100000; + lua_regex_cache_max_entries 8192; + + lua_http10_buffering off; + + # 全局缓存定义 + lua_shared_dict upstream_type_cache 1m; + lua_shared_dict timer_lock 1m; + lua_shared_dict lrucache_lock 10m; + lua_shared_dict user_info 500k; + lua_shared_dict my_limit_conn_store 100m; + + #最大等待任务数 + lua_max_pending_timers 1024; + #最大同时运行任务数 + lua_max_running_timers 256; + + + #lua库依赖路径 + lua_package_path "${prefix}deps/share/lua/5.1/?.lua;${prefix}deps/share/lua/5.1/?/init.lua;${prefix}gateway/?.lua;${prefix}gateway/?/init.lua;;"; + lua_package_cpath "${prefix}deps/lib64/lua/5.1/?.so;${prefix}deps/lib/lua/5.1/?.so;;"; + + #初始化脚本 + # init_by_lua_block { + # local app = require("app") + # app.http_init() + + # } + init_by_lua_file gateway/init_by_lua.lua; + init_worker_by_lua_file gateway/init_worker_by_lua.lua; + + include common/gzip.conf; + include servers/*.conf; +} diff --git a/conf/servers/demo1_1024.conf b/conf/servers/demo1_1024.conf new file mode 100644 index 0000000..a7afd6d --- /dev/null +++ b/conf/servers/demo1_1024.conf @@ -0,0 +1,12 @@ +server { + listen 1024; + server_name _; + + location ~ ^/openapi/(.*) { + echo "demo1 service 1024 open-api"; + } + + location / { + echo "demo1 service 1024 inner-api"; + } +} \ No newline at end of file diff --git a/conf/servers/demo1_1025.conf b/conf/servers/demo1_1025.conf new file mode 100644 index 0000000..009a87e --- /dev/null +++ b/conf/servers/demo1_1025.conf @@ -0,0 +1,12 @@ +server { + listen 1025; + server_name _; + + location ~ ^/openapi/(.*) { + echo "demo1 service 1025 open-api"; + } + + location / { + echo "demo1 service 1025 inner-api"; + } +} \ No newline at end of file diff --git a/conf/servers/gateway.conf b/conf/servers/gateway.conf new file mode 100644 index 0000000..5e04e44 --- /dev/null +++ b/conf/servers/gateway.conf @@ -0,0 +1,71 @@ + +server { + listen 8888 reuseport; + listen 11000 http2 reuseport; + server_name _; + + access_log logs/gateway-access.log json_log; + + location = /nginx_status { + allow 127.0.0.1; + allow 192.168.0.0/16; + allow 10.10.8.0/24; + deny all; + access_log off; + stub_status; + } + + location /api/admin/ { + access_log logs/admin-access.log admin_log; + + allow 127.0.0.1; + allow 192.168.0.0/16; + allow 10.10.8.0/24; + + allow 172.17.0.0/24; + #deny all; + + content_by_lua_block { + local admin = require("admin") + admin.http_admin() + } + } + + location / { + include common/proxy.conf; + set $target_service_name ''; + set $origin_uri $uri; + lua_code_cache on; + rewrite_by_lua_block { + local app = require("app") + app.http_rewrite() + } + include common/phase.conf; + proxy_pass http://backend_server; + } + + location @grpc_pass { + grpc_set_header Content-Type application/grpc; + grpc_socket_keepalive on; + + rewrite_by_lua_block { + local app = require("app") + app.grpc_rewrite() + } + include common/phase.conf; + grpc_pass grpc://backend_server; + } + +} + +upstream backend_server { + # just an invalid address as a place holder + server 0.0.0.0; + balancer_by_lua_block { + local app = require("app") + app.http_balancer() + } + # connection pool + keepalive 100; + keepalive_timeout 60s; +} diff --git a/debug.sh b/debug.sh new file mode 100644 index 0000000..3c7f1ab --- /dev/null +++ b/debug.sh @@ -0,0 +1,84 @@ +### + # @Author: cA7dEm0n + # @Blog: http://www.a-cat.cn + # @Since: 2020-12-30 17:14:05 + # @Motto: 欲目千里,更上一层 + # @message: 本地DEBUG测试 +### + +SCRIPT_DIR=$(cd $(dirname ${BASH_SOURCE[0]}); pwd) +POD_NAME="gateway" +IMAGE_NAME="code/gateway" + +run() { + docker ps |grep -q ${POD_NAME} && exit 0 + docker run -d -p 8888:8888 \ + -v ${SCRIPT_DIR}/conf:/usr/local/openresty/nginx/conf \ + -v ${SCRIPT_DIR}/deps:/usr/local/openresty/nginx/deps/ \ + -v ${SCRIPT_DIR}/gateway:/usr/local/openresty/nginx/gateway/ \ + -v ${SCRIPT_DIR}/init:/usr/local/openresty/nginx/init/ \ + -v ${SCRIPT_DIR}/rockspec:/usr/local/openresty/nginx/rockspec/ \ + --name ${POD_NAME} ${IMAGE_NAME} +} + +log() { + docker logs -f ${POD_NAME} +} + +stop() { + docker stop ${POD_NAME} +} + +start() { + docker start ${POD_NAME} +} + +rm_() { + docker rm ${POD_NAME} +} + +reload() { + docker exec ${POD_NAME} /usr/local/openresty/bin/openresty -s reload +} + +init_services() { + local token=$1 + curl http://127.0.0.1:8888/api/mg/admin/services/save -H "X-Api-Token: ${token}" -X POST -d' + { + "service_name": "demo1", + "upstream": "127.0.0.1:1024", + "weight": 1, + "status": 1 + }' +} + +init_routes() { + local token=$1 + curl http://127.0.0.1:8888/api/mg/admin/routes/save -H "X-Api-Token: ${token}" -X POST -d ' +{ + "prefix": "/openapi/demo1/*", + "status": 1, + "service_name": "demo1", + "protocol": "http", + "plugins": ["discovery", "tracing", "rewrite", "redis-logger"], + "props": { + "rewrite_url_regex": "^/openapi/(.*)/", + "rewrite_replace": "/openapi/" + } +}' +} + + +init() { + token=e09d6153f1c15395397be3639d144794 + # curl http://127.0.0.1:8888/api/mg/admin/plugins/list -H "X-Api-Token: e09d6153f1c15395397be3639d144794" + init_services ${token} + init_routes ${token} +} + +restart() { + stop + start +} + +$* diff --git a/deps/lib64/lua/5.1/lfs.so b/deps/lib64/lua/5.1/lfs.so new file mode 100644 index 0000000..9cd0a2c Binary files /dev/null and b/deps/lib64/lua/5.1/lfs.so differ diff --git a/deps/lib64/lua/5.1/librestychash.so b/deps/lib64/lua/5.1/librestychash.so new file mode 100644 index 0000000..8c767dd Binary files /dev/null and b/deps/lib64/lua/5.1/librestychash.so differ diff --git a/deps/lib64/lua/5.1/librestyradixtree.so b/deps/lib64/lua/5.1/librestyradixtree.so new file mode 100644 index 0000000..6a7a378 Binary files /dev/null and b/deps/lib64/lua/5.1/librestyradixtree.so differ diff --git a/deps/lib64/lua/5.1/lpeg.so b/deps/lib64/lua/5.1/lpeg.so new file mode 100644 index 0000000..ff15c92 Binary files /dev/null and b/deps/lib64/lua/5.1/lpeg.so differ diff --git a/deps/lib64/lua/5.1/pb.so b/deps/lib64/lua/5.1/pb.so new file mode 100644 index 0000000..7a8f791 Binary files /dev/null and b/deps/lib64/lua/5.1/pb.so differ diff --git a/deps/lib64/luarocks/rocks/base64/1.5-2/base64-1.5-2.rockspec b/deps/lib64/luarocks/rocks/base64/1.5-2/base64-1.5-2.rockspec new file mode 100644 index 0000000..7d0addd --- /dev/null +++ b/deps/lib64/luarocks/rocks/base64/1.5-2/base64-1.5-2.rockspec @@ -0,0 +1,20 @@ +package = "base64" +version = "1.5-2" +source = { + url = "git://github.com/iskolbin/lbase64", + tag = "v1.5.2", +} +description = { + summary = "Pure Lua base64 encoder/decoder", + detailed = [[ +Pure Lua [base64](https://en.wikipedia.org/wiki/Base64) encoder/decoder. Works with Lua 5.1+ and LuaJIT. Fallbacks to pure Lua bit operations if bit/bit32/native bit operators are not available.]], + homepage = "https://github.com/iskolbin/lbase64", + license = "MIT/Public Domain" +} +dependencies = {} +build = { + type = "builtin", + modules = { + base64 = "base64.lua", + } +} diff --git a/deps/lib64/luarocks/rocks/base64/1.5-2/doc/README.md b/deps/lib64/luarocks/rocks/base64/1.5-2/doc/README.md new file mode 100644 index 0000000..83cde7b --- /dev/null +++ b/deps/lib64/luarocks/rocks/base64/1.5-2/doc/README.md @@ -0,0 +1,42 @@ +[![Build Status](https://travis-ci.org/iskolbin/lbase64.svg?branch=master)](https://travis-ci.org/iskolbin/lbase64) +[![license](https://img.shields.io/badge/license-public%20domain-blue.svg)]() +[![MIT Licence](https://badges.frapsoft.com/os/mit/mit.svg?v=103)](https://opensource.org/licenses/mit-license.php) + +Lua base64 encoder/decoder +========================== + +Pure Lua [base64](https://en.wikipedia.org/wiki/Base64) encoder/decoder. Works with +Lua 5.1+ and LuaJIT. Fallbacks to pure Lua bit operations if bit/bit32/native bit +operators are not available. + +```lua +local base64 = require'base64' +local str = 'Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.' +local b64str = 'TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=' +local encoded = base64.encode( str ) +local decoded = base64.decode( b64str ) +assert( str == decoded ) +assert( b64str == encoded ) +``` + +base64.encode( str, encoder = DEFAULT, usecache = false ) +--------------------------------------------------------- +Encodes `str` string using `encoder` table. By default uses table with `+` as +char for 62, `/` as char for 63 and `=` as padding char. You can specify custom +encoder. For this you could use `base64.makeencoder`. If you are encoding large +chunks of text (or another highly redundant data) it's possible to highly +increase performace (for text approx. x2 gain) by using `usecache = true`. For +binary data like images using cache decreasing performance. + +base64.decode( str, decoder = DEFAULT, usecache = false ) +--------------------------------------------------------- +Decodes `str` string using `decoder` table. Default decoder uses same chars as +default encoder. + +base64.makeencoder( s62 = '+', s63 = '/', spad = '=' ) +------------------------------------------------------ +Make custom encoding table + +base64.makedecoder( s62 = '+', s63 = '/', spad = '=' ) +------------------------------------------------------ +Make custom decoding table diff --git a/deps/lib64/luarocks/rocks/base64/1.5-2/rock_manifest b/deps/lib64/luarocks/rocks/base64/1.5-2/rock_manifest new file mode 100644 index 0000000..084114f --- /dev/null +++ b/deps/lib64/luarocks/rocks/base64/1.5-2/rock_manifest @@ -0,0 +1,9 @@ +rock_manifest = { + ["base64-1.5-2.rockspec"] = "67b8bddf62a15d0b16051e0fb3453cc8", + doc = { + ["README.md"] = "599676514d1744acc0c14c40c29b88e1" + }, + lua = { + ["base64.lua"] = "97d7fe1769cf8ab1766aef91d7f542ef" + } +} diff --git a/deps/lib64/luarocks/rocks/dkjson/2.5-2/dkjson-2.5-2.rockspec b/deps/lib64/luarocks/rocks/dkjson/2.5-2/dkjson-2.5-2.rockspec new file mode 100644 index 0000000..9a56ca1 --- /dev/null +++ b/deps/lib64/luarocks/rocks/dkjson/2.5-2/dkjson-2.5-2.rockspec @@ -0,0 +1,30 @@ +package = "dkjson" +version = "2.5-2" +source = { + url = "http://dkolf.de/src/dkjson-lua.fsl/tarball/dkjson-2.5.tar.gz?uuid=release_2_5", + file = "dkjson-2.5.tar.gz" +} +description = { + summary = "David Kolf's JSON module for Lua", + detailed = [[ +dkjson is a module for encoding and decoding JSON data. It supports UTF-8. + +JSON (JavaScript Object Notation) is a format for serializing data based +on the syntax for JavaScript data structures. + +dkjson is written in Lua without any dependencies, but +when LPeg is available dkjson uses it to speed up decoding. +]], + homepage = "http://dkolf.de/src/dkjson-lua.fsl/", + license = "MIT/X11" +} +dependencies = { + "lua >= 5.1, < 5.4" +} +build = { + type = "builtin", + modules = { + dkjson = "dkjson.lua" + } +} + diff --git a/deps/lib64/luarocks/rocks/dkjson/2.5-2/doc/readme.txt b/deps/lib64/luarocks/rocks/dkjson/2.5-2/doc/readme.txt new file mode 100644 index 0000000..7641e86 --- /dev/null +++ b/deps/lib64/luarocks/rocks/dkjson/2.5-2/doc/readme.txt @@ -0,0 +1,211 @@ +David Kolf's JSON module for Lua 5.1/5.2 +======================================== + +*Version 2.5* + +In the default configuration this module writes no global values, not even +the module table. Import it using + + json = require ("dkjson") + +In environments where `require` or a similiar function are not available +and you cannot receive the return value of the module, you can set the +option `register_global_module_table` to `true`. The module table will +then be saved in the global variable with the name given by the option +`global_module_name`. + +Exported functions and values: + +`json.encode (object [, state])` +-------------------------------- + +Create a string representing the object. `Object` can be a table, +a string, a number, a boolean, `nil`, `json.null` or any object with +a function `__tojson` in its metatable. A table can only use strings +and numbers as keys and its values have to be valid objects as +well. It raises an error for any invalid data types or reference +cycles. + +`state` is an optional table with the following fields: + + - `indent` + When `indent` (a boolean) is set, the created string will contain + newlines and indentations. Otherwise it will be one long line. + - `keyorder` + `keyorder` is an array to specify the ordering of keys in the + encoded output. If an object has keys which are not in this array + they are written after the sorted keys. + - `level` + This is the initial level of indentation used when `indent` is + set. For each level two spaces are added. When absent it is set + to 0. + - `buffer` + `buffer` is an array to store the strings for the result so they + can be concatenated at once. When it isn't given, the encode + function will create it temporary and will return the + concatenated result. + - `bufferlen` + When `bufferlen` is set, it has to be the index of the last + element of `buffer`. + - `tables` + `tables` is a set to detect reference cycles. It is created + temporary when absent. Every table that is currently processed + is used as key, the value is `true`. + - `exception` + When `exception` is given, it will be called whenever the encoder + cannot encode a given value. + The parameters are `reason`, `value`, `state` and `defaultmessage`. + `reason` is either `"reference cycle"`, `"custom encoder failed"` or + `"unsupported type"`. `value` is the original value that caused the + exception, `state` is this state table, `defaultmessage` is the message + of the error that would usually be raised. + You can either return `true` and add directly to the buffer or you can + return the string directly. To keep raising an error return `nil` and + the desired error message. + An example implementation for an exception function is given in + `json.encodeexception`. + +When `state.buffer` was set, the return value will be `true` on +success. Without `state.buffer` the return value will be a string. + +`json.decode (string [, position [, null]])` +-------------------------------------------- + +Decode `string` starting at `position` or at 1 if `position` was +omitted. + +`null` is an optional value to be returned for null values. The +default is `nil`, but you could set it to `json.null` or any other +value. + +The return values are the object or `nil`, the position of the next +character that doesn't belong to the object, and in case of errors +an error message. + +Two metatables are created. Every array or object that is decoded gets +a metatable with the `__jsontype` field set to either `array` or +`object`. If you want to provide your own metatables use the syntax + + json.decode (string, position, null, objectmeta, arraymeta) + +To prevent the assigning of metatables pass `nil`: + + json.decode (string, position, null, nil) + +`.__jsonorder` +------------------------- + +`__jsonorder` can overwrite the `keyorder` for a specific table. + +`.__jsontype` +------------------------ + +`__jsontype` can be either `"array"` or `"object"`. This value is only +checked for empty tables. (The default for empty tables is `"array"`). + +`.__tojson (self, state)` +------------------------------------ + +You can provide your own `__tojson` function in a metatable. In this +function you can either add directly to the buffer and return true, +or you can return a string. On errors nil and a message should be +returned. + +`json.null` +----------- + +You can use this value for setting explicit `null` values. + +`json.version` +-------------- + +Set to `"dkjson 2.5"`. + +`json.quotestring (string)` +--------------------------- + +Quote a UTF-8 string and escape critical characters using JSON +escape sequences. This function is only necessary when you build +your own `__tojson` functions. + +`json.addnewline (state)` +------------------------- + +When `state.indent` is set, add a newline to `state.buffer` and spaces +according to `state.level`. + +`json.encodeexception (reason, value, state, defaultmessage)` +------------------------------------------------------------- + +This function can be used as value to the `exception` option. Instead of +raising an error this function encodes the error message as a string. This +can help to debug malformed input data. + + x = json.encode(value, { exception = json.encodeexception }) + +LPeg support +------------ + +When the local configuration variable `always_try_using_lpeg` is set, +this module tries to load LPeg to replace the `decode` function. The +speed increase is significant. You can get the LPeg module at + . +When LPeg couldn't be loaded, the pure Lua functions stay active. + +In case you don't want this module to require LPeg on its own, +disable the option `always_try_using_lpeg` in the options section at +the top of the module. + +In this case you can later load LPeg support using + +### `json.use_lpeg ()` + +Require the LPeg module and replace the functions `quotestring` and +and `decode` with functions that use LPeg patterns. +This function returns the module table, so you can load the module +using: + + json = require "dkjson".use_lpeg() + +Alternatively you can use `pcall` so the JSON module still works when +LPeg isn't found. + + json = require "dkjson" + pcall (json.use_lpeg) + +### `json.using_lpeg` + +This variable is set to `true` when LPeg was loaded successfully. + +--------------------------------------------------------------------- + +Contact +------- + +You can contact the author by sending an e-mail to 'david' at the +domain 'dkolf.de'. + +--------------------------------------------------------------------- + +*Copyright (C) 2010-2013 David Heiko Kolf* + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/deps/lib64/luarocks/rocks/dkjson/2.5-2/rock_manifest b/deps/lib64/luarocks/rocks/dkjson/2.5-2/rock_manifest new file mode 100644 index 0000000..3df1d34 --- /dev/null +++ b/deps/lib64/luarocks/rocks/dkjson/2.5-2/rock_manifest @@ -0,0 +1,9 @@ +rock_manifest = { + ["dkjson-2.5-2.rockspec"] = "e8b0f6529f14a4c3b9ff4ba0487b9468", + doc = { + ["readme.txt"] = "c9106008411120074fb26c0f02085949" + }, + lua = { + ["dkjson.lua"] = "9b1adbcdfbf2c749af4f2c91182e8c06" + } +} diff --git a/deps/lib64/luarocks/rocks/graphql/0.0.2-1/doc/LICENSE b/deps/lib64/luarocks/rocks/graphql/0.0.2-1/doc/LICENSE new file mode 100644 index 0000000..306ae35 --- /dev/null +++ b/deps/lib64/luarocks/rocks/graphql/0.0.2-1/doc/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2015 Bjorn Swenson + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/deps/lib64/luarocks/rocks/graphql/0.0.2-1/doc/README.md b/deps/lib64/luarocks/rocks/graphql/0.0.2-1/doc/README.md new file mode 100644 index 0000000..e7df836 --- /dev/null +++ b/deps/lib64/luarocks/rocks/graphql/0.0.2-1/doc/README.md @@ -0,0 +1,105 @@ +GraphQL Lua [![Join the chat at https://gitter.im/bjornbytes/graphql-lua](https://badges.gitter.im/bjornbytes/graphql-lua.svg)](https://gitter.im/bjornbytes/graphql-lua?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +=== + +Lua implementation of GraphQL. + +Example +--- + +```lua +local parse = require 'graphql.parse' +local schema = require 'graphql.schema' +local types = require 'graphql.types' +local validate = require 'graphql.validate' +local execute = require 'graphql.execute' + +-- Parse a query +local ast = parse [[ +query getUser($id: ID) { + person(id: $id) { + firstName + lastName + } +} +]] + +-- Create a type +local Person = types.object { + name = 'Person', + fields = { + id = types.id.nonNull, + firstName = types.string.nonNull, + middleName = types.string, + lastName = types.string.nonNull, + age = types.int.nonNull + } +} + +-- Create a schema +local schema = schema.create { + query = types.object { + name = 'Query', + fields = { + person = { + kind = Person, + arguments = { + id = types.id + }, + resolve = function(rootValue, arguments) + if arguments.id ~= 1 then return nil end + + return { + id = 1, + firstName = 'Bob', + lastName = 'Ross', + age = 52 + } + end + } + } + } +} + +-- Validate a parsed query against a schema +validate(schema, ast) + +-- Execution +local rootValue = {} +local variables = { id = 1 } +local operationName = 'getUser' + +execute(schema, ast, rootValue, variables, operationName) + +--[[ +{ + person = { + firstName = 'Bob', + lastName = 'Ross' + } +} +]] +``` + +Status +--- + +- [x] Parsing + - [ ] Improve error messages +- [x] Type system +- [ ] Introspection +- [x] Validation +- [x] Execution + - [ ] Asynchronous execution (coroutines) +- [ ] Example server + +Running tests +--- + +```lua +lua tests/runner.lua +``` + +License +--- + +MIT diff --git a/deps/lib64/luarocks/rocks/graphql/0.0.2-1/graphql-0.0.2-1.rockspec b/deps/lib64/luarocks/rocks/graphql/0.0.2-1/graphql-0.0.2-1.rockspec new file mode 100644 index 0000000..e88d699 --- /dev/null +++ b/deps/lib64/luarocks/rocks/graphql/0.0.2-1/graphql-0.0.2-1.rockspec @@ -0,0 +1,34 @@ +package = 'graphql' +version = '0.0.2-1' + +source = { + url = 'git://github.com/bjornbytes/graphql-lua.git', + tag ='v0.0.2', +} + +description = { + summary = 'Lua GraphQL implementation', + homepage = 'https://github.com/bjornbytes/graphql-lua', + maintainer = 'https://github.com/bjornbytes', + license = 'MIT' +} + +dependencies = { + 'lua >= 5.1', + 'lpeg' +} + +build = { + type = 'builtin', + modules = { + ['graphql'] = 'graphql/init.lua', + ['graphql.parse'] = 'graphql/parse.lua', + ['graphql.types'] = 'graphql/types.lua', + ['graphql.introspection'] = 'graphql/introspection.lua', + ['graphql.schema'] = 'graphql/schema.lua', + ['graphql.validate'] = 'graphql/validate.lua', + ['graphql.rules'] = 'graphql/rules.lua', + ['graphql.execute'] = 'graphql/execute.lua', + ['graphql.util'] = 'graphql/util.lua' + } +} diff --git a/deps/lib64/luarocks/rocks/graphql/0.0.2-1/rock_manifest b/deps/lib64/luarocks/rocks/graphql/0.0.2-1/rock_manifest new file mode 100644 index 0000000..49d6ff9 --- /dev/null +++ b/deps/lib64/luarocks/rocks/graphql/0.0.2-1/rock_manifest @@ -0,0 +1,20 @@ +rock_manifest = { + doc = { + LICENSE = "d47729e1a926c24c4a378db9d8016fd9", + ["README.md"] = "5ca8d46ab3c6dfb0264c89c89b942429" + }, + ["graphql-0.0.2-1.rockspec"] = "ffbfb334ceb5d34efdf68c2ce167ff41", + lua = { + graphql = { + ["execute.lua"] = "87fcb0a9f841c5d016799517a1c44cb5", + ["init.lua"] = "106307a4661f7d5d3d530bbdea8eb7e2", + ["introspection.lua"] = "5684253a0e0a41e60a47e5afd6743056", + ["parse.lua"] = "445e4f252dddbf0218db91f4d4baa809", + ["rules.lua"] = "3dece2b014d6f754fd4ebb0d7fc72ae1", + ["schema.lua"] = "604fdf8ee61d5b87dcfea6f77d665a58", + ["types.lua"] = "c0bdd4b795eccdca0c76da7370b95246", + ["util.lua"] = "35927b296bb9321fcaf0240afe63b6ca", + ["validate.lua"] = "ebd55ce03a0d8b35d44006674b301b6d" + } + } +} diff --git a/deps/lib64/luarocks/rocks/jsonschema/0.9.3-0/doc/LICENSE b/deps/lib64/luarocks/rocks/jsonschema/0.9.3-0/doc/LICENSE new file mode 100644 index 0000000..751a5b4 --- /dev/null +++ b/deps/lib64/luarocks/rocks/jsonschema/0.9.3-0/doc/LICENSE @@ -0,0 +1,204 @@ +Copyright (c) 2019 ShenZhen ZhiLiu Technology Co., Ltd +Copyright (c) 2017 Julien Desgats + + 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/deps/lib64/luarocks/rocks/jsonschema/0.9.3-0/doc/README.md b/deps/lib64/luarocks/rocks/jsonschema/0.9.3-0/doc/README.md new file mode 100644 index 0000000..f87b4ae --- /dev/null +++ b/deps/lib64/luarocks/rocks/jsonschema/0.9.3-0/doc/README.md @@ -0,0 +1,115 @@ +jsonschema: JSON schema validator +=========================================== + +This library provides a JSON schema draft 4, draft 6, draft 7 validator for Lua/LuaJIT. +Note that even though it uses the JSON Schema semantics, it is neither bound or limited +to JSON. It can be used to validate saner key/value data formats as well (Lua +tables, msgpack, bencode, ...). + +It has been designed to validate incoming data for HTTP APIs so it is decently +fast: it works by transforming the given schema into a pure Lua function +on-the-fly. Work is currently in progress to make it as JIT-friendly as +possible. + +This project base on [ljsonschema](https://github.com/jdesgats/ljsonschema). Many thanks to the author `jdesgats` for the perfect work. The re-implementation is we need to support OpenResty env, +and we can use more optimization methods only available in OpenResty, which can make it run faster in OpenResty land. + +Installation +------------ + +This module is pure Lua/LuaJIT project, it support Lua 5.2, Lua 5.3, LuaJIT 2.1 beta. + +The preferred way to install this library is to use Luarocks: + + luarocks install jsonschema + +Running the tests: + + git submodule update --init --recursive + make dev + make test + +The project references the pcre regular library. + +If you were using the LuaJIT of OpenResty, it will use the built-in `ngx.re.find` automaticly. +But if you are using Lua 5.2, 5.3 or LuaJIT 2.1 beta, you will need to install `lrexlib-pcre`. + +In addition, the project also relies on the `net_url` library, which you need to install anyway. + +Usage +----- + +### Getting started + +```lua +local jsonschema = require 'jsonschema' + +-- Note: do cache the result of schema compilation as this is a quite +-- expensive process +local myvalidator = jsonschema.generate_validator { + type = 'object', + properties = { + foo = { type = 'string' }, + bar = { type = 'number' }, + }, +} + +print(myvalidator{ foo='hello', bar=42 }) +``` + +### Advanced usage + +Some advanced features of JSON Schema are not possible to implement using the +standard library and require third party libraries to be work. + +In order to not force one particular library, and not bloat this library for +the simple schemas, extension points are provided: the `generate_validator` +takes a second table argument that can be used to customise the generated +parser. + +```lua +local v = jsonschema.generate_validator(schema, { + -- a value used to check null elements in the validated documents + -- defaults to `cjson.null` (if available) or `nil` + null = null_token, + + -- function called to match patterns, defaults to `ngx.re.find` in OpenResty + -- or `rex.find` from lrexlib-pcre on other occassions. + -- The pattern given here will obey the ECMA-262 specification. + match_pattern = function(string, patt) + return ... -- boolean value + end, + + -- function called to resolve external schemas. It is called with the full + -- url to fetch (without the fragment part) and must return the + -- corresponding schema as a Lua table. + -- There is no default implementation: this function must be provided if + -- resolving external schemas is required. + external_resolver = function(url) + return ... -- Lua table + end, + + -- name when generating the validator function, it might ease debugging as + -- as it will appear in stack traces. + name = "myschema", +}) +``` + +Differences with JSONSchema +--------------------------- + +Due to the nature of the Lua language, the full JSON schema support is +difficult to reach. Some of the limitations can be solved using the advanced +options detailed previously, but some features are not supported (correctly) +at this time: + +* Empty tables and empty arrays are the same from Lua point of view + + +On the other hand, some extra features are supported: + +* The type `table` can be used to match arrays or objects, it is also much + faster than `array` or `object` as it does not involve walking the table to + find out if it's a sequence or a hash +* The type `function` can be used to check for functions + diff --git a/deps/lib64/luarocks/rocks/jsonschema/0.9.3-0/jsonschema-0.9.3-0.rockspec b/deps/lib64/luarocks/rocks/jsonschema/0.9.3-0/jsonschema-0.9.3-0.rockspec new file mode 100644 index 0000000..a702f7b --- /dev/null +++ b/deps/lib64/luarocks/rocks/jsonschema/0.9.3-0/jsonschema-0.9.3-0.rockspec @@ -0,0 +1,30 @@ +package = "jsonschema" +version = "0.9.3-0" +source = { + url = "git://github.com/api7/jsonschema.git", + tag = "v0.9.3", +} + +description = { + summary = "JSON Schema data validator", + detailed = [[ +This library provides a jsonschema draft 4, draft 6, draft 7 validator for Lua/LuaJIT. +Given an JSON schema, it will generates a validator function that can be used +to validate any kind of data (not limited to JSON). +Base on https://github.com/jdesgats/jsonschema . +]], + homepage = "https://github.com/iresty/jsonschema", + license = "MIT" +} + +dependencies = { + "net-url", +} + +build = { + type = "builtin", + modules = { + ["jsonschema"] = "lib/jsonschema.lua", + ["jsonschema.store"] = "lib/jsonschema/store.lua", + } +} diff --git a/deps/lib64/luarocks/rocks/jsonschema/0.9.3-0/rock_manifest b/deps/lib64/luarocks/rocks/jsonschema/0.9.3-0/rock_manifest new file mode 100644 index 0000000..00fb3fa --- /dev/null +++ b/deps/lib64/luarocks/rocks/jsonschema/0.9.3-0/rock_manifest @@ -0,0 +1,13 @@ +rock_manifest = { + doc = { + LICENSE = "8fc7c3a156caf74c7767ab8162ad6faa", + ["README.md"] = "170eafa93c6cc8218b3c1d48208e3d3e" + }, + ["jsonschema-0.9.3-0.rockspec"] = "affa03902c0b6306d6ef4794f3a8632e", + lua = { + jsonschema = { + ["store.lua"] = "0602b893b6e6ed1db5e102a2173dec95" + }, + ["jsonschema.lua"] = "27c3549145c72576ddca8bbb89a07b70" + } +} diff --git a/deps/lib64/luarocks/rocks/lpeg/1.0.2-1/lpeg-1.0.2-1.rockspec b/deps/lib64/luarocks/rocks/lpeg/1.0.2-1/lpeg-1.0.2-1.rockspec new file mode 100644 index 0000000..67ab927 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lpeg/1.0.2-1/lpeg-1.0.2-1.rockspec @@ -0,0 +1,32 @@ +package = 'LPeg' +version = '1.0.2-1' +source = { + url = 'http://www.inf.puc-rio.br/~roberto/lpeg/lpeg-1.0.2.tar.gz', + md5 = 'd342571886f1abcb7afe6a83d024d583', +} +description = { + summary = 'Parsing Expression Grammars For Lua', + detailed = [[ + LPeg is a new pattern-matching library for Lua, based on Parsing + Expression Grammars (PEGs). The nice thing about PEGs is that it + has a formal basis (instead of being an ad-hoc set of features), + allows an efficient and simple implementation, and does most things + we expect from a pattern-matching library (and more, as we can + define entire grammars). + ]], + homepage = 'http://www.inf.puc-rio.br/~roberto/lpeg.html', + maintainer = 'Gary V. Vaughan ', + license = 'MIT/X11' +} +dependencies = { + 'lua >= 5.1' +} +build = { + type = 'builtin', + modules = { + lpeg = { + 'lpcap.c', 'lpcode.c', 'lpprint.c', 'lptree.c', 'lpvm.c' + }, + re = 're.lua' + } +} diff --git a/deps/lib64/luarocks/rocks/lpeg/1.0.2-1/rock_manifest b/deps/lib64/luarocks/rocks/lpeg/1.0.2-1/rock_manifest new file mode 100644 index 0000000..d7b235c --- /dev/null +++ b/deps/lib64/luarocks/rocks/lpeg/1.0.2-1/rock_manifest @@ -0,0 +1,9 @@ +rock_manifest = { + lib = { + ["lpeg.so"] = "03df46cdb4ff87651ee2fb71b7d6d2b7" + }, + ["lpeg-1.0.2-1.rockspec"] = "7e5211dafbd5750059819e1ca96241b6", + lua = { + ["re.lua"] = "a7df04cbc0919d5b42b2911a27ad15f5" + } +} diff --git a/deps/lib64/luarocks/rocks/lua-protobuf/0.3.1-0/doc/LICENSE b/deps/lib64/luarocks/rocks/lua-protobuf/0.3.1-0/doc/LICENSE new file mode 100644 index 0000000..306734a --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-protobuf/0.3.1-0/doc/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Xavier Wang + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/deps/lib64/luarocks/rocks/lua-protobuf/0.3.1-0/doc/README.md b/deps/lib64/luarocks/rocks/lua-protobuf/0.3.1-0/doc/README.md new file mode 100644 index 0000000..31e99e6 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-protobuf/0.3.1-0/doc/README.md @@ -0,0 +1,455 @@ +# Google protobuf support for Lua + +[![Build Status](https://travis-ci.org/starwing/lua-protobuf.svg?branch=master)](https://travis-ci.org/starwing/lua-protobuf)[![Coverage Status](https://coveralls.io/repos/github/starwing/lua-protobuf/badge.svg?branch=master)](https://coveralls.io/github/starwing/lua-protobuf?branch=master) + +中文使用说明:https://zhuanlan.zhihu.com/p/26014103 + +QQ群:485016061 [![lua-protobuf1交流群](https://pub.idqqimg.com/wpa/images/group.png)](https://shang.qq.com/wpa/qunwpa?idkey=d7e2973604a723c4f77d0a837df39be26e15be2c2ec29d5ebfdb64f94e74e6ae) + +This project offers a simple C library for basic protobuf wire format encode/decode, it splits to several modules: + - `pb.slice`: a wire format decode module. + - `pb.buffer`: a buffer implement that use to encode basic types into protobuf's wire format. It also can be used to support streaming decode protobuf data. + - `pb.conv`: a module to convert between integers in protobuf. + - `pb.io`: a module to support binary mode read/write to stdin/stdout. + +It also has a high level Lua module to direct decode protobuf data to Lua table, or encode Lua table to protobuf data. + +It both support protobuf version 2 and 3 syntax and semantics. + +To support new protobuf type, you can use pb.load()/pb.loadfile() to load a compiled protobuf schema file, generated by Google protobuf's protoc compiler. And if you don't want include google's huge library, it includes a pure Lua module named protoc to translate text protobuf schema file into *.pb format. + +After load schema into `pb` module, you could use `pb.encode()` or `pb.decode()` routines to produce protobuf data. + +## Install + +To install this Lua module, you could just use `luarocks`: + +```shell +luarocks install lua-protobuf +``` + +If you want build it from source, just clone repo and use luarocks: + +```shell +git clone https://github.com/starwing/lua-protobuf +luarocks make rockspecs/lua-protobuf-scm-1.rockspec +``` + +If you don't have luarocks, use `hererocks` to install Lua and luarocks: + +```shell +pip install hererocks +git clone https://github.com/starwing/lua-protobuf +hererocks -j 2.0 -rlatest . +bin/luarocks make lua-protobuf/rockspecs/lua-protobuf-scm-1.rockspec CFLAGS="-fPIC -Wall -Wextra" LIBFLAGS="-shared" +cp protoc.lua pb.so .. +``` + +Or you can build it by hand, it only have a pure Lua module and a pair of C file: pb.h and pb.c + +To build it on macOS, use your favor compiler: + +```shell +gcc -O2 -shared -undefined dynamic_lookup pb.c -o pb.so +``` + +On Linux, use the nearly same command: + +```shell +gcc -O2 -shared -fPIC pb.c -o pb.so +``` + +On Windows, you could use MinGW or MSVC, create a sln project or build it on command line: + +```shell +cl /O2 /LD /Fepb.dll /I Lua53\include /DLUA_BUILD_AS_DLL pb.c Lua53\lib\lua53.lib +``` + +## Example + +```lua +local pb = require "pb" +local protoc = require "protoc" + +assert(protoc:load [[ + message Phone { + optional string name = 1; + optional int64 phonenumber = 2; + } + message Person { + optional string name = 1; + optional int32 age = 2; + optional string address = 3; + repeated Phone contacts = 4; + } ]]) + +local data = { + name = "ilse", + age = 18, + contacts = { + { name = "alice", phonenumber = 12312341234 }, + { name = "bob", phonenumber = 45645674567 } + } +} + +local bytes = assert(pb.encode("Person", data)) +print(pb.tohex(bytes)) + +local data2 = assert(pb.decode("Person", bytes)) +print(require "serpent".block(data2)) + +``` + +## Use case + +[![零境交错](https://img.tapimg.com/market/images/e59627dc9039ff22ba7d000b5c9fe7f6.jpg?imageView2/2/h/560/q/40/format/jpg/interlace/1/ignore-error/1)](http://djwk.qq.com) + + + +## Usage + +### `protoc` Module + +| Function | Returns | Descriptions | +| ----------------------- | ------------- | ---------------------------------------------------- | +| `protoc.new()` | Proroc object | create a new compiler instance | +| `protoc.reload()` | true | reload all google standard messages into `pb` module | +| `p:parse(string)` | table | transform schema to `DescriptorProto` table | +| `p:parsefile(string)` | table | like `p:parse()`, but accept filename | +| `p:compile(string)` | string | transform schema to binary *.pb format data | +| `p:compilefile(string)` | string | like `p:compile()`, but accept filename | +| `p:load(string)` | true | load schema into `pb` module | +| `p:loadfile(string)` | true | like `pb:loadfile()`, but accept filename | +| `p.loaded` | table | contains all parsed `DescriptorProto` table | +| `p.paths` | table | a table contains import search directories | +| `p.unknown_module` | see below | handle schema import error | +| `p.unknown_type` | see below | handle unknown type in schema | +| `p.include_imports` | bool | auto load imported proto | + +To parse a text schema file, you should create a compiler instance first: + +```lua +local p = protoc.new() +``` + +Then, you can set some options to compiler, e.g. the search path, the unknown handlers, etc. + +```lua +p.paths[#p.paths+1] = "whatever/folder/hold/.proto/files" +p.unknown_module = function(self, module_name) ... end +p.unknown_type = function(self, type_name) ... end +p.include_imports = true +``` + +The `unknwon_module` and `unknown_type` handle could be `true`, string or a function. If set it to `true`, means all non-exists module or type are given a default value and do not trigger a error. If set it to a string, that string will be a Lua pattern that indicate whether a unknown module or type should produce a error, e.g. + +```lua +p.unknown_type = "Foo.*" +``` + +means all Types prefixed by Foo will treat as exists type and not trigger errors. + +If these handlers are set to functions, the unknown type or module name will passed to function, for module handler, it should return a `DescriptorProto` Table produced by `p:load[file]()` functions, for type handler, it should return a type name and type, such as `message` or `enum`, e.g. + +```lua +function p:unknown_module(name) + -- if can not find "foo.proto", load "my_foo.proto" instead + return p:load("my_"..name) +end + +function p:unknown_type(name) + -- if can not find "Type", treat it as ".MyType" and is a message type + return ".My"..name, "message" +end +``` + +After setting options, use `load[file]()` or `compile[file]()` or `parse[file]()` function to get result. + +### `pb` Module + +`pb` module have the high level routines to maniplate protobuf messages. + +in below functions, we have several types that has special means: + +- `type`: a string that indicate a protobuf message type, `".Foo"` means a type in a proto file that have not `package` statement declared. `"foo.Foo"` means a type in a proto file that declared `package foo;` + +- `data`: could be string, `pb.Slice` value or `pb.Buffer` value. + +- `iterator`: a function that can used in Lua `for in` statement, e.g. + + ```lua + for name in pb.types() do + print(name) + end + ``` + + +all functions returns `nil, errmsg` when meet errors. + +| Function | Returns | Description | +| ------------------------------ | ---------- | ------------------------------------------------- | +| `pb.clear()` | None | clear all types | +| `pb.clear(type)` | None | delete specific type | +| `pb.load(data)` | true | load a binary schema data into `pb` module | +| `pb.loadfile(string)` | true | same as `pb.load()`, but accept file name | +| `pb.encode(type, table)` | string | encode a message table into binary form | +| `pb.encode(type, table, b)` | buffer | encode a message table into binary form to buffer | +| `pb.decode(type, data)` | table | decode a binary message into Lua table | +| `pb.decode(type, data, table)` | table | decode a binary message into a given Lua table | +| `pb.pack(fmt, ...)` | string | same as `buffer.pack()` but return string | +| `pb.unpack(data, fmt, ...)` | values... | same as `slice.unpack()` but accept data | +| `pb.types()` | iterator | iterate all types in `pb` module | +| `pb.type(type)` | see below | return informations for specific type | +| `pb.fields(type)` | iterator | iterate all fields in a message | +| `pb.field(type, string)` | see below | return informations for specific field of type | +| `pb.enum(type, string)` | number | get the value of a enum by name | +| `pb.enum(type, number)` | string | get the name of a enum by value | +| `pb.defaults(type[, table])` | table | get the default table of type | +| `pb.option(string)` | string | set options to decoder/encoder | +| `pb.state()` | `pb.State` | retrieve current pb state | +| `pb.state(newstate \| nil)` | `pb.State` | set new pb state and retrieve the old one | + +#### Type Information + +You can use `pb.(type|field)[s]()` functions to retrieve type information for loaded messages. + +`pb.type()` returns multiple informations for specified type: + +- name : the full qualifier name of type, e.g. ".package.TypeName" +- basename: the type name without package prefix, e.g. "TypeName" +- "map" | "enum" | "message": whether the type is a map_entry type, enum type or message type. + +`pb.types()` returns a iterators, behavior like call `pb.type()` on every types of all messages. + +```lua +print(pb.type "MyType") + +-- list all types that loaded into pb +for name, basename, type in pb.types() do + print(name, basename, type) +end +``` + +`pb.field()` returns informations of the specified field for one type: + +- name: the name of field +- number: number of field in schema +- type: field type +- default value: if no default value, nil +- "packed"|"repeated"| "optional": label of field, optional or repeated, required is not supported +- [oneof_name, oneof_index] : if this is a oneof field, this is the oneof name and index + +And `pb.fields()` iterates all fields in a message: + +```lua +print(pb.field("MyType", "the_first_field")) + +-- notice that you needn't receive all return values from iterator +for name, number, type in pb.fields "MyType" do + print(name, number, type) +end +``` + +`pb.enum()` maps from enum name and value: + +```lua +protoc:load [[ +enum Color { Red = 1; Green = 2; Blue = 3 } +]] +print(pb.enum("Color", "Red")) --> 1 +print(pb.enum("Color", 2)) --> "Green" +``` + +#### Default Values + +Using `pb.defaults()`, you could get a table with all default values from a message: + +```lua + check_load [[ + message TestDefault { + optional int32 defaulted_int = 10 [ default = 777 ]; + optional bool defaulted_bool = 11 [ default = true ]; + optional string defaulted_str = 12 [ default = "foo" ]; + optional float defaulted_num = 13 [ default = 0.125 ]; + } ]] + print(require "serpent".block(pb.defaults "TestDefault")) +-- output: +-- { +-- defaulted_bool = true, +-- defaulted_int = 777, +-- defaulted_num = 0.125, +-- defaulted_str = "foo" +-- } --[[table: 0x7f8c1e52b050]] + +``` + +#### Options + +You can set options to change the behavior or decoder/encoder. +current these options are supported: + +| Option | Description | +| ----------------------- | ------------------------------------------------------------ | +| `enum_as_name` | set value to enum name when decode a enum **(default)** | +| `enum_as_value` | set value to enum value when decode a enum | +| `int64_as_number` | set value to integer when it fit int32, otherwise return a number **(default)** | +| `int64_as_string` | same as above, but when it not fit int32, return a string instead | +| `int64_as_hexstring` | same as above, but return a hexadigit string instead | +| `no_default_values` | do not default values for decoded message table **(default)** | +| `use_default_values` | set default values by copy values from default table before decode | +| `use_default_metatable` | set default values by set default table as the metatable | + + Note: The string returned by `int64_as_string` or `int64_as_hexstring` will prefix a `'#'` character. Because Lua may convert string and number, prefix a '#' makes lua return the string as-is. + +all routines in all module can accept `'#'` prefix `string`/`hexstring` as arguments. + +#### Multiple State + +`pb` module support multiple state. A state is a database that contains all type information of registered messages. You can retrieve current state by `pb.state()`, or set new state by `pb.state(newstate)`. + +Use `pb.state(nil)` to discard current state, but not to set a new one (the following routines call that use the state will create a new default state automatedly). Use `pb.state()` to retrieve current state without setting a new one. e.g. + +```lua +local old = pb.state(nil) +-- if you use protoc.lua, call protoc.reload() here. +assert(pb.load(...)) +-- do someting ... +pb.state(old) +``` + +Notice that if you use `protoc.lua` module, it will register some message to state, so you should call `proto.reload()` after setting a new state. + + + +### `pb.io` Module + +`pb.io` module are used to read binary data from file or `stdin`/`stdout`, `pb.io.read()` is used to read binary data from file, if no file name given as the first parameter, it reads binary data from `stdin`. + +`pb.io.write()` and `pb.io.dump()` all same as Lua's `io.write()` but they write binary data. The first one write data to `stdout`, and latter write data to a file, specific by the first parameter, the file name. + +All these functions return true value when success, and return `nil, errmsg` when error occurs. + +| Function | Returns | Description | +| ----------------------- | ------- | ----------------------------------- | +| `io.read()` | string | read all binary data from `stdin` | +| `io.read(string)` | string | read all binary data from file name | +| `io.write(...)` | true | write binary data to `stdout` | +| `io.dump(string, ...)` | string | write binary data to file name | + + + +### `pb.conv` Module + +`pb.conv` have functions to convert between numbers. + +| Encode Function | Decode Function | +| ---------------------- | ---------------------- | +| `conv.encode_int32()` | `conv.decode_int32()` | +| `conv.encode_uint32()` | `conv.decode_uint32()` | +| `conv.encode_sint32()` | `conv.decode_sint32()` | +| `conv.encode_sint64()` | `conv.decode_sint64()` | +| `conv.encode_float()` | `conv.decode_float()` | +| `conv.encode_double()` | `conv.decode_double()` | + + + +### `pb.slice` Module + +Slice module used to parse binary protobuf data in low level way. Use `slice.new()` to create a slice object, you can specific offset `i` and `j` to just access a sub part of the original data (named a view). + +A slice object itself has a stack, use `s:enter(i, j)` to save current position and enter next level which the view is specific by the offset `i` and `j`, just as `slice.new()`. Use `s:leave()` to restore previous view. You can use `s:level()` to get the current level, and use `s:level(n)` to get the current position, the start and the end position informations of the `n`th level. You can also use `s:enter()` without parameter to read a length delimited type value from slice and enter the view in readed value. To get the count of bytes remains in current view to read, use `#s`. + +To read values from slice, use `slice.unpack()`, it use a format string to control how to read into a slice (same format character are also used in `buffer.pack()`): + +| Format | Description | +| ------ | ---------------------------------------- | +| v | variable Int value | +| d | 4 bytes fixed32 value | +| q | 8 bytes fixed64 value | +| s | length delimited value, usually a `string`, `bytes` or `message` in protobuf. | +| c | receive a extra number parameter `count` after the format, and reads `count` bytes in slice. | +| b | variable int value as a Lua `boolean` value. | +| f | 4 bytes `fixed32` value as floating point `number` value. | +| F | 8 bytes `fixed64` value as floating point `number` value. | +| i | variable int value as signed int value, i.e. `int32` | +| j | variable int value as zig-zad encoded signed int value, i.e.`sint32` | +| u | variable int value as unsigned int value, i.e. `uint32` | +| x | 4 bytes fixed32 value as unsigned fixed32 value, i.e.`fixed32` | +| y | 4 bytes fixed32 value as signed fixed32 value, i.e. `sfixed32` | +| I | variable int value as signed int value, i.e.`int64` | +| J | variable int value as zig-zad encoded signed int value, i.e. `sint64` | +| U | variable int value and treat it as `uint64` | +| X | 8 bytes fixed64 value as unsigned fixed64 value, i.e. `fixed64` | +| Y | 8 bytes fixed64 value as signed fixed64 value, i.e. `sfixed64` | + +And you can use extra format to control the read cursor in one `slice.unpack()` process: + +| Format | Description | +| ------ | ---------------------------------------- | +| @ | returns current cursor position in slice, related with the begining of current view. | +| * | set the current cursor position to the extra parameter after format string. | +| + | set the relate cursor position, i.e. add the extra parameter to current position. | + +e.g. If you want to read a varint value twice, you can write it as: + +```lua +local v1, v2 = s:unpack("v*v", 1) +-- v: reads a varint value +-- *: receive the second parameter 1 and set it to current cursor position, i.e. restore cursor to the head of view +-- v: reads the first varint value again +``` + + + +| Function | Returns | Description | +| ------------------------- | ------------ | ---------------------------------------- | +| `slice.new(data[,i[,j]])` | Slice object | create a new slice object | +| `s:delete()` | none | same as `s:reset()`, free it's content | +| `tostring(s)` | string | return the string repr of the object | +| `#s` | number | returns the count of bytes can read in current view | +| `s:reset([...])` | self | reset object to another data | +| `s:level()` | number | returns the count of stored state | +| `s:level(number)` | p, i, j | returns the informations of the `n`th stored state | +| `s:enter()` | self | reads a bytes value, and enter it's view | +| `s:enter(i[, j])` | self | enter a view start at `i` and ends at `j`, includes | +| `s:leave([number])` | self, n | leave the number count of level (default 1) and return current level | +| `s:unpack(fmt, ...)` | values... | reads values of current view from slice | + + + +### `pb.buffer` Module + +Buffer module used to construct a protobuf data format stream in low level way, it's just a bytes data buffer, you can add values by `buffer.pack()`, and use `buffer.result()` get the encoded raw data, or use `buffer.tohex()` to get human readable hexadigit value of data. + +the `buffer.pack()` use the same format syntax with `slice.unpack()`, and support '()' format, if you use a pair of parenthesis, it means the inner value will be encoded as a length delimited value, i.e. a message value encoded format. + +parenthesis could be nested. + +e.g. + +```lua +b:pack("(vvv)", 1, 2, 3) -- get a bytes value that contains three varint value. +``` + + + +`buffer.pack()` also support '#' format, it means prepends a length into buffer. + +e.g. + +```lua +b:pack("#", 5) -- prepends a varint length #b-5+1 at offset 5 +``` + +| Function | Returns | Description | +| ------------------- | ------------- | ---------------------------------------- | +| `buffer.new([...])` | Buffer object | create a new buffer object, extra args will passed to `b:reset()` | +| `b:delete()` | none | same as `b:reset()`, free it's content | +| `tostring(b)` | string | returns the string repr of the object | +| `#b` | number | returns the encoded count of bytes in buffer | +| `b:reset()` | self | free buffer content, reset it to a empty buffer | +| `b:reset([...])` | self | resets the buffer and set its content as the concat of it's args | +| `b:tohex([i[, j]])` | string | return the string of hexadigit represent of the data, `i` and `j` are ranges in encoded data, includes. Omit it means the whole range | +| `b:result([i[,j]])` | string | return the raw data, `i` and `j` are ranges in encoded data, includes,. Omit it means the whole range | +| `b:pack(fmt, ...)` | self | encode the values passed to `b:pack()`, use `fmt` to indicate how to encode value | + diff --git a/deps/lib64/luarocks/rocks/lua-protobuf/0.3.1-0/lua-protobuf-0.3.1-0.rockspec b/deps/lib64/luarocks/rocks/lua-protobuf/0.3.1-0/lua-protobuf-0.3.1-0.rockspec new file mode 100644 index 0000000..530337d --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-protobuf/0.3.1-0/lua-protobuf-0.3.1-0.rockspec @@ -0,0 +1,24 @@ +package = "lua-protobuf" +version = "0.3.1-0" +source = { + url = "git://github.com/starwing/lua-protobuf.git", + tag = "0.3.1" +} +description = { + summary = "protobuf data support for Lua", + detailed = [[ +This project offers a simple C library for basic protobuf wire format encode/decode. + ]], + homepage = "https://github.com/starwing/lua-protobuf", + license = "MIT" +} +dependencies = { + "lua >= 5.1" +} +build = { + type = "builtin", + modules = { + pb = "pb.c", + protoc = "protoc.lua" + } +} diff --git a/deps/lib64/luarocks/rocks/lua-protobuf/0.3.1-0/rock_manifest b/deps/lib64/luarocks/rocks/lua-protobuf/0.3.1-0/rock_manifest new file mode 100644 index 0000000..2d492a4 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-protobuf/0.3.1-0/rock_manifest @@ -0,0 +1,13 @@ +rock_manifest = { + doc = { + LICENSE = "759700dd96fbc5c3b37ea958b7eae988", + ["README.md"] = "81e93e09ef9e8352157341ef93c4b025" + }, + lib = { + ["pb.so"] = "1466a21dd200d5abb1bcf5042230bdab" + }, + lua = { + ["protoc.lua"] = "8c00594e517641504763f8222b330db7" + }, + ["lua-protobuf-0.3.1-0.rockspec"] = "d74dfeb46acce306fea42a52581b2eb5" +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-balancer/0.02rc5-0/doc/README.markdown b/deps/lib64/luarocks/rocks/lua-resty-balancer/0.02rc5-0/doc/README.markdown new file mode 100644 index 0000000..0285552 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-balancer/0.02rc5-0/doc/README.markdown @@ -0,0 +1,342 @@ +Name +==== + +lua-resty-chash - A generic consistent hash implementation for OpenResty/LuaJIT + +lua-resty-roundrobin - A generic roundrobin implementation for OpenResty/LuaJIT + +Table of Contents +================= + +* [Name](#name) +* [Status](#status) +* [Description](#description) +* [Synopsis](#synopsis) +* [Methods](#methods) + * [new](#new) + * [reinit](#reinit) + * [set](#set) + * [delete](#delete) + * [incr](#incr) + * [decr](#decr) + * [find](#find) + * [next](#next) +* [Installation](#installation) +* [Performance](#performance) +* [Author](#author) +* [Copyright and License](#copyright-and-license) +* [See Also](#see-also) + +Status +====== + +This library is still under early development and is still experimental. + +Description +=========== + +This Lua library can be used with `balancer_by_lua*`. + +Synopsis +======== + +```lua + lua_package_path "/path/to/lua-resty-chash/lib/?.lua;;"; + lua_package_cpath "/path/to/lua-resty-chash/?.so;;"; + + init_by_lua_block { + local resty_chash = require "resty.chash" + local resty_roundrobin = require "resty.roundrobin" + + local server_list = { + ["127.0.0.1:1985"] = 2, + ["127.0.0.1:1986"] = 2, + ["127.0.0.1:1987"] = 1, + } + + -- XX: we can do the following steps to keep consistency with nginx chash + local str_null = string.char(0) + + local servers, nodes = {}, {} + for serv, weight in pairs(server_list) do + -- XX: we can just use serv as id when we doesn't need keep consistency with nginx chash + local id = string.gsub(serv, ":", str_null) + + servers[id] = serv + nodes[id] = weight + end + + local chash_up = resty_chash:new(nodes) + + package.loaded.my_chash_up = chash_up + package.loaded.my_servers = servers + + local rr_up = resty_roundrobin:new(server_list) + package.loaded.my_rr_up = rr_up + } + + upstream backend_chash { + server 0.0.0.1; + balancer_by_lua_block { + local b = require "ngx.balancer" + + local chash_up = package.loaded.my_chash_up + local servers = package.loaded.my_servers + + -- we can balancer by any key here + local id = chash_up:find(ngx.var.arg_key) + local server = servers[id] + + assert(b.set_current_peer(server)) + } + } + + upstream backend_rr { + server 0.0.0.1; + balancer_by_lua_block { + local b = require "ngx.balancer" + + local rr_up = package.loaded.my_rr_up + + local server = rr_up:find() + + assert(b.set_current_peer(server)) + } + } + + server { + location /chash { + proxy_pass http://backend_chash; + } + + location /roundrobin { + proxy_pass http://backend_rr; + } + } +``` + +[Back to TOC](#table-of-contents) + +Methods +======= + +Both `resty.chash` and `resty.roundrobin` have the same apis. + +[Back to TOC](#table-of-contents) + +new +--- +**syntax:** `obj, err = class.new(nodes)` + +Instantiates an object of this class. The `class` value is returned by the call `require "resty.chash"`. + +The `id` should be `table.concat({host, string.char(0), port})` like the nginx chash does, +when we need to keep consistency with nginx chash. + +The `id` can be any string value when we do not need to keep consistency with nginx chash. + +```lua +local nodes = { + -- id => weight + server1 = 10, + server2 = 2, +} + +local resty_chash = require "resty.chash" + +local chash = resty_chash:new(nodes) + +local id = chash:find("foo") + +ngx.say(id) +``` + +[Back to TOC](#table-of-contents) + +reinit +-------- +**syntax:** `obj:reinit(nodes)` + +Reinit the chash obj with the new `nodes`. + +[Back to TOC](#table-of-contents) + +set +-------- +**syntax:** `obj:set(id, weight)` + +Set `weight` of the `id`. + +[Back to TOC](#table-of-contents) + +delete +-------- +**syntax:** `obj:delete(id)` + +Delete the `id`. + +[Back to TOC](#table-of-contents) + +incr +-------- +**syntax:** `obj:incr(id, weight?)` + +Increments weight for the `id` by the step value `weight`(default to 1). + +[Back to TOC](#table-of-contents) + +decr +-------- +**syntax:** `obj:decr(id, weight?)` + +Decrease weight for the `id` by the step value `weight`(default to 1). + +[Back to TOC](#table-of-contents) + +find +-------- +**syntax:** `id, index = obj:find(key)` + +Find an id by the `key`, same key always return the same `id` in the same `obj`. + +The second return value `index` is the index in the chash circle of the hash value of the `key`. + +[Back to TOC](#table-of-contents) + +next +-------- +**syntax:** `id, new_index = obj:next(old_index)` + +If we have chance to retry when the first `id`(server) doesn't work well, +then we can use `obj:next` to get the next `id`. + +The new `id` may be the same as the old one. + +[Back to TOC](#table-of-contents) + +Installation +============ + +First you need to run `make` to generate the librestychash.so. +Then you need to configure the lua_package_path and lua_package_cpath directive +to add the path of your lua-resty-chash source tree to ngx_lua's LUA_PATH search +path, as in + +```nginx + # nginx.conf + http { + lua_package_path "/path/to/lua-resty-chash/lib/?.lua;;"; + lua_package_cpath "/path/to/lua-resty-chash/?.so;;"; + ... + } +``` + +Ensure that the system account running your Nginx ''worker'' proceses have +enough permission to read the `.lua` and `.so` file. + +[Back to TOC](#table-of-contents) + +Performance +=========== + +There is a benchmark script `t/bench.lua`. + +I got the result when I run `make bench`: + +``` +chash new servers +10000 times +elasped: 0.61600017547607 + +chash new servers2 +1000 times +elasped: 0.77300000190735 + +chash new servers3 +10000 times +elasped: 0.66899991035461 + +new in func +10000 times +elasped: 0.62000012397766 + +new dynamic +10000 times +elasped: 0.75499987602234 + +incr server3 +10000 times +elasped: 0.19000029563904 + +incr server1 +10000 times +elasped: 0.33699989318848 + +decr server1 +10000 times +elasped: 0.27300024032593 + +delete server3 +10000 times +elasped: 0.037999868392944 + +delete server1 +10000 times +elasped: 0.065000057220459 + +set server1 9 +10000 times +elasped: 0.26600003242493 + +set server1 8 +10000 times +elasped: 0.32000017166138 + +set server1 1 +10000 times +elasped: 0.56699991226196 + +base for find +1000000 times +elasped: 0.01800012588501 + +find +1000000 times +elasped: 0.9469997882843 +``` + +[Back to TOC](#table-of-contents) + +Author +====== + +Dejiang Zhu (doujiang24) . + +[Back to TOC](#table-of-contents) + +Copyright and License +===================== + +This module is licensed under the BSD license. + +Copyright (C) 2015-2016, by Yichun Zhang (agentzh) , CloudFlare Inc. + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. + +[Back to TOC](#table-of-contents) + +See Also +======== +* the ngx_lua module: http://wiki.nginx.org/HttpLuaModule +* the json lib for Lua and C: https://github.com/cloudflare/lua-resty-json + +[Back to TOC](#table-of-contents) + diff --git a/deps/lib64/luarocks/rocks/lua-resty-balancer/0.02rc5-0/lua-resty-balancer-0.02rc5-0.rockspec b/deps/lib64/luarocks/rocks/lua-resty-balancer/0.02rc5-0/lua-resty-balancer-0.02rc5-0.rockspec new file mode 100644 index 0000000..12fa657 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-balancer/0.02rc5-0/lua-resty-balancer-0.02rc5-0.rockspec @@ -0,0 +1,23 @@ +package = "lua-resty-balancer" +version = "0.02rc5-0" +source = { + url = "git://github.com/openresty/lua-resty-balancer", + tag = "v0.02rc5", +} + +description = { + summary = "A generic consistent hash implementation for OpenResty", + homepage = "https://github.com/openresty/lua-resty-balancer", + license = "Apache License 2.0", + maintainer = "Yichun Zhang (agentzh) ", +} + +build = { + type = "builtin", + modules = { + ["librestychash"] = {"chash.c"}, + + ["resty.chash"] = "lib/resty/chash.lua", + ["resty.roundrobin"] = "lib/resty/roundrobin.lua", + } +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-balancer/0.02rc5-0/rock_manifest b/deps/lib64/luarocks/rocks/lua-resty-balancer/0.02rc5-0/rock_manifest new file mode 100644 index 0000000..08b2b04 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-balancer/0.02rc5-0/rock_manifest @@ -0,0 +1,15 @@ +rock_manifest = { + doc = { + ["README.markdown"] = "9c6337e11a469629c8bc5892519e22ab" + }, + lib = { + ["librestychash.so"] = "41c7948c8ec9449fcad0bb94bdbc4ea1" + }, + lua = { + resty = { + ["chash.lua"] = "941d5d8a28512ea8d9550cdc549df7e1", + ["roundrobin.lua"] = "9cdf3453c65f59aa493a89418b832ac7" + } + }, + ["lua-resty-balancer-0.02rc5-0.rockspec"] = "32bb2e3ba02e95b45957f5427f3e6be9" +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-cookie/0.1.0-1/doc/README.md b/deps/lib64/luarocks/rocks/lua-resty-cookie/0.1.0-1/doc/README.md new file mode 100644 index 0000000..5ac833d --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-cookie/0.1.0-1/doc/README.md @@ -0,0 +1,184 @@ +Name +==== + +lua-resty-cookie - This library parses HTTP Cookie header for Nginx and returns each field in the cookie. + +Table of Contents +================= + +* [Name](#name) +* [Status](#status) +* [Synopsis](#synopsis) +* [Methods](#methods) + * [new](#new) + * [get](#get) + * [get_all](#get_all) + * [set](#set) +* [Installation](#installation) +* [Authors](#authors) +* [Copyright and License](#copyright-and-license) + +Status +====== + +This library is production ready. + +Synopsis +======== +```lua + lua_package_path "/path/to/lua-resty-cookie/lib/?.lua;;"; + + server { + location /test { + content_by_lua ' + local ck = require "resty.cookie" + local cookie, err = ck:new() + if not cookie then + ngx.log(ngx.ERR, err) + return + end + + -- get single cookie + local field, err = cookie:get("lang") + if not field then + ngx.log(ngx.ERR, err) + return + end + ngx.say("lang", " => ", field) + + -- get all cookies + local fields, err = cookie:get_all() + if not fields then + ngx.log(ngx.ERR, err) + return + end + + for k, v in pairs(fields) do + ngx.say(k, " => ", v) + end + + -- set one cookie + local ok, err = cookie:set({ + key = "Name", value = "Bob", path = "/", + domain = "example.com", secure = true, httponly = true, + expires = "Wed, 09 Jun 2021 10:18:14 GMT", max_age = 50, + extension = "a4334aebaec" + }) + if not ok then + ngx.log(ngx.ERR, err) + return + end + + -- set another cookie, both cookies will appear in HTTP response + local ok, err = cookie:set({ + key = "Age", value = "20", + }) + if not ok then + ngx.log(ngx.ERR, err) + return + end + '; + } + } +``` + +Methods +======= + +[Back to TOC](#table-of-contents) + +new +--- +`syntax: cookie_obj = cookie()` + +Create a new cookie object for current request. You can get parsed cookie from client or set cookie to client later using this object. + +[Back to TOC](#table-of-contents) + +get +--- +`syntax: cookie_val, err = cookie_obj:get(cookie_name)` + +Get a single client cookie value. On error, returns `nil` and an error message. + +[Back to TOC](#table-of-contents) + +get_all +------- +`syntax: fields, err = cookie_obj:get_all()` + +Get all client cookie key/value pairs in a lua table. On error, returns `nil` and an error message. + +[Back to TOC](#table-of-contents) + +set +--- +```lua +syntax: ok, err = cookie_obj:set({ + key = "Name", + value = "Bob", + path = "/", + domain = "example.com", + secure = true, httponly = true, + expires = "Wed, 09 Jun 2021 10:18:14 GMT", + max_age = 50, + extension = "a4334aebaec" +}) +``` + +Set a cookie to client. This will add a new 'Set-Cookie' response header. `key` and `value` are required, all other fields are optional. +If the same cookie (whole cookie string, e.g. "Name=Bob; Expires=Wed, 09 Jun 2021 10:18:14 GMT; Max-Age=50; Domain=example.com; Path=/; Secure; HttpOnly;") has already been setted, new cookie will be ignored. + +[Back to TOC](#table-of-contents) + +Installation +============ + +You need to compile [ngx_lua](https://github.com/chaoslawful/lua-nginx-module/tags) with your Nginx. + +You need to configure +the [lua_package_path](https://github.com/chaoslawful/lua-nginx-module#lua_package_path) directive to +add the path of your `lua-resty-cookie` source tree to ngx_lua's Lua module search path, as in + + # nginx.conf + http { + lua_package_path "/path/to/lua-resty-cookie/lib/?.lua;;"; + ... + } + +and then load the library in Lua: + + local ck = require "resty.cookie" + +[Back to TOC](#table-of-contents) + +Authors +======= + +Jiale Zhi , CloudFlare Inc. + +Yichun Zhang (agentzh) , CloudFlare Inc. + +[Back to TOC](#table-of-contents) + +Copyright and License +===================== + +This module is licensed under the BSD license. + +Copyright (C) 2013, by Jiale Zhi , CloudFlare Inc. + +Copyright (C) 2013, by Yichun Zhang , CloudFlare Inc. + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. + +[Back to TOC](#table-of-contents) + diff --git a/deps/lib64/luarocks/rocks/lua-resty-cookie/0.1.0-1/lua-resty-cookie-0.1.0-1.rockspec b/deps/lib64/luarocks/rocks/lua-resty-cookie/0.1.0-1/lua-resty-cookie-0.1.0-1.rockspec new file mode 100644 index 0000000..61c0911 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-cookie/0.1.0-1/lua-resty-cookie-0.1.0-1.rockspec @@ -0,0 +1,24 @@ +package = "lua-resty-cookie" +version = "0.1.0-1" + +source = { + url = "git://github.com/cloudflare/lua-resty-cookie.git", + tag = "v0.1.0", +} + +description = { + summary = "Lua library for HTTP cookie manipulations for OpenResty/ngx_lua", + homepage = "https://github.com/cloudflare/lua-resty-cookie", + license = "BSD", +} + +dependencies = { + "lua >= 5.1", -- lua-nginx-module needed +} + +build = { + type = "builtin", + modules = { + ["resty.cookie"] = "lib/resty/cookie.lua" + } +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-cookie/0.1.0-1/rock_manifest b/deps/lib64/luarocks/rocks/lua-resty-cookie/0.1.0-1/rock_manifest new file mode 100644 index 0000000..0943c7f --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-cookie/0.1.0-1/rock_manifest @@ -0,0 +1,11 @@ +rock_manifest = { + doc = { + ["README.md"] = "41cb4db3a1cafc91c44e50d83f9ff8ff" + }, + lua = { + resty = { + ["cookie.lua"] = "7c60ed3a197d789f51383350e2147be2" + } + }, + ["lua-resty-cookie-0.1.0-1.rockspec"] = "740073ffa26149fad0b268b353dbfa1f" +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-etcd/1.4.3-0/doc/LICENSE b/deps/lib64/luarocks/rocks/lua-resty-etcd/1.4.3-0/doc/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-etcd/1.4.3-0/doc/LICENSE @@ -0,0 +1,201 @@ + 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/deps/lib64/luarocks/rocks/lua-resty-etcd/1.4.3-0/doc/README.md b/deps/lib64/luarocks/rocks/lua-resty-etcd/1.4.3-0/doc/README.md new file mode 100644 index 0000000..99b9d67 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-etcd/1.4.3-0/doc/README.md @@ -0,0 +1,36 @@ +Name +==== + +[resty-etcd](https://github.com/iresty/lua-resty-etcd) Nonblocking Lua etcd driver library for OpenResty, this module supports etcd API v2 and v3. + +[![Build Status](https://travis-ci.org/api7/lua-resty-etcd.svg?branch=master)](https://travis-ci.org/api7/lua-resty-etcd) +[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/iresty/lua-resty-etcd/blob/master/LICENSE) + +Table of Contents +================= +* [Install](#install) +* [API v2](api_v2.md) +* [API v3](api_v3.md) + +## Install + +> Dependencies + +- lua-resty-http: https://github.com/ledgetech/lua-resty-http +- lua-typeof: https://github.com/iresty/lua-typeof + +> install by luarocks + +```shell +luarocks install lua-resty-etcd +``` + +> install by source + +```shell +$ git clone https://github.com/iresty/lua-resty-etcd.git +$ cd lua-resty-etcd +$ make dev +$ sudo make install +``` + diff --git a/deps/lib64/luarocks/rocks/lua-resty-etcd/1.4.3-0/doc/api_v2.md b/deps/lib64/luarocks/rocks/lua-resty-etcd/1.4.3-0/doc/api_v2.md new file mode 100644 index 0000000..6e3c9ea --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-etcd/1.4.3-0/doc/api_v2.md @@ -0,0 +1,285 @@ +API V2 +====== + +* [Methods](#methods) + * [new](#new) + * [get](#get) + * [set](#set) + * [setnx](#setnx) + * [setx](#setx) + * [delete](#delete) + * [wait](#wait) + * [readdir](#readdir) + * [mkdir](#mkdir) + * [rmdir](#rmdir) + * [waitdir](#waitdir) + * [push](#push) + * [version](#version) + * [stats_leader](#stats_leader) + * [stats_self](#stats_self) + * [stats_store](#stats_store) + +Method +====== + +### new + +`syntax: cli, err = etcd.new([option:table])` + +- `option:table` + - `protocol`: string - default `v2`. + - `http_host`: string - default `http://127.0.0.1:2379` + - `ttl`: int - default `-1` + default ttl for key operation. set -1 to disable ttl. + - `key_prefix`: string + append this prefix path string to key operation url `'/v2/keys'`. + - `timeout`: int + request timeout seconds. + - `serializer`: string - serializer type, default `json`, also support `raw` to keep origin string value. + - `ssl_verify`: boolean - whether to verify the etcd certificate when originating TLS connection with etcd (if you want to communicate to etcd with TLS connection, use `https` scheme in your `http_host`), default is `true`. + +The client methods returns either a `HTTP Response Entity` or an `error string`. + +`HTTP Response Entity` contains the following fields except `408` timeout status; + +- `status`: number - HTTP status code. +- `header`: table - response header if `status` is not `408` timeout status. +- `body`: string or table - response body if `status` is not `408` timeout status. + +**Note:** a client method will decode a response body as a JSON string if a `Content-Type` response header value is a `application/json`. + +```lua +local cli, err = require('resty.etcd').new() +``` + +Please refer the **etcd API documentaion** at - https://github.com/coreos/etcd for more details of a response entity. + +[Back to TOP](#api-v2) + +### get + +`syntax: res, err = cli:get(key:string)` + +Gets the value for key. + +```lua +local res, err = cli:get('/path/to/key') +``` + +[Back to TOP](#api-v2) + +### set + +`syntax: res, err = cli:set(key:string, val:JSON value [, ttl:int])` + +Set a key-value pair. + +```lua +local res, err = cli:set('/path/to/key', 'val', 10) +``` + +[Back to TOP](#api-v2) + +### setnx + +`syntax: res, err = cli:setnx(key:string, val:JSON value [, ttl:int])` + +Set a key-value pair if that key does not exist. + +```lua +local res, err = cli:setnx('/path/to/key', 'val', 10) +``` + +[Back to TOP](#api-v2) + +### setx + +`syntax: res, err = cli:setx(key:string, val:JSON value [, ttl:int [, modified_index:uint] ])` + +- `modified_index`: uint - this argument to use to the `prev_index` query of atomic operation. + +Set a key-value pair when that key is exists. + +```lua +local res, err = cli:setx('/path/to/key', 'val', 10) +``` + +```lua +local res, err = cli:get('/path/to/key') + +-- this operation will be failed if the `modified_index` of specified key +-- has already been updated by another client. +res, err = cli:setx('/path/to/key', 'val', 10, res.body.node.modifiedIndex) +``` + +[Back to TOP](#api-v2) + +### delete + +`syntax: res, err = cli:delete(key:string [, val:JSON value [, modified_index:uint] ])` + +- `val`: JSON value - this argument to use to the `prevValue` query of atomic operation. +- `modified_index`: uint - this argument to use to the `prev_index` query of atomic operation. + +Deletes a key-value pair. + +```lua +local res, err = cli:delete('/path/to/key') +``` + +```lua +local res, err = cli:get('/path/to/key') + +-- delete key-value pair if both of `value` and `modified_index` has matched +-- to the passed arguments +res, err = cli:delete('/path/to/key', res.body.node.value, + res.body.node.modifiedIndex) + +-- delete key-value pair if `value` has matched to the passed value +res, err = cli:delete('/path/to/key', res.body.node.value) + +-- delete key-value pair if `modified_index` has matched to the passed +-- modifiedIndex +res, err = cli:delete('/path/to/key', nil, res.body.node.modifiedIndex) + +``` + +[Back to TOP](#api-v2) + +### wait + +`syntax: res, err = cli:wait(key:string [, modified_index:uint [, timeout:uint] ]) ` + +- `modified_index`: uint - this argument to use to the `prev_index` query of atomic operation. +- `timeout`: uint - request timeout seconds. set 0 to disable timeout. + +Wait the update of key. + +```lua +local res, err = cli:wait('/path/to/key') +``` + +```lua +local res, err = cli:get('/path/to/key') + +-- Wait forever the update of key until that modifiedIndex of key has changed +-- to modifiedIndex + 1 +res, err = cli:wait('/path/to/key', res.body.node.modifiedIndex + 1, 0) + +-- Wait for 10 seconds the update of key until that modifiedIndex of key has +-- changed to modifiedIndex + 2 +res, err = cli:wait('/path/to/key', res.body.node.modifiedIndex + 2, 10) +``` + +[Back to TOP](#api-v2) + +### readdir + +`syntax: res, err = cli:readdir(dir:string [, recursive:boolean])` + +- `recursive`: boolean - get all the contents under a directory. + +Read the directory. + +```lua +local res, err = cli:readdir('/path/to/dir') +``` + +[Back to TOP](#api-v2) + +### mkdir + +`syntax: res, err = cli:mkdir(dir:string [, ttl:int])` + +Creates a directory. + +```lua +local res, err = cli:mkdir('/path/to/dir', 10) +``` + +[Back to TOP](#api-v2) + +### mkdirnx + +`syntax: res, err = cli:mkdirnx(dir:string [, ttl:int])` + +Creates a directory if that directory does not exist. + +```lua +local res, err = cli:mkdirnx('/path/to/dir', 10) +``` + +[Back to TOP](#api-v2) + +### rmdir + +`syntax: res, err = cli:rmdir(dir:string [, recursive:boolean])` + +- `recursive`: boolean - remove all the contents under a directory. + +Remove the directory + +```lua +local res, err = cli:rmdir('/path/to/dir') +``` + +[Back to TOP](#api-v2) + +### waitdir + +`syntax: res, err = cli:waitdir(dir:string [, modified_index:uint [, timeout:uint] ])` + + +- `modified_index`: uint - this argument to use to the `prev_index` query of atomic operation. +- `timeout`: uint - request timeout seconds. set 0 to disable timeout. + +```lua +local res, err = cli:waitdir('/path/to/dir') +``` + +[Back to TOP](#api-v2) + +### push + +`syntax: res, err = cli:push(dir:string, val:JSON value [, ttl:int])` + +Pushs a value into the specified directory. + +```lua +local res, err = cli:mkdir('/path/to/dir') +res, err = cli:push('/path/to/dir', 'val', 10) +``` + +[Back to TOP](#api-v2) + +### version + +`syntax: res, err = cli:version()` + +Gets the etcd version info. + +[Back to TOP](#api-v2) + +### stats_leader + +`syntax: res, err = cli:stats_leader()` + +Gets the leader statistics info. + +[Back to TOP](#api-v2) + +### stats_self + +`syntax: res, err = cli:stats_self()` + +Gets the self statistics info. + +[Back to TOP](#api-v2) + +### stats_store + +`syntax: res, err = cli:stats_store()` + +Gets the store statistics info. + +[Back to TOP](#api-v2) diff --git a/deps/lib64/luarocks/rocks/lua-resty-etcd/1.4.3-0/doc/api_v3.md b/deps/lib64/luarocks/rocks/lua-resty-etcd/1.4.3-0/doc/api_v3.md new file mode 100644 index 0000000..4492bbe --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-etcd/1.4.3-0/doc/api_v3.md @@ -0,0 +1,353 @@ +API V3 +====== + +* [Methods](#methods) + * [new](#new) + * [get](#get) + * [set](#set) + * [setnx](#setnx) + * [setx](#setx) + * [delete](#delete) + * [watch](#watch) + * [watchcancel](#watchcancel) + * [readdir](#readdir) + * [watchdir](#watchdir) + * [rmdir](#rmdir) + * [txn](#txn) + * [version](#version) + * [grant](#grant) + * [revoke](#revoke) + * [keepalive](#keepalive) + * [timetolive](#timetolive) + * [leases](#leases) + +Method +====== + +### new + +`syntax: cli, err = etcd.new([option:table])` + +- `option:table` + - `protocol`: string - `v3`. + - `http_host`: string - default `http://127.0.0.1:2379` + - `ttl`: int - default `-1` + default ttl for key operation. set -1 to disable ttl. + - `key_prefix`: string + append this prefix path string to key operation url. + - `timeout`: int + default request timeout seconds. + - `api_prefix`: string + to suit [etcd v3 api gateway](https://github.com/etcd-io/etcd/blob/master/Documentation/dev-guide/api_grpc_gateway.md#notes). + it will autofill by fetching etcd version if this option empty. + - `ssl_verify`: boolean - whether to verify the etcd certificate when originating TLS connection with etcd (if you want to communicate to etcd with TLS connection, use `https` scheme in your `http_host`), default is `true. + +The client method returns either a `etcd` object or an `error string`. + +```lua +local cli, err = require("resty.etcd").new({protocol = "v3"}) +``` + +Please refer to the **etcd API documentaion** at - https://github.com/coreos/etcd for more details. + +[Back to TOP](#api-v3) + +### get + +`syntax: res, err = cli:get(key:string[, opts])` + +* `key`: string value. +* `opts`: optional options. + * `timeout`: (int) request timeout seconds. set 0 to disable timeout. + * `revision`: (int) revision is the point-in-time of the key-value store to use for the range. If revision is less than or equal to zero, the range is over the newest key-value store. If the revision has been compacted, ErrCompacted is returned as a response. + +To get the value for key. + +```lua +local res, err = cli:get('/path/to/key') +``` + +[Back to TOP](#api-v3) + +### set + +`syntax: res, err = cli:set(key:string, val:JSON value [, opts:table])` + +* `key`: string value. +* `val`: the value which can be encoded via JSON. +* `opts`: optional options. + * `timeout`: (int) request timeout seconds. set 0 to disable timeout. + * `lease`: (int) the lease ID to associate with the key in the key-value store. + * `prev_kv`: (bool) If prev_kv is set, etcd gets the previous key-value pair before changing it. The previous key-value pair will be returned in the put response. + * `ignore_value`: (bool) If ignore_value is set, etcd updates the key using its current value. Returns an error if the key does not exist. + * `ignore_lease`: (bool) If ignore_lease is set, etcd updates the key using its current lease. Returns an error if the key does not exist. + +To set a key-value pair. + +```lua +local res, err = cli:set('/path/to/key', 'val', 10) +``` + +[Back to TOP](#api-v3) + +### setnx + +`syntax: res, err = cli:setnx(key:string, val:JSON value [, opts:table])` + +* `key`: string value. +* `val`: the value which can be encoded via JSON. +* `opts`: optional options. + * `timeout`: (int) request timeout seconds. set 0 to disable timeout. + +To set a key-value pair if that key does not exist. + +```lua +local res, err = cli:setnx('/path/to/key', 'val', 10) +``` + +[Back to TOP](#api-v3) + +### setx + +`syntax: res, err = cli:setx(key:string, val:JSON value [, opts:table])` + +* `key`: string value. +* `val`: the value which can be encoded via JSON. +* `opts`: optional options. + * `timeout`: (int) request timeout seconds. set 0 to disable timeout. + +To set a key-value pair when that key exists. + +```lua +local res, err = cli:setx('/path/to/key', 'val', 10) +``` + +[Back to TOP](#api-v3) + +### delete + +`syntax: res, err = cli:delete(key:string [, opts:table])` + +* `key`: string value. +* `opts`: optional options. + * `timeout`: (int) request timeout seconds. set 0 to disable timeout. + * `prev_kv`: (bool) If prev_kv is set, etcd gets the previous key-value pairs before deleting it. The previous key-value pairs will be returned in the delete response. + +To delete a key-value pair. + +```lua +local res, err = cli:delete('/path/to/key') +``` + +[Back to TOP](#api-v3) + + +### watch + +`syntax: res, err = cli:watch(key:string [, opts:table]) ` + +* `key`: string value. +* `opts`: optional options. + * `timeout`: (int) request timeout seconds. set 0 to disable timeout. + * `start_revision`: (int) start_revision is an optional revision to watch from (inclusive). No start_revision is "now". + * `progress_notify`: (bool) progress_notify is set so that the etcd server will periodically send a WatchResponse with no events to the new watcher if there are no recent events. + * `filters`: (slice of (enum FilterType {NOPUT = 0;NODELETE = 1;})) filters filter the events at server side before it sends back to the watcher. + * `prev_kv`: (bool) If prev_kv is set, created watcher gets the previous KV before the event happens. If the previous KV is already compacted, nothing will be returned. + * `watch_id`: (int) If watch_id is provided and non-zero, it will be assigned to this watcher. Since creating a watcher in etcd is not a synchronous operation, this can be used to ensure that ordering is correct when creating multiple watchers on the same stream. Creating a watcher with an ID already in use on the stream will cause an error to be returned. + * `fragment`: (bool) fragment enables splitting large revisions into multiple watch responses. + * `need_cancel`: (bool) if watch need to be cancel, watch would return http_cli for further cancelation. See [watchcancel](#watchcancel) for detail. + +To watch the update of key. + +```lua +local res, err = cli:watch('/path/to/key') +``` + +[Back to TOP](#api-v3) + +### watchcancel + +`syntax: res, err = cli:watchcancel(http_cli:table)` + +* `http_cli`: the http client needs to revoke. + +To cancel the watch before it get expired. Need to set `need_cancel` to get the http client for cancelation. + +```lua +local res, err, http_cli = cli:watch('/path/to/key', {need_cancel = true}) +res = cli:watchcancel(http_cli) +``` + +[Back to TOP](#api-v3) + +### readdir + +`syntax: res, err = cli:readdir(dir:string [, opts:table])` + +* `key`: string value. +* `opts`: optional options. + * `timeout`: (int) request timeout seconds. set 0 to disable timeout. + * `revision`: (int) revision is the point-in-time of the key-value store to use for the range. If revision is less than or equal to zero, the range is over the newest key-value store. If the revision has been compacted, ErrCompacted is returned as a response. + * `limit`: (int) limit is a limit on the number of keys returned for the request. When limit is set to 0, it is treated as no limit. + * `sort_order`: (int [SortNone:0, SortAscend:1, SortDescend:2]) sort_order is the order for returned sorted results. + * `sort_target`: (int [SortByKey:0, SortByVersion:1, SortByCreateRevision:2, SortByModRevision:3, SortByValue:4]) sort_target is the key-value field to use for sorting. + * `keys_only`: (bool) keys_only when set returns only the keys and not the values. + * `count_only`: (bool) count_only when set returns only the count of the keys in the range. + +To read the directory. + +```lua +local res, err = cli:readdir('/path/to/dir') +``` + +[Back to TOP](#api-v3) + + +### watchdir + +`syntax: res, err = cli:watchdir(dir:string [, opts:table])` + + +* `key`: string value. +* `opts`: optional options. + * `timeout`: (int) request timeout seconds. set 0 to disable timeout. + * `start_revision`: (int) start_revision is an optional revision to watch from (inclusive). No start_revision is "now". + * `progress_notify`: (bool) progress_notify is set so that the etcd server will periodically send a WatchResponse with no events to the new watcher if there are no recent events. + * `filters`: (slice of [enum FilterType {NOPUT = 0;NODELETE = 1;}]) filters filter the events at server side before it sends back to the watcher. + * `prev_kv`: (bool) If prev_kv is set, created watcher gets the previous KV before the event happens. If the previous KV is already compacted, nothing will be returned. + * `watch_id`: (int) If watch_id is provided and non-zero, it will be assigned to this watcher. Since creating a watcher in etcd is not a synchronous operation, this can be used to ensure that ordering is correct when creating multiple watchers on the same stream. Creating a watcher with an ID already in use on the stream will cause an error to be returned. + * `fragment`: (bool) fragment enables splitting large revisions into multiple watch responses. + +To watch the update of directory. + + +```lua +local res, err = cli:watchdir('/path/to/dir') +``` + +[Back to TOP](#api-v3) + + +### rmdir + +`syntax: res, err = cli:rmdir(dir:string [, opts:table])` + +* `key`: string value. +* `opts`: optional options. + * `timeout`: (int) request timeout seconds. set 0 to disable timeout. + * `prev_kv`: (bool) If prev_kv is set, etcd gets the previous key-value pairs before deleting it. The previous key-value pairs will be returned in the delete response. + +To remove the directory. + +```lua +local res, err = cli:rmdir('/path/to/dir') +``` + +[Back to TOP](#api-v3) + + +### txn + +`syntax: res, err = cli:txn(compare:array, success:array, failure:array [, opts:table])` + +* `compare`: array of [table](https://github.com/etcd-io/etcd/blob/master/Documentation/dev-guide/api_reference_v3.md#message-compare-etcdserveretcdserverpbrpcproto). +* `success`: array of [table](https://github.com/etcd-io/etcd/blob/master/Documentation/dev-guide/api_reference_v3.md#message-requestop-etcdserveretcdserverpbrpcproto). +* `failure`: array of [table](https://github.com/etcd-io/etcd/blob/master/Documentation/dev-guide/api_reference_v3.md#message-requestop-etcdserveretcdserverpbrpcproto). +* `opts`: optional options. + * `timeout`: (int) request timeout seconds. set 0 to disable timeout. + +Transaction. + +```lua +local compare = {} +compare[1] = {} +compare[1].target = "CREATE" +compare[1].key = encode_base64("test") +compare[1].createRevision = 0 + +local success = {} +success[1] = {} +success[1].requestPut = {} +success[1].requestPut.key = encode_base64("test") + +local res, err = cli:txn(compare, success, nil) +``` + +[Back to TOP](#api-v3) + + +### version + +`syntax: res, err = cli:version()` + +To get the etcd version info. + +[Back to TOP](#api-v3) + +### grant + +`syntax: res, err = cli:grant(TTL:int [, ID:int])` + +- `TTL`: advisory time-to-live in seconds. +- `ID`: the requested ID for the lease. If ID is set to 0, the lessor chooses an ID. + +To create a lease which expires if the server does not receive a keepalive within a given time to live period. All keys attached to the lease will get expired and be deleted if the lease expires. Each expired key generates a delete event in the event history. + +```lua +-- grant a lease with 5 second TTL +local res, err = cli:grant(5) + +-- attach key to lease, whose ID would be contained in res +local data, err = etcd:set('/path/to/key', 'val', {lease = res.body.ID}) +``` + +[Back to TOP](#api-v3) + +### revoke + +`syntax: res, err = cli:revoke(ID:int)` + +- `ID`: the lease ID to revoke. When the ID is revoked, all associated keys will be deleted. + +To revoke a lease. All keys attached to the lease will expire and be deleted. + +```lua +local res, err = cli:grant(5) +local data, err = etcd:set('/path/to/key', 'val', {lease = res.body.ID}) + +local data, err = etcd:revoke(res.body.ID) +local data, err = cli:get('/path/to/key') +-- responce would contains no kvs +``` + +[Back to TOP](#api-v3) + +### keepalive + +`syntax: res, err = cli:keepalive(ID:int)` + +- `ID`: the lease ID for the lease to keep alive. + +To keep the lease alive by streaming keep alive requests from the client to the server and streaming keep alive responses from the server to the client. + +[Back to TOP](#api-v3) + +### timetolive + +`syntax: res, err = cli:timetolive(ID:int [, keys: bool])` + +- `ID`: the lease ID for the lease. +- `keys`: if true, query all the keys attached to this lease. + +To retrieve lease information. + +[Back to TOP](#api-v3) + +### leases + +`syntax: res, err = cli:leases()` + +To list all existing leases. + +[Back to TOP](#api-v3) + diff --git a/deps/lib64/luarocks/rocks/lua-resty-etcd/1.4.3-0/lua-resty-etcd-1.4.3-0.rockspec b/deps/lib64/luarocks/rocks/lua-resty-etcd/1.4.3-0/lua-resty-etcd-1.4.3-0.rockspec new file mode 100644 index 0000000..6dc6996 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-etcd/1.4.3-0/lua-resty-etcd-1.4.3-0.rockspec @@ -0,0 +1,30 @@ +package = "lua-resty-etcd" +version = "1.4.3-0" +source = { + url = "git://github.com/api7/lua-resty-etcd", + tag = "v1.4.3" +} + +description = { + summary = "Nonblocking Lua etcd driver library for OpenResty", + homepage = "https://github.com/api7/lua-resty-etcd", + license = "Apache License 2.0", + maintainer = "Yuansheng Wang " +} + +dependencies = { + "lua-resty-http = 0.15", + "lua-typeof = 0.1" +} + +build = { + type = "builtin", + modules = { + ["resty.etcd"] = "lib/resty/etcd.lua", + ["resty.etcd.v2"] = "lib/resty/etcd/v2.lua", + ["resty.etcd.v3"] = "lib/resty/etcd/v3.lua", + ["resty.etcd.utils"] = "lib/resty/etcd/utils.lua", + ["resty.etcd.serializers.json"] = "lib/resty/etcd/serializers/json.lua", + ["resty.etcd.serializers.raw"] = "lib/resty/etcd/serializers/raw.lua", + } +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-etcd/1.4.3-0/rock_manifest b/deps/lib64/luarocks/rocks/lua-resty-etcd/1.4.3-0/rock_manifest new file mode 100644 index 0000000..4ab0226 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-etcd/1.4.3-0/rock_manifest @@ -0,0 +1,23 @@ +rock_manifest = { + doc = { + LICENSE = "86d3f3a95c324c9479bd8986968f4327", + ["README.md"] = "370d4b3709dbc8e5b35e605f17a38d1c", + ["api_v2.md"] = "07a6b7ce7e3959b61843c8732d64445b", + ["api_v3.md"] = "7f962413a6c9c223e2bd5a8e4ce59204" + }, + lua = { + resty = { + etcd = { + serializers = { + ["json.lua"] = "94b2b2a2158b142978500bd0637377c3", + ["raw.lua"] = "c7268ab622ec4c9b5a0a2ad9edc8f45f" + }, + ["utils.lua"] = "e4016236f8f8cf13a1478ff158a0712d", + ["v2.lua"] = "0b185beab3fd1f1246ce81b0588df476", + ["v3.lua"] = "fcf3efb2ecd423b6f30da170d2f72d5e" + }, + ["etcd.lua"] = "87c5ded7fd2de277fb332ac7e8995aba" + } + }, + ["lua-resty-etcd-1.4.3-0.rockspec"] = "8b93954808eac086864569874543dbec" +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-expr/1.0.0-0/doc/LICENSE b/deps/lib64/luarocks/rocks/lua-resty-expr/1.0.0-0/doc/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-expr/1.0.0-0/doc/LICENSE @@ -0,0 +1,201 @@ + 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/deps/lib64/luarocks/rocks/lua-resty-expr/1.0.0-0/doc/README.md b/deps/lib64/luarocks/rocks/lua-resty-expr/1.0.0-0/doc/README.md new file mode 100644 index 0000000..6037f0c --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-expr/1.0.0-0/doc/README.md @@ -0,0 +1,124 @@ +# lua-resty-expr + +## Name + +A tiny DSL to evaluate expressions which is used inside of APISIX. + +[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/api7/lua-resty-expr/blob/main/LICENSE) + +This project has been working in microservices API gateway [Apache APISIX](https://github.com/apache/incubator-apisix). + +The project is open sourced by [Shenzhen ZhiLiu](https://www.apiseven.com/) Technology Co., Ltd. + +In addition to this open source version, our company also provides a more powerful and performing commercial version, and provides technical support. If you are interested in our commercial version, please [contact us](https://www.apiseven.com/). + +Table of Contents +================= + +* [lua-resty-expr](#lua-resty-expr) + * [Name](#name) + * [Synopsis](#synopsis) + * [Methods](#methods) + * [new](#new) + * [Operator List](#operator-list) + * [eval](#eval) + * [Install](#install) + * [Compile and install](#compile-and-install) + * [DEV ENV](#dev-env) + * [Install Dependencies](#install-dependencies) + +## Synopsis + +```lua + location / { + content_by_lua_block { + local expr = require("resty.expr.v1") + local ex = expr.new({ + { + {"arg_name", "==", "json"}, + {"arg_weight", ">", 10}, + {"arg_weight", "!", ">", 15}, + } + }) + + -- equal to + -- 'ngx.say(ngx.var.arg_name == "json" and ngx.var.arg_weight > 10 and not ngx.var.arg_weight > 15)' + ngx.say(ex:eval(ngx.var)) + } + } +``` + +[Back to TOC](#table-of-contents) + +## Methods + +### new + +`syntax: ex, err = expr.new(rule)` + +Create a expression object which can be evaluated later. + +The syntax of rule is an array table of expressions. +Each expression is an array table which has three elements: +```lua +{ + {"var name (aka. left value)", "optional '!' operator", "operator", "const value (aka. right value)"}, + ... +} +``` + +[Back to TOC](#table-of-contents) + +#### Operator List + +|operator|description|example| +|--------|-----------|-------| +|== |equal |{"arg_name", "==", "json"}| +|~= |not equal |{"arg_name", "~=", "json"}| +|> |greater than|{"arg_age", ">", 24}| +|< |less than |{"arg_age", "<", 24}| +|~~ |Regular match|{"arg_name", "~~", "[a-z]+"}| +|~* |Case insensitive regular match|{"arg_name", "~*", "[a-z]+"}| +|in |find in array|{"arg_name", "in", {"1","2"}}| +|has |left value array has value in the right |{"graphql_root_fields", "has", "repo"}| +|! |reverse the result|{"arg_name", "!", "~~", "[a-z]+"}| + +[Back to TOC](#table-of-contents) + +### eval + +`syntax: ok, err = ex:eval(ctx)` + +Evaluate the expression according to the `ctx`. If `ctx` is missing, `ngx.var` is used by default. + +```lua +local ok = rx:eval() +if ok == nil then + log_err("failed to eval expression: ", err) + return false +end + +return ok +``` + +[Back to TOC](#table-of-contents) + +## Install + +### Compile and install + +```shell +make install +``` + +[Back to TOC](#table-of-contents) + +## DEV ENV + +### Install Dependencies + +```shell +make deps +``` +[Back to TOC](#table-of-contents) + diff --git a/deps/lib64/luarocks/rocks/lua-resty-expr/1.0.0-0/lua-resty-expr-1.0.0-0.rockspec b/deps/lib64/luarocks/rocks/lua-resty-expr/1.0.0-0/lua-resty-expr-1.0.0-0.rockspec new file mode 100644 index 0000000..0f015e8 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-expr/1.0.0-0/lua-resty-expr-1.0.0-0.rockspec @@ -0,0 +1,24 @@ +package = "lua-resty-expr" +version = "1.0.0-0" +source = { + url = "git://github.com/api7/lua-resty-expr", + tag = "v1.0.0" +} + +description = { + summary = "A tiny DSL to evaluate expressions which is used inside of APISIX", + homepage = "https://github.com/api7/lua-resty-expr", + license = "Apache License 2.0", + maintainer = "Yuansheng Wang " +} + +dependencies = { +} + + +build = { + type = "builtin", + modules = { + ["resty.expr.v1"] = "lib/resty/expr/v1.lua", + } +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-expr/1.0.0-0/rock_manifest b/deps/lib64/luarocks/rocks/lua-resty-expr/1.0.0-0/rock_manifest new file mode 100644 index 0000000..87ec3c0 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-expr/1.0.0-0/rock_manifest @@ -0,0 +1,14 @@ +rock_manifest = { + doc = { + LICENSE = "86d3f3a95c324c9479bd8986968f4327", + ["README.md"] = "b60f0fe9e5291b12e383f5b7f50e0945" + }, + lua = { + resty = { + expr = { + ["v1.lua"] = "bcd1c24bfa3d195a2852a90d3598dbcf" + } + } + }, + ["lua-resty-expr-1.0.0-0.rockspec"] = "4257a93839de0a5cc8b2bc34a1f0313d" +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-healthcheck-api7/2.2.0-0/doc/LICENSE b/deps/lib64/luarocks/rocks/lua-resty-healthcheck-api7/2.2.0-0/doc/LICENSE new file mode 100644 index 0000000..8dada3e --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-healthcheck-api7/2.2.0-0/doc/LICENSE @@ -0,0 +1,201 @@ + 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/deps/lib64/luarocks/rocks/lua-resty-healthcheck-api7/2.2.0-0/doc/readme.md b/deps/lib64/luarocks/rocks/lua-resty-healthcheck-api7/2.2.0-0/doc/readme.md new file mode 100644 index 0000000..622e0ce --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-healthcheck-api7/2.2.0-0/doc/readme.md @@ -0,0 +1,188 @@ +# lua-resty-healthcheck + +[![Build Status][badge-travis-image]][badge-travis-url] + +A health check library for OpenResty. + +## Synopsis + +```nginx +http { + lua_shared_dict test_shm 8m; + lua_shared_dict my_worker_events 8m; + init_worker_by_lua_block { + + local we = require "resty.worker.events" + local ok, err = we.configure({ + shm = "my_worker_events", + interval = 0.1 + }) + if not ok then + ngx.log(ngx.ERR, "failed to configure worker events: ", err) + return + end + + local healthcheck = require("resty.healthcheck") + local checker = healthcheck.new({ + name = "testing", + shm_name = "test_shm", + checks = { + active = { + type = "https", + http_path = "/status", + healthy = { + interval = 2, + successes = 1, + }, + unhealthy = { + interval = 1, + http_failures = 2, + } + }, + } + }) + + local ok, err = checker:add_target("127.0.0.1", 8080, "example.com", false) + + local handler = function(target, eventname, sourcename, pid) + ngx.log(ngx.DEBUG,"Event from: ", sourcename) + if eventname == checker.events.remove + -- a target was removed + ngx.log(ngx.DEBUG,"Target removed: ", + target.ip, ":", target.port, " ", target.hostname) + elseif eventname == checker.events.healthy + -- target changed state, or was added + ngx.log(ngx.DEBUG,"Target switched to healthy: ", + target.ip, ":", target.port, " ", target.hostname) + elseif eventname == checker.events.unhealthy + -- target changed state, or was added + ngx.log(ngx.DEBUG,"Target switched to unhealthy: ", + target.ip, ":", target.port, " ", target.hostname) + else + -- unknown event + end + end + } +} +``` + +## Description + +This library supports performing active and passive health checks on arbitrary hosts. + +Control of the library happens via its programmatic API. Consumption of its events +happens via the [lua-resty-worker-events](https://github.com/Kong/lua-resty-worker-events) library. + +Targets are added using `checker:add_target(host, port)`. +Changes in status ("healthy" or "unhealthy") are broadcasted via worker-events. + +Active checks are executed in the background based on the specified timer intervals. + +For passive health checks, the library receives explicit notifications via its +programmatic API using functions such as `checker:report_http_status(host, port, status)`. + +See the [online LDoc documentation](http://kong.github.io/lua-resty-healthcheck) +for the complete API. + +## History + +Versioning is strictly based on [Semantic Versioning](https://semver.org/) + +### 1.2.0 (13-Feb-2020) + + * Adds `set_all_target_statuses_for_hostname`, which sets the targets for + all entries with a given hostname at once. + +### 1.1.2 (19-Dec-2019) + + * Fix: when `ngx.sleep` API is not available (e.g. in the log phase) it is not + possible to lock using lua-resty-lock and any function that needs exclusive + access would fail. This fix adds a retry method that starts a new light + thread, which has access to `ngx.sleep`, to lock the critical path. + [#37](https://github.com/Kong/lua-resty-healthcheck/pull/37); + +### 1.1.1 (14-Nov-2019) + + * Fix: fail when it is not possible to get exclusive access to the list of + targets. This fix prevents that workers get to an inconsistent state. + [#34](https://github.com/Kong/lua-resty-healthcheck/pull/34); + +### 1.1.0 (30-Sep-2019) + + * Add support for setting the custom `Host` header to be used for active checks. + * Fix: log error on SSL Handshake failure + [#28](https://github.com/Kong/lua-resty-healthcheck/pull/28); + +### 1.0.0 (05-Jul-2019) + + * BREAKING: all API functions related to hosts require a `hostname` argument + now. This way different hostnames listening on the same IP and ports + combination do not have an effect on each other. + * Fix: fix reporting active TCP probe successes + [#20](https://github.com/Kong/lua-resty-healthcheck/pull/20); + fixes issue [#19](https://github.com/Kong/lua-resty-healthcheck/issues/19) + +### 0.6.1 (04-Apr-2019) + + * Fix: set up event callback only after target list is loaded + [#18](https://github.com/Kong/lua-resty-healthcheck/pull/18); + fixes Kong issue [#4453](https://github.com/Kong/kong/issues/4453) + +### 0.6.0 (26-Sep-2018) + + * Introduce `checks.active.https_verify_certificate` field. + It is `true` by default; setting it to `false` disables certificate + verification in active healthchecks over HTTPS. + +### 0.5.0 (25-Jul-2018) + + * Add support for `https` -- thanks @gaetanfl for the PR! + * Introduce separate `checks.active.type` and `checks.passive.type` fields; + the top-level `type` field is still supported as a fallback but is now + deprecated. + +### 0.4.2 (23-May-2018) + + * Fix `Host` header in active healthchecks + +### 0.4.1 (21-May-2018) + + * Fix internal management of healthcheck counters + +### 0.4.0 (20-Mar-2018) + + * Correct setting of defaults in `http_statuses` + * Type and bounds checking to `checks` table + +### 0.3.0 (18-Dec-2017) + + * Disable individual checks by setting their counters to 0 + +### 0.2.0 (30-Nov-2017) + + * Adds `set_target_status` + +### 0.1.0 (27-Nov-2017) Initial release + + * Initial upload + +## Copyright and License + +``` +Copyright 2017-2019 Kong Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +``` + +[badge-travis-url]: https://travis-ci.org/Kong/lua-resty-healthcheck/branches +[badge-travis-image]: https://travis-ci.org/Kong/lua-resty-healthcheck.svg?branch=master diff --git a/deps/lib64/luarocks/rocks/lua-resty-healthcheck-api7/2.2.0-0/lua-resty-healthcheck-api7-2.2.0-0.rockspec b/deps/lib64/luarocks/rocks/lua-resty-healthcheck-api7/2.2.0-0/lua-resty-healthcheck-api7-2.2.0-0.rockspec new file mode 100644 index 0000000..7e12b48 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-healthcheck-api7/2.2.0-0/lua-resty-healthcheck-api7-2.2.0-0.rockspec @@ -0,0 +1,26 @@ +package = "lua-resty-healthcheck-api7" +version = "2.2.0-0" +source = { + url = "git://github.com/api7/lua-resty-healthcheck", + tag = "v2.2.0" +} +description = { + summary = "Healthchecks for OpenResty to check upstream service status", + detailed = [[ + lua-resty-healthcheck is a module that can check upstream service + availability by sending requests and validating responses at timed + intervals. + ]], + homepage = "https://github.com/api7/lua-resty-healthcheck", + license = "Apache 2.0" +} +dependencies = { + "lua-resty-worker-events = 1.0.0" +} +build = { + type = "builtin", + modules = { + ["resty.healthcheck"] = "lib/resty/healthcheck.lua", + ["resty.healthcheck.utils"] = "lib/resty/healthcheck/utils.lua" + } +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-healthcheck-api7/2.2.0-0/rock_manifest b/deps/lib64/luarocks/rocks/lua-resty-healthcheck-api7/2.2.0-0/rock_manifest new file mode 100644 index 0000000..14bbb22 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-healthcheck-api7/2.2.0-0/rock_manifest @@ -0,0 +1,15 @@ +rock_manifest = { + doc = { + LICENSE = "e3fc50a88d0a364313df4b21ef20c29e", + ["readme.md"] = "b1824e06f1a1c40ce86e3fc6368435ca" + }, + lua = { + resty = { + healthcheck = { + ["utils.lua"] = "4a8d6515f71a21fb85d7eb99747cf0cf" + }, + ["healthcheck.lua"] = "cc7fc2ac7484aaf05c9b28a4e46b0197" + } + }, + ["lua-resty-healthcheck-api7-2.2.0-0.rockspec"] = "a78b5b6ddc77c305b66bc6c652da7eb3" +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-hmac-ffi/0.05-0/doc/README.markdown b/deps/lib64/luarocks/rocks/lua-resty-hmac-ffi/0.05-0/doc/README.markdown new file mode 100644 index 0000000..d441bf6 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-hmac-ffi/0.05-0/doc/README.markdown @@ -0,0 +1,214 @@ +Name +==== + +lua-resty-hmac - HMAC functions for ngx_lua and LuaJIT + +Table of Contents +================= + +* [Name](#name) +* [Status](#status) +* [Description](#description) +* [Synopsis](#synopsis) +* [Methods](#methods) + * [new](#new) + * [update](#update) + * [final](#final) + * [reset](#reset) +* [Prerequisites](#prerequisites) +* [Installation](#installation) +* [Copyright and License](#copyright-and-license) +* [See Also](#see-also) + +Status +====== + +This library is still under active development and is considered production ready. + +Description +=========== + +This library requires an nginx build with OpenSSL, +the [ngx_lua module](http://wiki.nginx.org/HttpLuaModule), and [LuaJIT 2.0](http://luajit.org/luajit.html). + +Synopsis +======== + +```lua + # nginx.conf: + + lua_package_path "/path/to/lua-resty-hmac/lib/?.lua;;"; + + server { + location = /test { + content_by_lua_file conf/test.lua; + } + } + + -- conf/test.lua: + + local hmac = require "resty.hmac" + + local hmac_sha1 = hmac:new("secret_key", hmac.ALGOS.SHA1) + if not hmac_sha1 then + ngx.say("failed to create the hmac_sha1 object") + return + end + + local ok = hmac_sha1:update("he") + if not ok then + ngx.say("failed to add data") + return + end + + ok = hmac_sha1:update("llo") + if not ok then + ngx.say("failed to add data") + return + end + + local mac = hmac_sha1:final() -- binary mac + + local str = require "resty.string" + ngx.say("hmac_sha1: ", str.to_hex(mac)) + -- output: "hmac_sha1: aee4b890b574ea8fa4f6a66aed96c3e590e5925a" + + -- dont forget to reset after final! + if not hmac_sha1:reset() then + ngx.say("failed to reset hmac_sha1") + return + end + + -- short version + ngx.say("hmac_sha1: ", hmac_sha1:final("world", true)) + -- output: "hmac_sha1: 4e9538f1efbe565c522acfb72fce6092ea6b15e0" +``` + +[Back to TOC](#table-of-contents) + +Methods +======= + +To load this library, + +1. you need to specify this library's path in ngx_lua's [lua_package_path](https://github.com/openresty/lua-nginx-module#lua_package_path) directive. For example, `lua_package_path "/path/to/lua-resty-hmac/lib/?.lua;;";`. +2. you use `require` to load the library into a local Lua variable: + +```lua + local hmac = require "resty.hmac" +``` + +[Back to TOC](#table-of-contents) + +new +--- +`syntax: local hmac_sha256 = hmac:new(key [, hash_algorithm])` + +Creates a new hmac instance. If failed, returns `nil`. + +The `key` argument specifies the key to use when calculating the message authentication code (MAC). +`key` is a lua string which may contain printable characters or binary data. + +The `hash_algorithm` argument specifies which hashing algorithm to use (`hmac.ALGOS.MD5`, `hmac.ALGOS.SHA1`, `hmac.ALGOS.SHA256`, `hmac.ALGOS.SHA512`). +The default value is `hmac.ALGOS.MD5`. + +[Back to TOC](#table-of-contents) + +update +--- +`syntax: hmac_sha256:update(data)` + +Updates the MAC calculation to include new data. If failed, returns `false`. + +The `data` argument specifies the additional data to include in the MAC. +`data` is a lua string which may contain printable characters or binary data. + +[Back to TOC](#table-of-contents) + +final +--- +`syntax: local mac = hmac_sha256:final([data, output_hex])` + +Finalizes the MAC calculation and returns the final MAC value. If failed, returns `nil`. +When `output_hex` is not `true` returns a lua string containing the raw, binary MAC. When `output_hex` is `true` returns a lua string containing the hexadecimal representation of the MAC. + +The `data` argument specifies the additional data to include in the MAC before finalizing the calculation. +The default value is `nil`. + +The `output_hex` argument specifies wether the MAC should be returned as hex or binary. If `true` the MAC will be returned as hex. +The default value is `false`. + +[Back to TOC](#table-of-contents) + +reset +------ +`syntax: hmac_sha256:reset()` + +Resets the internal hmac context so it can be re-used to calculate a new MAC. If failed, returns `false`. +If successful, the `key` and `hash_algorithm` remain the same but all other information is cleared. + +This MUST be called after `hmac_sha256:final()` in order to calculate a new MAC using the same hmac instance. + +[Back to TOC](#table-of-contents) + +Prerequisites +============= + +* [LuaJIT](http://luajit.org) 2.0+ +* [ngx_lua module](http://wiki.nginx.org/HttpLuaModule) +* [lua-resty-string](https://github.com/openresty/lua-resty-string) 0.8+ +* [OpenSSL](https://www.openssl.org/) 1.0.0+ + +[Back to TOC](#table-of-contents) + +Installation +============ + +It is recommended to use the latest [ngx_openresty bundle](http://openresty.org) directly. You'll need to enable LuaJIT when building your ngx_openresty +bundle by passing the `--with-luajit` option to its `./configure` script. + +Also, You need to configure +the [lua_package_path](https://github.com/openresty/lua-nginx-module#lua_package_path) directive to +add the path of your lua-resty-hmac source tree to ngx_lua's Lua module search path, as in + +```nginx + # nginx.conf + http { + lua_package_path "/path/to/lua-resty-hmac/lib/?.lua;;"; + ... + } +``` + +and then load the library in Lua: + +```lua + local hmac = require "resty.hmac" +``` + +[Back to TOC](#table-of-contents) + +Copyright and License +===================== + +This module is licensed under the BSD license. + +Copyright (C) 2012-2020, Thought Foundry Inc. + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. + +[Back to TOC](#table-of-contents) + +See Also +======== +* the ngx_lua module: http://wiki.nginx.org/HttpLuaModule + +[Back to TOC](#table-of-contents) + diff --git a/deps/lib64/luarocks/rocks/lua-resty-hmac-ffi/0.05-0/lua-resty-hmac-ffi-0.05-0.rockspec b/deps/lib64/luarocks/rocks/lua-resty-hmac-ffi/0.05-0/lua-resty-hmac-ffi-0.05-0.rockspec new file mode 100644 index 0000000..adc5a7d --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-hmac-ffi/0.05-0/lua-resty-hmac-ffi-0.05-0.rockspec @@ -0,0 +1,24 @@ +package = 'lua-resty-hmac-ffi' +version = '0.05-0' + +source = { + url = 'git://github.com/jkeys089/lua-resty-hmac', + tag = 'v0.05' +} + +description = { + summary = 'HMAC functions for ngx_lua and LuaJIT', + homepage = 'https://github.com/jkeys089/lua-resty-hmac', + license = 'BSD-2-Clause License' +} + +dependencies = { + 'lua == 5.1' +} + +build = { + type = 'builtin', + modules = { + ['resty.hmac'] = 'lib/resty/hmac.lua' + } +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-hmac-ffi/0.05-0/rock_manifest b/deps/lib64/luarocks/rocks/lua-resty-hmac-ffi/0.05-0/rock_manifest new file mode 100644 index 0000000..f82558f --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-hmac-ffi/0.05-0/rock_manifest @@ -0,0 +1,11 @@ +rock_manifest = { + doc = { + ["README.markdown"] = "a0bfe06b489ea5293c79e675c0bb4540" + }, + lua = { + resty = { + ["hmac.lua"] = "e9d7934d0d50529cae9f1bfb472c266c" + } + }, + ["lua-resty-hmac-ffi-0.05-0.rockspec"] = "4919fabe13aa09d0326f846b6e85d897" +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-http/0.15-0/doc/LICENSE b/deps/lib64/luarocks/rocks/lua-resty-http/0.15-0/doc/LICENSE new file mode 100644 index 0000000..f108ed7 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-http/0.15-0/doc/LICENSE @@ -0,0 +1,23 @@ +Copyright (c) 2013, James Hurst +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. \ No newline at end of file diff --git a/deps/lib64/luarocks/rocks/lua-resty-http/0.15-0/doc/README.md b/deps/lib64/luarocks/rocks/lua-resty-http/0.15-0/doc/README.md new file mode 100644 index 0000000..857484c --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-http/0.15-0/doc/README.md @@ -0,0 +1,477 @@ +# lua-resty-http + +Lua HTTP client cosocket driver for [OpenResty](http://openresty.org/) / [ngx_lua](https://github.com/openresty/lua-nginx-module). + +# Status + +Production ready. + +# Features + +* HTTP 1.0 and 1.1 +* SSL +* Streaming interface to the response body, for predictable memory usage +* Alternative simple interface for singleshot requests without manual connection step +* Chunked and non-chunked transfer encodings +* Keepalive +* Pipelining +* Trailers + + +# API + +* [new](#new) +* [connect](#connect) +* [connect_proxy](#connect_proxy) +* [set_proxy_options](#set_proxy_options) +* [set_timeout](#set_timeout) +* [set_timeouts](#set_timeouts) +* [ssl_handshake](#ssl_handshake) +* [set_keepalive](#set_keepalive) +* [get_reused_times](#get_reused_times) +* [close](#close) +* [request](#request) +* [request_uri](#request_uri) +* [request_pipeline](#request_pipeline) +* [Response](#response) + * [body_reader](#resbody_reader) + * [read_body](#resread_body) + * [read_trailers](#resread_trailers) +* [Proxy](#proxy) + * [proxy_request](#proxy_request) + * [proxy_response](#proxy_response) +* [Utility](#utility) + * [parse_uri](#parse_uri) + * [get_client_body_reader](#get_client_body_reader) + + +## Synopsis + +```` lua +lua_package_path "/path/to/lua-resty-http/lib/?.lua;;"; + +server { + + + location /simpleinterface { + resolver 8.8.8.8; # use Google's open DNS server for an example + + content_by_lua_block { + + -- For simple singleshot requests, use the URI interface. + local http = require "resty.http" + local httpc = http.new() + local res, err = httpc:request_uri("http://example.com/helloworld", { + method = "POST", + body = "a=1&b=2", + headers = { + ["Content-Type"] = "application/x-www-form-urlencoded", + }, + keepalive_timeout = 60, + keepalive_pool = 10 + }) + + if not res then + ngx.say("failed to request: ", err) + return + end + + -- In this simple form, there is no manual connection step, so the body is read + -- all in one go, including any trailers, and the connection closed or keptalive + -- for you. + + ngx.status = res.status + + for k,v in pairs(res.headers) do + -- + end + + ngx.say(res.body) + } + } + + + location /genericinterface { + content_by_lua_block { + + local http = require "resty.http" + local httpc = http.new() + + -- The generic form gives us more control. We must connect manually. + httpc:set_timeout(500) + httpc:connect("127.0.0.1", 80) + + -- And request using a path, rather than a full URI. + local res, err = httpc:request({ + path = "/helloworld", + headers = { + ["Host"] = "example.com", + }, + }) + + if not res then + ngx.say("failed to request: ", err) + return + end + + -- Now we can use the body_reader iterator, to stream the body according to our desired chunk size. + local reader = res.body_reader + + repeat + local chunk, err = reader(8192) + if err then + ngx.log(ngx.ERR, err) + break + end + + if chunk then + -- process + end + until not chunk + + local ok, err = httpc:set_keepalive() + if not ok then + ngx.say("failed to set keepalive: ", err) + return + end + } + } +} +```` + +# Connection + +## new + +`syntax: httpc = http.new()` + +Creates the http object. In case of failures, returns `nil` and a string describing the error. + +## connect + +`syntax: ok, err = httpc:connect(host, port, options_table?)` + +`syntax: ok, err = httpc:connect("unix:/path/to/unix.sock", options_table?)` + +Attempts to connect to the web server. + +Before actually resolving the host name and connecting to the remote backend, this method will always look up the connection pool for matched idle connections created by previous calls of this method. + +An optional Lua table can be specified as the last argument to this method to specify various connect options: + +* `pool` +: Specifies a custom name for the connection pool being used. If omitted, then the connection pool name will be generated from the string template `:` or ``. + +## connect_proxy + +`syntax: ok, err = httpc:connect_proxy(proxy_uri, scheme, host, port, proxy_authorization)` + +Attempts to connect to the web server through the given proxy server. The method accepts the following arguments: + +* `proxy_uri` - Full URI of the proxy server to use (e.g. `http://proxy.example.com:3128/`). Note: Only `http` protocol is supported. +* `scheme` - The protocol to use between the proxy server and the remote host (`http` or `https`). If `https` is specified as the scheme, `connect_proxy()` makes a `CONNECT` request to establish a TCP tunnel to the remote host through the proxy server. +* `host` - The hostname of the remote host to connect to. +* `port` - The port of the remote host to connect to. +* `proxy_authorization` - The `Proxy-Authorization` header value sent to the proxy server via `CONNECT` when the `scheme` is `https`. + +If an error occurs during the connection attempt, this method returns `nil` with a string describing the error. If the connection was successfully established, the method returns `1`. + +There's a few key points to keep in mind when using this api: + +* If the scheme is `https`, you need to perform the TLS handshake with the remote server manually using the `ssl_handshake()` method before sending any requests through the proxy tunnel. +* If the scheme is `http`, you need to ensure that the requests you send through the connections conforms to [RFC 7230](https://tools.ietf.org/html/rfc7230) and especially [Section 5.3.2.](https://tools.ietf.org/html/rfc7230#section-5.3.2) which states that the request target must be in absolute form. In practice, this means that when you use `send_request()`, the `path` must be an absolute URI to the resource (e.g. `http://example.com/index.html` instead of just `/index.html`). + +## set_timeout + +`syntax: httpc:set_timeout(time)` + +Sets the timeout (in ms) protection for subsequent operations, including the `connect` method. + +## set_timeouts + +`syntax: httpc:set_timeouts(connect_timeout, send_timeout, read_timeout)` + +Sets the connect timeout threshold, send timeout threshold, and read timeout threshold, respectively, in milliseconds, for subsequent socket operations (connect, send, receive, and iterators returned from receiveuntil). + +## ssl_handshake + +`syntax: session, err = httpc:ssl_handshake(session, host, verify)` + +Performs an SSL handshake on the TCP connection, only available in ngx_lua > v0.9.11 + +See docs for [ngx.socket.tcp](https://github.com/openresty/lua-nginx-module#ngxsockettcp) for details. + +## set_keepalive + +`syntax: ok, err = httpc:set_keepalive(max_idle_timeout, pool_size)` + +Attempts to puts the current connection into the ngx_lua cosocket connection pool. + +You can specify the max idle timeout (in ms) when the connection is in the pool and the maximal size of the pool every nginx worker process. + +Only call this method in the place you would have called the `close` method instead. Calling this method will immediately turn the current http object into the `closed` state. Any subsequent operations other than `connect()` on the current object will return the `closed` error. + +Note that calling this instead of `close` is "safe" in that it will conditionally close depending on the type of request. Specifically, a `1.0` request without `Connection: Keep-Alive` will be closed, as will a `1.1` request with `Connection: Close`. + +In case of success, returns `1`. In case of errors, returns `nil, err`. In the case where the connection is conditionally closed as described above, returns `2` and the error string `connection must be closed`. + +## set_proxy_options + +`syntax: httpc:set_proxy_options(opts)` + +Configure an http proxy to be used with this client instance. The `opts` is a table that accepts the following fields: + +* `http_proxy` - an URI to a proxy server to be used with http requests +* `http_proxy_authorization` - a default `Proxy-Authorization` header value to be used with `http_proxy`, e.g. `Basic ZGVtbzp0ZXN0`, which will be overriden if the `Proxy-Authorization` request header is present. +* `https_proxy` - an URI to a proxy server to be used with https requests +* `https_proxy_authorization` - as `http_proxy_authorization` but for use with `https_proxy`. +* `no_proxy` - a comma separated list of hosts that should not be proxied. + +Note that proxy options are only applied when using the high-level `request_uri()` API. + +## get_reused_times + +`syntax: times, err = httpc:get_reused_times()` + +This method returns the (successfully) reused times for the current connection. In case of error, it returns `nil` and a string describing the error. + +If the current connection does not come from the built-in connection pool, then this method always returns `0`, that is, the connection has never been reused (yet). If the connection comes from the connection pool, then the return value is always non-zero. So this method can also be used to determine if the current connection comes from the pool. + +## close + +`syntax: ok, err = http:close()` + +Closes the current connection and returns the status. + +In case of success, returns `1`. In case of errors, returns `nil` with a string describing the error. + + +# Requesting + +## request + +`syntax: res, err = httpc:request(params)` + +Returns a `res` table or `nil` and an error message. + +The `params` table accepts the following fields: + +* `version` The HTTP version number, currently supporting 1.0 or 1.1. +* `method` The HTTP method string. +* `path` The path string. +* `query` The query string, presented as either a literal string or Lua table.. +* `headers` A table of request headers. +* `body` The request body as a string, or an iterator function (see [get_client_body_reader](#get_client_body_reader)). +* `ssl_verify` Verify SSL cert matches hostname + +When the request is successful, `res` will contain the following fields: + +* `status` The status code. +* `reason` The status reason phrase. +* `headers` A table of headers. Multiple headers with the same field name will be presented as a table of values. +* `has_body` A boolean flag indicating if there is a body to be read. +* `body_reader` An iterator function for reading the body in a streaming fashion. +* `read_body` A method to read the entire body into a string. +* `read_trailers` A method to merge any trailers underneath the headers, after reading the body. + +## request_uri + +`syntax: res, err = httpc:request_uri(uri, params)` + +The simple interface. Options supplied in the `params` table are the same as in the generic interface, and will override components found in the uri itself. + +There are 3 additional parameters for controlling keepalives: + +* `keepalive` Set to `false` to disable keepalives and immediately close the connection. +* `keepalive_timeout` The maximal idle timeout (ms). Defaults to `lua_socket_keepalive_timeout`. +* `keepalive_pool` The maximum number of connections in the pool. Defaults to `lua_socket_pool_size`. + +In this mode, there is no need to connect manually first. The connection is made on your behalf, suiting cases where you simply need to grab a URI without too much hassle. + +Additionally there is no ability to stream the response body in this mode. If the request is successful, `res` will contain the following fields: + +* `status` The status code. +* `headers` A table of headers. +* `body` The response body as a string. + + +## request_pipeline + +`syntax: responses, err = httpc:request_pipeline(params)` + +This method works as per the [request](#request) method above, but `params` is instead a table of param tables. Each request is sent in order, and `responses` is returned as a table of response handles. For example: + +```lua +local responses = httpc:request_pipeline{ + { + path = "/b", + }, + { + path = "/c", + }, + { + path = "/d", + } +} + +for i,r in ipairs(responses) do + if r.status then + ngx.say(r.status) + ngx.say(r:read_body()) + end +end +``` + +Due to the nature of pipelining, no responses are actually read until you attempt to use the response fields (status / headers etc). And since the responses are read off in order, you must read the entire body (and any trailers if you have them), before attempting to read the next response. + +Note this doesn't preclude the use of the streaming response body reader. Responses can still be streamed, so long as the entire body is streamed before attempting to access the next response. + +Be sure to test at least one field (such as status) before trying to use the others, in case a socket read error has occurred. + +# Response + +## res.body_reader + +The `body_reader` iterator can be used to stream the response body in chunk sizes of your choosing, as follows: + +````lua +local reader = res.body_reader + +repeat + local chunk, err = reader(8192) + if err then + ngx.log(ngx.ERR, err) + break + end + + if chunk then + -- process + end +until not chunk +```` + +If the reader is called with no arguments, the behaviour depends on the type of connection. If the response is encoded as chunked, then the iterator will return the chunks as they arrive. If not, it will simply return the entire body. + +Note that the size provided is actually a **maximum** size. So in the chunked transfer case, you may get chunks smaller than the size you ask, as a remainder of the actual HTTP chunks. + +## res:read_body + +`syntax: body, err = res:read_body()` + +Reads the entire body into a local string. + + +## res:read_trailers + +`syntax: res:read_trailers()` + +This merges any trailers underneath the `res.headers` table itself. Must be called after reading the body. + + +# Proxy + +There are two convenience methods for when one simply wishes to proxy the current request to the connected upstream, and safely send it downstream to the client, as a reverse proxy. A complete example: + +```lua +local http = require "resty.http" +local httpc = http.new() + +httpc:set_timeout(500) +local ok, err = httpc:connect(HOST, PORT) + +if not ok then + ngx.log(ngx.ERR, err) + return +end + +httpc:set_timeout(2000) +httpc:proxy_response(httpc:proxy_request()) +httpc:set_keepalive() +``` + + +## proxy_request + +`syntax: local res, err = httpc:proxy_request(request_body_chunk_size?)` + +Performs a request using the current client request arguments, effectively proxying to the connected upstream. The request body will be read in a streaming fashion, according to `request_body_chunk_size` (see [documentation on the client body reader](#get_client_body_reader) below). + + +## proxy_response + +`syntax: httpc:proxy_response(res, chunksize?)` + +Sets the current response based on the given `res`. Ensures that hop-by-hop headers are not sent downstream, and will read the response according to `chunksize` (see [documentation on the body reader](#resbody_reader) above). + + +# Utility + +## parse_uri + +`syntax: local scheme, host, port, path, query? = unpack(httpc:parse_uri(uri, query_in_path?))` + +This is a convenience function allowing one to more easily use the generic interface, when the input data is a URI. + +As of version `0.10`, the optional `query_in_path` parameter was added, which specifies whether the querystring is to be included in the `path` return value, or separately as its own return value. This defaults to `true` in order to maintain backwards compatibility. When set to `false`, `path` will only include the path, and `query` will contain the URI args, not including the `?` delimiter. + + +## get_client_body_reader + +`syntax: reader, err = httpc:get_client_body_reader(chunksize?, sock?)` + +Returns an iterator function which can be used to read the downstream client request body in a streaming fashion. You may also specify an optional default chunksize (default is `65536`), or an already established socket in +place of the client request. + +Example: + +```lua +local req_reader = httpc:get_client_body_reader() + +repeat + local chunk, err = req_reader(8192) + if err then + ngx.log(ngx.ERR, err) + break + end + + if chunk then + -- process + end +until not chunk +``` + +This iterator can also be used as the value for the body field in request params, allowing one to stream the request body into a proxied upstream request. + +```lua +local client_body_reader, err = httpc:get_client_body_reader() + +local res, err = httpc:request{ + path = "/helloworld", + body = client_body_reader, +} +``` + +If `sock` is specified, + +# Author + +James Hurst + +Originally started life based on https://github.com/bakins/lua-resty-http-simple. Cosocket docs and implementation borrowed from the other lua-resty-* cosocket modules. + + +# Licence + +This module is licensed under the 2-clause BSD license. + +Copyright (c) 2013-2016, James Hurst + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. diff --git a/deps/lib64/luarocks/rocks/lua-resty-http/0.15-0/lua-resty-http-0.15-0.rockspec b/deps/lib64/luarocks/rocks/lua-resty-http/0.15-0/lua-resty-http-0.15-0.rockspec new file mode 100644 index 0000000..56ead74 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-http/0.15-0/lua-resty-http-0.15-0.rockspec @@ -0,0 +1,22 @@ +package = "lua-resty-http" +version = "0.15-0" +source = { + url = "git://github.com/ledgetech/lua-resty-http", + tag = "v0.15" +} +description = { + summary = "Lua HTTP client cosocket driver for OpenResty / ngx_lua.", + homepage = "https://github.com/ledgetech/lua-resty-http", + license = "2-clause BSD", + maintainer = "James Hurst " +} +dependencies = { + "lua >= 5.1" +} +build = { + type = "builtin", + modules = { + ["resty.http"] = "lib/resty/http.lua", + ["resty.http_headers"] = "lib/resty/http_headers.lua" + } +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-http/0.15-0/rock_manifest b/deps/lib64/luarocks/rocks/lua-resty-http/0.15-0/rock_manifest new file mode 100644 index 0000000..3d1d580 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-http/0.15-0/rock_manifest @@ -0,0 +1,13 @@ +rock_manifest = { + doc = { + LICENSE = "552f8cec37e0043674a5eee6f87bd5bc", + ["README.md"] = "c98d9dfd8caf30472d55f62205f5ed2a" + }, + lua = { + resty = { + ["http.lua"] = "a12171d90fe9eda93428535535708e7a", + ["http_headers.lua"] = "9e5772fce9b1f908b99203e179a14029" + } + }, + ["lua-resty-http-0.15-0.rockspec"] = "f9455526d47cfb0a2968c56c1fa6824c" +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-ipmatcher/0.6-0/doc/LICENSE b/deps/lib64/luarocks/rocks/lua-resty-ipmatcher/0.6-0/doc/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-ipmatcher/0.6-0/doc/LICENSE @@ -0,0 +1,201 @@ + 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/deps/lib64/luarocks/rocks/lua-resty-ipmatcher/0.6-0/doc/README.md b/deps/lib64/luarocks/rocks/lua-resty-ipmatcher/0.6-0/doc/README.md new file mode 100644 index 0000000..5fae26b --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-ipmatcher/0.6-0/doc/README.md @@ -0,0 +1,127 @@ +# lua-resty-ipmatcher + +High performance match IP address for OpenResty Lua. + +## API + +```lua +local ipmatcher = require("resty.ipmatcher") +local ip = ipmatcher.new({ + "127.0.0.1", + "192.168.0.0/16", + "::1", + "fe80::/32", +}) + +ngx.say(ip:match("127.0.0.1")) +ngx.say(ip:match("192.168.1.100")) +ngx.say(ip:match("::1")) +``` + +## ipmatcher.new + +`syntax: ok, err = ipmatcher.new(ips)` + +The `ips` is a array table, like `{ip1, ip2, ip3, ...}`, +each element in the array is a string IP address. + +```lua +local ip, err = ipmatcher.new({"127.0.0.1", "192.168.0.0/16"}) +``` + +Returns `nil` and error message if failed to create new `ipmatcher` instance. + +It supports any CIDR format for IPv4 and IPv6. + +```lua +local ip, err = ipmatcher.new({ + "127.0.0.1", "192.168.0.0/16", + "::1", "fe80::/16", + }) +``` + +## ipmatcher.new_with_value + +`syntax: matcher, err = ipmatcher.new_with_value(ips)` + +The `ips` is a hash table, like `{[ip1] = val1, [ip2] = val2, ...}`, +each key in the hash is a string IP address. + +When the `matcher` is created by `new_with_value`, calling `match` or `match_bin` +on it will return the corresponding value of matched CIDR range instead of `true`. + +```lua +local ip, err = ipmatcher.new_with_value({ + ["127.0.0.1"] = {info = "a"}, + ["192.168.0.0/16"] = {info = "b"}, +}) +local data, err = ip:match("192.168.0.1") +print(data.info) -- the value is "b" +``` + +Returns `nil` and error message if failed to create new `ipmatcher` instance. + +It supports any CIDR format for IPv4 and IPv6. + +```lua +local ip, err = ipmatcher.new_with_value({ + ["127.0.0.1"] = {info = "a"}, + ["192.168.0.0/16"] = {info = "b"}, + ["::1"] = 1, + ["fe80::/32"] = "xx", +}) +``` + +If the ip address can be satified by multiple CIDR ranges, the returned value +is undefined (depended on the internal implementation). For instance, + +```lua +local ip, err = ipmatcher.new_with_value({ + ["192.168.0.1"] = {info = "a"}, + ["192.168.0.0/16"] = {info = "b"}, +}) +local data, err = ip:match("192.168.0.1") +print(data.info) -- the value can be "a" or "b" +``` + +## ip.match + +`syntax: ok, err = ip:match(ip)` + +Returns a `true` if the IP exists within any of the specified IP list. +Returns a `false` if the IP doesn't exist within any of the specified IP list. +Returns `false` and an error message with an invalid IP address. + +```lua +local ok, err = ip:match("127.0.0.1") +``` + +## ip.match_bin + +`syntax: ok, err = ip:match_bin(bin_ip)` + +Returns a `true` if the binary format IP exists within any of the specified IP list. + +Returns `nil` and an error message with an invalid binary IP address. + +```lua +local ok, err = ip:match_bin(ngx.var.binary_remote_addr) +``` + +## ipmatcher.parse_ipv4 + +`syntax: res = ipmatcher.parse_ipv4(ip)` + +Tries to parse an IPv4 address to host byte order. + +Returns a `false` if the ip is not a valid IPv4 address. + + +## ipmatcher.parse_ipv6 + +`syntax: res = ipmatcher.parse_ipv6(ip)` + +Tries to parse an IPv6 address to host byte order. The given IPv6 address +can be wrapped by square brackets like `[::1]`. + +Returns a `false` if the ip is not a valid IPv6 address. diff --git a/deps/lib64/luarocks/rocks/lua-resty-ipmatcher/0.6-0/lua-resty-ipmatcher-0.6-0.rockspec b/deps/lib64/luarocks/rocks/lua-resty-ipmatcher/0.6-0/lua-resty-ipmatcher-0.6-0.rockspec new file mode 100644 index 0000000..4557d52 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-ipmatcher/0.6-0/lua-resty-ipmatcher-0.6-0.rockspec @@ -0,0 +1,20 @@ +package = "lua-resty-ipmatcher" +version = "0.6-0" +source = { + url = "git://github.com/iresty/lua-resty-ipmatcher", + tag = "v0.6", +} + +description = { + summary = "High performance match IP address for Lua(OpenResty).", + homepage = "https://github.com/iresty/lua-resty-ipmatcher", + license = "Apache License 2.0", + maintainer = "Yuansheng Wang " +} + +build = { + type = "builtin", + modules = { + ["resty.ipmatcher"] = "resty/ipmatcher.lua" + } +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-ipmatcher/0.6-0/rock_manifest b/deps/lib64/luarocks/rocks/lua-resty-ipmatcher/0.6-0/rock_manifest new file mode 100644 index 0000000..333c9fe --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-ipmatcher/0.6-0/rock_manifest @@ -0,0 +1,12 @@ +rock_manifest = { + doc = { + LICENSE = "86d3f3a95c324c9479bd8986968f4327", + ["README.md"] = "04bff2c3e404365842bbf53a70b20aac" + }, + lua = { + resty = { + ["ipmatcher.lua"] = "ecf415fc2ffc55329990d41de16ecf1a" + } + }, + ["lua-resty-ipmatcher-0.6-0.rockspec"] = "2544b720877ffb681301668804e1725e" +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-jit-uuid/0.0.7-2/doc/LICENSE b/deps/lib64/luarocks/rocks/lua-resty-jit-uuid/0.0.7-2/doc/LICENSE new file mode 100644 index 0000000..1693ee4 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-jit-uuid/0.0.7-2/doc/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Thibault Charbonnier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/deps/lib64/luarocks/rocks/lua-resty-jit-uuid/0.0.7-2/doc/README.md b/deps/lib64/luarocks/rocks/lua-resty-jit-uuid/0.0.7-2/doc/README.md new file mode 100644 index 0000000..70aa0a5 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-jit-uuid/0.0.7-2/doc/README.md @@ -0,0 +1,171 @@ +# lua-resty-jit-uuid + +[![Module Version][badge-version-image]][luarocks-resty-jit-uuid] +[![Build Status][badge-travis-image]][badge-travis-url] +[![Coverage Status][badge-coveralls-image]][badge-coveralls-url] + +A pure LuaJIT (no dependencies) UUID library tuned for performance. + +### Table of Contents + +* [Motivation](#motivation) +* [Usage](#usage) +* [Installation](#installation) +* [Documentation](#documentation) +* [Benchmarks](#benchmarks) +* [Contributions](#contributions) +* [License](#license) + +### Motivation + +This module is aimed at being a free of dependencies, performant and +complete UUID library for LuaJIT and ngx_lua. + +Unlike FFI and C bindings, it does not depend on libuuid being available +in your system. On top of that, it performs **better** than most (all?) +of the generators it was benchmarked against, FFI bindings included. + +Finally, it provides additional features such as UUID v3/v4/v5 generation and +UUID validation. + +See the [Benchmarks](#benchmarks) section for comparisons between other UUID +libraries for Lua/LuaJIT. + +[Back to TOC](#table-of-contents) + +### Usage + +LuaJIT: +```lua +local uuid = require 'resty.jit-uuid' + +uuid.seed() ---> automatic seeding with os.time(), LuaSocket, or ngx.time() + +uuid() ---> v4 UUID (random) +uuid.generate_v4() ---> v4 UUID + +uuid.generate_v3() ---> v3 UUID (name-based with MD5) +uuid.generate_v5() ---> v5 UUID (name-based with SHA-1) + +uuid.is_valid() ---> true/false (automatic JIT PCRE or Lua patterns) +``` + +OpenResty: +```nginx +http { + init_worker_by_lua_block { + local uuid = require 'resty.jit-uuid' + uuid.seed() -- very important! + } + + server { + location / { + content_by_lua_block { + local uuid = require 'resty.jit-uuid' + ngx.say(uuid()) + } + } + } +} +``` + +**Note**: when generating v4 (random) UUIDs in ngx_lua, it is **very +important** that you seed this module in the `init_worker` phase. If you do +not, your workers will generate identical UUID sequences, which could lead to +serious issues in your application. The seeding requirement also applies in +uses outside of ngx_lua, although seeding is less delicate in such cases. +Additionally, you should be weary about the usage of the +[`lua_code_cache`](https://github.com/openresty/lua-nginx-module#lua_code_cache) +directive: if Lua code cache is disabled, all sequences of UUIDs generated +during subsequent requests will be identical, unless this module is seeded for +every request. Just like disabling Lua code cache, such behavior would be +considered an ngx_lua anti-pattern and you should avoid it. + +[Back to TOC](#table-of-contents) + +### Installation + +This module can be installed through Luarocks: +```bash +$ luarocks install lua-resty-jit-uuid +``` + +Or via [opm](https://github.com/openresty/opm): +```bash +$ opm get thibaultcha/lua-resty-jit-uuid +``` + +Or can be manually copied in your `LUA_PATH`. + +[Back to TOC](#table-of-contents) + +### Documentation + +Documentation is available online at +. + +[Back to TOC](#table-of-contents) + +### Benchmarks + +This module has been carefully benchmarked on each step of its implementation +to ensure the best performance for OpenResty and plain LuaJIT. For example, +UUID validation will use JIT PCRE over Lua patterns when possible. + +The `bench.lua` file provides benchmarks of UUID generation for several popular +UUID libraries. + +Run `make bench` to run them: +``` +LuaJIT 2.1.0-beta1 with 1e+06 UUIDs +UUID v4 (random) generation +1. resty-jit-uuid took: 0.064228s 0% +2. FFI binding took: 0.093374s +45% +3. C binding took: 0.220542s +243% +4. Pure Lua took: 2.051905s +3094% + +UUID v3 (name-based and MD5) generation if supported +1. resty-jit-uuid took: 1.306127s + +UUID v5 (name-based and SHA-1) generation if supported +1. resty-jit-uuid took: 4.834929s + +UUID validation if supported (set of 70% valid, 30% invalid) +1. resty-jit-uuid (JIT PCRE enabled) took: 0.223060s +2. FFI binding took: 0.256580s +3. resty-jit-uuid (Lua patterns) took: 0.444174s +``` + +* FFI binding: +* C binding: +* Pure Lua: +* resty-jit-uuid: this module (base reference for generation % comparison) + +**Note**: UUID validation performance in ngx_lua (JIT PCRE) can be greatly +improved by enabling +[lua-resty-core](https://github.com/openresty/lua-resty-core). + +[Back to TOC](#table-of-contents) + +### Contributions + +Suggestions improving this module's or the benchmarks' performance +(of any benchmarked library) are particularly appreciated. + +[Back to TOC](#table-of-contents) + +### License + +Work licensed under the MIT License. + +[Back to TOC](#table-of-contents) + +[luarocks-resty-jit-uuid]: http://luarocks.org/modules/thibaultcha/lua-resty-jit-uuid + +[badge-travis-url]: https://travis-ci.org/thibaultcha/lua-resty-jit-uuid +[badge-travis-image]: https://travis-ci.org/thibaultcha/lua-resty-jit-uuid.svg?branch=master + +[badge-coveralls-url]: https://coveralls.io/r/thibaultcha/lua-resty-jit-uuid?branch=master +[badge-coveralls-image]: https://coveralls.io/repos/thibaultcha/lua-resty-jit-uuid/badge.svg?branch=master&style=flat + +[badge-version-image]: https://img.shields.io/badge/version-0.0.7-blue.svg?style=flat diff --git a/deps/lib64/luarocks/rocks/lua-resty-jit-uuid/0.0.7-2/lua-resty-jit-uuid-0.0.7-2.rockspec b/deps/lib64/luarocks/rocks/lua-resty-jit-uuid/0.0.7-2/lua-resty-jit-uuid-0.0.7-2.rockspec new file mode 100644 index 0000000..c9935e1 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-jit-uuid/0.0.7-2/lua-resty-jit-uuid-0.0.7-2.rockspec @@ -0,0 +1,28 @@ +package = "lua-resty-jit-uuid" +version = "0.0.7-2" +source = { + url = "git+https://github.com/thibaultcha/lua-resty-jit-uuid", + tag = "0.0.7" +} +description = { + summary = "Fast and dependency-free uuid generation for OpenResty/LuaJIT", + detailed = [[ + This module is aimed at being a free of dependencies, performant and + complete UUID library for LuaJIT and ngx_lua. + + Unlike FFI and C bindings, it does not depend on libuuid being available + in your system. On top of that, it performs **better** than most (all?) + of the generators it was benchmarked against, FFI bindings included. + + Finally, it provides additional features such as UUID v3/v4 generation and + UUID validation. + ]], + homepage = "http://thibaultcha.github.io/lua-resty-jit-uuid/", + license = "MIT" +} +build = { + type = "builtin", + modules = { + ["resty.jit-uuid"] = "lib/resty/jit-uuid.lua" + } +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-jit-uuid/0.0.7-2/rock_manifest b/deps/lib64/luarocks/rocks/lua-resty-jit-uuid/0.0.7-2/rock_manifest new file mode 100644 index 0000000..5811ff7 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-jit-uuid/0.0.7-2/rock_manifest @@ -0,0 +1,12 @@ +rock_manifest = { + doc = { + LICENSE = "6e1253a7a7d1f1c009806996e67531d3", + ["README.md"] = "c277ddee756e1b863481e9efbb0208be" + }, + lua = { + resty = { + ["jit-uuid.lua"] = "3a20fb33d0487fe00998bbaa930867b7" + } + }, + ["lua-resty-jit-uuid-0.0.7-2.rockspec"] = "ba15558e99d3883b187103bf4d98647e" +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-jwt/0.2.0-0/doc/AUTHORS.md b/deps/lib64/luarocks/rocks/lua-resty-jwt/0.2.0-0/doc/AUTHORS.md new file mode 100644 index 0000000..cf5c6b8 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-jwt/0.2.0-0/doc/AUTHORS.md @@ -0,0 +1,21 @@ +# Authors +Thank you guys for making this project better! + +## Repo Owners + - [@SkyLothar](https://github.com/skylothar) + +## Tons of Features + - Em. [@fermaem](https://github.com/fermaem) + - Nathan Toone [@toonetown](https://github.com/toonetown) + +## Resty.EVP + - Daniel Hiltgen [@dhiltgen](https://github.com/dhiltgen) + - ravenscar [@ravenscar](https://github.com/ravenscar) + - William [@Deadleg](https://github.com/Deadleg) + +## Patches and Suggestions + - Daniel Hiltgen [@dhiltgen](https://github.com/dhiltgen) + - Jun Hanamaki [@junhanamaki](https://github.com/junhanamaki) + +## Resty.HMAC + - @jkeys089 [lua-resty-hmac](https://github.com/jkeys089/lua-resty-hmac) diff --git a/deps/lib64/luarocks/rocks/lua-resty-jwt/0.2.0-0/doc/LICENSE b/deps/lib64/luarocks/rocks/lua-resty-jwt/0.2.0-0/doc/LICENSE new file mode 100644 index 0000000..e06d208 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-jwt/0.2.0-0/doc/LICENSE @@ -0,0 +1,202 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/deps/lib64/luarocks/rocks/lua-resty-jwt/0.2.0-0/doc/README.md b/deps/lib64/luarocks/rocks/lua-resty-jwt/0.2.0-0/doc/README.md new file mode 100644 index 0000000..6c3eb62 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-jwt/0.2.0-0/doc/README.md @@ -0,0 +1,446 @@ +Name +==== + +lua-resty-jwt - [JWT](http://self-issued.info/docs/draft-jones-json-web-token-01.html) for ngx_lua and LuaJIT + +[![Build Status](https://img.shields.io/travis/cdbattags/lua-resty-jwt.svg?style=flat-square)](https://travis-ci.org/cdbattags/lua-resty-jwt) + + +**Attention :exclamation: the hmac lib used here is [lua-resty-hmac](https://github.com/jkeys089/lua-resty-hmac), not the one in luarocks.** + +Installation +============ +- opm: `opm get SkyLothar/lua-resty-jwt` (to be updated soon) +- luarocks: `luarocks install lua-resty-jwt` +- Head to [release page](https://github.com/cdbattags/lua-resty-jwt/releases) and download `tar.gz` + +version +======= + +0.1.12 + + +Table of Contents +================= + +* [Name](#name) +* [Status](#status) +* [Description](#description) +* [Synopsis](#synopsis) +* [Methods](#methods) + * [sign](#sign) + * [verify](#verify) + * [load and verify](#load--verify) + * [sign JWE](#sign-jwe) +* [Verification](#verification) + * [JWT Validators](#jwt-validators) + * [Legacy/Timeframe options](#legacy-timeframe-options) +* [Example](#examples) +* [Installation](#installation) +* [Testing With Docker](#testing-with-docker) +* [Authors](AUTHORS.md) +* [See Also](#see-also) + +Status +====== + +This library is under active development but is considered production ready. + +Description +=========== + +This library requires an nginx build with OpenSSL, +the [ngx_lua module](http://wiki.nginx.org/HttpLuaModule), +the [LuaJIT 2.0](http://luajit.org/luajit.html), +the [lua-resty-hmac](https://github.com/jkeys089/lua-resty-hmac), +and the [lua-resty-string](https://github.com/openresty/lua-resty-string), + + +Synopsis +======== + +```lua + # nginx.conf: + + lua_package_path "/path/to/lua-resty-jwt/lib/?.lua;;"; + + server { + default_type text/plain; + location = /verify { + content_by_lua ' + local cjson = require "cjson" + local jwt = require "resty.jwt" + + local jwt_token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9" .. + ".eyJmb28iOiJiYXIifQ" .. + ".VAoRL1IU0nOguxURF2ZcKR0SGKE1gCbqwyh8u2MLAyY" + local jwt_obj = jwt:verify("lua-resty-jwt", jwt_token) + ngx.say(cjson.encode(jwt_obj)) + '; + } + location = /sign { + content_by_lua ' + local cjson = require "cjson" + local jwt = require "resty.jwt" + + local jwt_token = jwt:sign( + "lua-resty-jwt", + { + header={typ="JWT", alg="HS256"}, + payload={foo="bar"} + } + ) + ngx.say(jwt_token) + '; + } + } +``` + +[Back to TOC](#table-of-contents) + +Methods +======= + +To load this library, + +1. you need to specify this library's path in ngx_lua's [lua_package_path](https://github.com/openresty/lua-nginx-module#lua_package_path) directive. For example, `lua_package_path "/path/to/lua-resty-jwt/lib/?.lua;;";`. +2. you use `require` to load the library into a local Lua variable: + +```lua + local jwt = require "resty.jwt" +``` + +[Back to TOC](#table-of-contents) + + +sign +---- + +`syntax: local jwt_token = jwt:sign(key, table_of_jwt)` + +sign a table_of_jwt to a jwt_token. + +The `alg` argument specifies which hashing algorithm to use (`HS256`, `HS512`, `RS256`). + +### sample of table_of_jwt ### +``` +{ + "header": {"typ": "JWT", "alg": "HS512"}, + "payload": {"foo": "bar"} +} +``` + +verify +------ +`syntax: local jwt_obj = jwt:verify(key, jwt_token [, claim_spec [, ...]])` + +verify a jwt_token and returns a jwt_obj table. `key` can be a pre-shared key (as a string), *or* a function which takes a single parameter (the value of `kid` from the header) and returns either the pre-shared key (as a string) for the `kid` or `nil` if the `kid` lookup failed. This call will fail if you try to specify a function for `key` and there is no `kid` existing in the header. + +See [Verification](#verification) for details on the format of `claim_spec` parameters. + + +load & verify +------------- +``` +syntax: local jwt_obj = jwt:load_jwt(jwt_token) +syntax: local verified = jwt:verify_jwt_obj(key, jwt_obj [, claim_spec [, ...]]) +``` + + +__verify = load_jwt + verify_jwt_obj__ + +load jwt, check for kid, then verify it with the correct key + + +### sample of jwt_obj ### +``` +{ + "raw_header": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9", + "raw_payload: "eyJmb28iOiJiYXIifQ", + "signature": "wrong-signature", + "header": {"typ": "JWT", "alg": "HS256"}, + "payload": {"foo": "bar"}, + "verified": false, + "valid": true, + "reason": "signature mismatched: wrong-signature" +} +``` + +sign-jwe +-------- + +`syntax: local jwt_token = jwt:sign(key, table_of_jwt)` + +sign a table_of_jwt to a jwt_token. + +The `alg` argument specifies which hashing algorithm to use for encrypting key (`dir`). +The `enc` argument specifies which hashing algorithm to use for encrypting payload (`A128CBC-HS256`, `A256CBC-HS512`) + +### sample of table_of_jwt ### +``` +{ + "header": {"typ": "JWE", "alg": "dir", "enc":"A128CBC-HS256"}, + "payload": {"foo": "bar"} +} +``` + +[Back to TOC](#table-of-contents) + + +Verification +============ + +Both the `jwt:load` and `jwt:verify_jwt_obj` functions take, as additional parameters, any number of optional `claim_spec` parameters. A `claim_spec` is simply a lua table of claims and validators. Each key in the `claim_spec` table corresponds to a matching key in the payload, and the `validator` is a function that will be called to determine if the claims are met. + +The signature of a `validator` function is: + +``` +function(val, claim, jwt_json) +``` + +Where `val` is the value of the claim from the `jwt_obj` being tested (or nil if it doesn't exist in the object's payload), `claim` is the name of the claim that is being verified, and `jwt_json` is a json-serialized representation of the object that is being verified. If the function has no need of the `claim` or `jwt_json`, parameters, they may be left off. + +A `validator` function returns either `true` or `false`. Any `validator` *MAY* raise an error, and the validation will be treated as a failure, and the error that was raised will be put into the reason field of the resulting object. If a `validator` returns nothing (i.e. `nil`), then the function is treated to have succeeded - under the assumption that it would have raised an error if it would have failed. + +A special claim named `__jwt` can be used such that if a `validator` function exists for it, then the `validator` will be called with a deep clone of the entire parsed jwt object as the value of `val`. This is so that you can write verifications for an entire object that may depend on one or more claims. + +Multiple `claim_spec` tables can be specified to the `jwt:load` and `jwt:verify_jwt_obj` - and they will be executed in order. There is no guarantee of the execution order of individual `validators` within a single `claim_spec`. If a `claim_spec` fails, then any following `claim_specs` will *NOT* be executed. + + +### sample `claim_spec` ### +``` +{ + sub = function(val) return string.match("^[a-z]+$", val) end, + iss = function(val) + for _, value in pairs({ "first", "second" }) do + if value == val then return true end + end + return false + end, + __jwt = function(val, claim, jwt_json) + if val.payload.foo == nil or val.payload.bar == nil then + error("Need to specify either 'foo' or 'bar'") + end + end +} +``` + +JWT Validators +-------------- + +A library of helpful `validator` functions exists at `resty.jwt-validators`. You can use this library by including: +``` +local validators = require "resty.jwt-validators" +``` + +The following functions are currently defined in the validator library. Those marked with "(opt)" means that the same function exists named `opt_` which takes the same parameters. The "opt" version of the function will return `true` if the key does not exist in the payload of the jwt_object being verified, while the "non-opt" version of the function will return false if the key does not exist in the payload of the jwt_object being verified. + +#### `validators.chain(...)` #### +Returns a validator that chains the given functions together, one after another - as long as they keep passing their checks. + +#### `validators.required(chain_function)` #### +Returns a validator that returns `false` if a value doesn't exist. If the value exists and a `chain_function` is specified, then the value of `chain_function(val, claim, jwt_json)` will be returned, otherwise, `true` will be returned. This allows for specifying that a value is both required *and* it must match some additional check. + +#### `validators.require_one_of(claim_keys)` #### +Returns a validator which errors with a message if *NONE* of the given claim keys exist. It is expected that this function is used against a full jwt object. The claim_keys must be a non-empty table of strings. + +#### `validators.check(check_val, check_function, name, check_type)` (opt) #### +Returns a validator that checks if the result of calling the given `check_function` for the tested value and `check_val` returns true. The value of `check_val` and `check_function` cannot be nil. The optional `name` is used for error messages and defaults to "check_value". The optional `check_type` is used to make sure that the check type matches and defaults to `type(check_val)`. The first parameter passed to check_function will *never* be nil. If the `check_function` raises an error, that will be appended to the error message. + +#### `validators.equals(check_val)` (opt) #### +Returns a validator that checks if a value exactly equals (using `==`) the given check_value. The value of `check_val` cannot be nil. + +#### `validators.matches(pattern)` (opt) #### +Returns a validator that checks if a value matches the given pattern (using `string.match`). The value of `pattern` must be a string. + +#### `validators.any_of(check_values, check_function, name, check_type, table_type)` (opt) #### +Returns a validator which calls the given `check_function` for each of the given `check_values` and the tested value. If any of these calls return `true`, then this function returns `true`. The value of `check_values` must be a non-empty table with all the same types, and the value of `check_function` must not be `nil`. The optional `name` is used for error messages and defaults to "check_values". The optional `check_type` is used to make sure that the check type matches and defaults to `type(check_values[1])` - the table type. + +#### `validators.equals_any_of(check_values)` (opt) #### +Returns a validator that checks if a value exactly equals any of the given `check_values`. + +#### `validators.matches_any_of(patterns)` (opt) #### +Returns a validator that checks if a value matches any of the given `patterns`. + +#### `validators.contains_any_of(check_values,name)` (opt) #### +Returns a validator that checks if a value of expected type `string` exists in any of the given `check_values`. The value of `check_values`must be a non-empty table with all the same types. The optional name is used for error messages and defaults to `check_values`. + +#### `validators.greater_than(check_val)` (opt) #### +Returns a validator that checks how a value compares (numerically, using `>`) to a given `check_value`. The value of `check_val` cannot be `nil` and must be a number. + +#### `validators.greater_than_or_equal(check_val)` (opt) #### +Returns a validator that checks how a value compares (numerically, using `>=`) to a given `check_value`. The value of `check_val` cannot be `nil` and must be a number. + +#### `validators.less_than(check_val)` (opt) #### +Returns a validator that checks how a value compares (numerically, using `<`) to a given `check_value`. The value of `check_val` cannot be `nil` and must be a number. + +#### `validators.less_than_or_equal(check_val)` (opt) #### +Returns a validator that checks how a value compares (numerically, using `<=`) to a given `check_value`. The value of `check_val` cannot be `nil` and must be a number. + +#### `validators.is_not_before()` (opt) #### +Returns a validator that checks if the current time is not before the tested value within the system's leeway. This means that: +``` +val <= (system_clock() + system_leeway). +``` + +#### `validators.is_not_expired()` (opt) #### +Returns a validator that checks if the current time is not equal to or after the tested value within the system's leeway. This means that: +``` +val > (system_clock() - system_leeway). +``` + +#### `validators.is_at()` (opt) #### +Returns a validator that checks if the current time is the same as the tested value within the system's leeway. This means that: +``` +val >= (system_clock() - system_leeway) and val <= (system_clock() + system_leeway). +``` + +#### `validators.set_system_leeway(leeway)` #### +A function to set the leeway (in seconds) used for `is_not_before` and `is_not_expired`. The default is to use `0` seconds + +#### `validators.set_system_clock(clock)` #### +A function to set the system clock used for `is_not_before` and `is_not_expired`. The default is to use `ngx.now` + +### sample `claim_spec` using validators ### +``` +local validators = require "resty.jwt-validators" +local claim_spec = { + sub = validators.opt_matches("^[a-z]+$), + iss = validators.equals_any_of({ "first", "second" }), + __jwt = validators.require_one_of({ "foo", "bar" }) +} +``` + + +Legacy/Timeframe options +------------------------ + +In order to support code which used previous versions of this library, as well as to simplify specifying timeframe-based `claim_specs`, you may use in place of any single `claim_spec` parameter a table of `validation_options`. The parameter should be expressed as a key/value table. Each key of the table should be picked from the following list. + +When using legacy `validation_options`, you *MUST ONLY* specify these options. That is, you cannot mix legacy `validation_options` with other `claim_spec` validators. In order to achieve that, you must specify multiple options to the `jwt:load`/`jwt:verify_jwt_obj` functions. + +* `lifetime_grace_period`: Define the leeway in seconds to account for clock skew between the server that generated the jwt and the server validating it. Value should be zero (`0`) or a positive integer. + + * When this validation option is specified, the process will ensure that the jwt contains at least one of the two `nbf` or `exp` claim and compare the current clock time against those boundaries. Would the jwt be deemed as expired or not valid yet, verification will fail. + + * When none of the `nbf` and `exp` claims can be found, verification will fail. + + * `nbf` and `exp` claims are expected to be expressed in the jwt as numerical values. Wouldn't that be the case, verification will fail. + + * Specifying this option is equivalent to calling: + ``` + validators.set_system_leeway(leeway) + ``` + + and specifying as a `claim_spec`: + ``` + { + __jwt = validators.require_one_of({ "nbf", "exp" }), + nbf = validators.opt_is_not_before(), + exp = validators.opt_is_not_expired() + } + ``` + +* `require_nbf_claim`: Express if the `nbf` claim is optional or not. Value should be a boolean. + + * When this validation option is set to `true` and no `lifetime_grace_period` has been specified, a zero (`0`) leeway is implied. + + * Specifying this option is equivalent to specifying as a `claim_spec`: + ``` + { + nbf = validators.is_not_before(), + } + ``` + +* `require_exp_claim`: Express if the `exp` claim is optional or not. Value should be a boolean. + + * When this validation option is set to `true` and no `lifetime_grace_period` has been specified, a zero (`0`) leeway is implied. + + * Specifying this option is equivalent to specifying as a `claim_spec`: + ``` + { + exp = validators.is_not_expired(), + } + ``` + +* `valid_issuers`: Whitelist the vetted issuers of the jwt. Value should be a array of strings. + + * When this validation option is specified, the process will compare the jwt `iss` claim against the list of valid issuers. Comparison is done in a case sensitive manner. Would the jwt issuer not be found in the whitelist, verification will fail. + + * `iss` claim is expected to be expressed in the jwt as a string. Wouldn't that be the case, verification will fail. + + * Specifying this option is equivalent to specifying as a `claim_spec`: + ``` + { + iss = validators.equals_any_of(valid_issuers), + } + ``` + + +### sample of validation_options usage ### +``` +local jwt_obj = jwt:verify(key, jwt_token, + { + lifetime_grace_period = 120, + require_exp_claim = true, + valid_issuers = { "my-trusted-issuer", "my-other-trusteed-issuer" } + } +) +``` + + + +Examples +======== +* [JWT Auth With Query and Cookie](examples/README.md#jwt-auth-using-query-and-cookie) +* [JWT Auth With KID and Store Your Key in Redis](examples/README.md#jwt-auth-with-kid-and-store-keys-in-redis) + +[Back to TOC](#table-of-contents) + + +Installation +============ + +Using Luarocks +```bash +luarocks install lua-resty-jwt +``` + +It is recommended to use the latest [ngx_openresty bundle](http://openresty.org) directly. + +Also, You need to configure +the [lua_package_path](https://github.com/openresty/lua-nginx-module#lua_package_path) directive to +add the path of your lua-resty-jwt source tree to ngx_lua's Lua module search path, as in + +```nginx + # nginx.conf + http { + lua_package_path "/path/to/lua-resty-jwt/lib/?.lua;;"; + ... + } +``` + +and then load the library in Lua: + +```lua + local jwt = require "resty.jwt" +``` + + +[Back to TOC](#table-of-contents) + +Testing With Docker +=================== + +``` +./ci script +``` + +[Back to TOC](#table-of-contents) + + +See Also +======== +* the ngx_lua module: http://wiki.nginx.org/HttpLuaModule + +[Back to TOC](#table-of-contents) diff --git a/deps/lib64/luarocks/rocks/lua-resty-jwt/0.2.0-0/lua-resty-jwt-0.2.0-0.rockspec b/deps/lib64/luarocks/rocks/lua-resty-jwt/0.2.0-0/lua-resty-jwt-0.2.0-0.rockspec new file mode 100644 index 0000000..439fc8e --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-jwt/0.2.0-0/lua-resty-jwt-0.2.0-0.rockspec @@ -0,0 +1,29 @@ +package = 'lua-resty-jwt' +version = '0.2.0-0' +source = { + url = 'git://github.com/cdbattags/lua-resty-jwt', + tag = 'v0.2.0' +} +description = { + summary = 'JWT for ngx_lua and LuaJIT.', + detailed = [[ + This library requires an nginx build + with OpenSSL, the ngx_lua module, + the LuaJIT 2.0, the lua-resty-hmac, + and the lua-resty-string, + ]], + homepage = 'https://github.com/cdbattags/lua-resty-jwt', + license = 'Apache License Version 2' +} +dependencies = { + 'lua >= 5.1' +} +build = { + type = 'builtin', + modules = { + ['resty.jwt'] = 'lib/resty/jwt.lua', + ['resty.evp'] = 'lib/resty/evp.lua', + ['resty.jwt-validators'] = 'lib/resty/jwt-validators.lua', + ['resty.hmac'] = 'vendor/resty/hmac.lua' + } +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-jwt/0.2.0-0/rock_manifest b/deps/lib64/luarocks/rocks/lua-resty-jwt/0.2.0-0/rock_manifest new file mode 100644 index 0000000..64de933 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-jwt/0.2.0-0/rock_manifest @@ -0,0 +1,16 @@ +rock_manifest = { + doc = { + ["AUTHORS.md"] = "fbbd71023a49dd671db591a0024e7533", + LICENSE = "d2794c0df5b907fdace235a619d80314", + ["README.md"] = "8323ccc7e5994c7ad4379b5761e60d72" + }, + lua = { + resty = { + ["evp.lua"] = "c068fd19edf73c80018dcaf11290f4f8", + ["hmac.lua"] = "564d049c1dca570b13ad2ad024c7e1bd", + ["jwt-validators.lua"] = "8bb746a3b6c98ce1d6521a4f2283493f", + ["jwt.lua"] = "9415351aa6b0fd1b43fcb6966b5728b7" + } + }, + ["lua-resty-jwt-0.2.0-0.rockspec"] = "97af5e2825f879a05390ff52189ffabf" +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-kafka/0.07-0/doc/LICENSE b/deps/lib64/luarocks/rocks/lua-resty-kafka/0.07-0/doc/LICENSE new file mode 100644 index 0000000..f6e7810 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-kafka/0.07-0/doc/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2014, doujiang +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of lua-resty-kafka nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. + diff --git a/deps/lib64/luarocks/rocks/lua-resty-kafka/0.07-0/doc/README.md b/deps/lib64/luarocks/rocks/lua-resty-kafka/0.07-0/doc/README.md new file mode 100644 index 0000000..cc1ab8f --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-kafka/0.07-0/doc/README.md @@ -0,0 +1,393 @@ +Name +===== + +lua-resty-kafka - Lua kafka client driver for the ngx_lua based on the cosocket API + +Table of Contents +================= + +* [Name](#name) +* [Status](#status) +* [Description](#description) +* [Synopsis](#synopsis) +* [Modules](#modules) + * [resty.kafka.client](#restykafkaclient) + * [Methods](#methods) + * [new](#new) + * [fetch_metadata](#fetch_metadata) + * [refresh](#refresh) + * [resty.kafka.producer](#restykafkaproducer) + * [Methods](#methods) + * [new](#new) + * [send](#send) + * [offset](#offset) + * [flush](#flush) +* [Installation](#installation) +* [TODO](#todo) +* [Author](#author) +* [Copyright and License](#copyright-and-license) +* [See Also](#see-also) + +Status +====== + +This library is still under early development and is still experimental. + +Description +=========== + +This Lua library is a Kafka client driver for the ngx_lua nginx module: + +http://wiki.nginx.org/HttpLuaModule + +This Lua library takes advantage of ngx_lua's cosocket API, which ensures +100% nonblocking behavior. + +Note that at least [ngx_lua 0.9.3](https://github.com/openresty/lua-nginx-module/tags) or [ngx_openresty 1.4.3.7](http://openresty.org/#Download) is required, and unfortunately only LuaJIT supported (`--with-luajit`). + + +Synopsis +======== + +```lua + lua_package_path "/path/to/lua-resty-kafka/lib/?.lua;;"; + + server { + location /test { + content_by_lua ' + local cjson = require "cjson" + local client = require "resty.kafka.client" + local producer = require "resty.kafka.producer" + + local broker_list = { + { host = "127.0.0.1", port = 9092 }, + } + + local key = "key" + local message = "halo world" + + -- usually we do not use this library directly + local cli = client:new(broker_list) + local brokers, partitions = cli:fetch_metadata("test") + if not brokers then + ngx.say("fetch_metadata failed, err:", partitions) + end + ngx.say("brokers: ", cjson.encode(brokers), "; partitions: ", cjson.encode(partitions)) + + + -- sync producer_type + local p = producer:new(broker_list) + + local offset, err = p:send("test", key, message) + if not offset then + ngx.say("send err:", err) + return + end + ngx.say("send success, offset: ", tonumber(offset)) + + -- this is async producer_type and bp will be reused in the whole nginx worker + local bp = producer:new(broker_list, { producer_type = "async" }) + + local ok, err = bp:send("test", key, message) + if not ok then + ngx.say("send err:", err) + return + end + + ngx.say("send success, ok:", ok) + '; + } + } +``` + + +[Back to TOC](#table-of-contents) + +Modules +======= + + +resty.kafka.client +---------------------- + +To load this module, just do this + +```lua + local client = require "resty.kafka.client" +``` + +[Back to TOC](#table-of-contents) + +### Methods + +#### new + +`syntax: c = client:new(broker_list, client_config)` + +The `broker_list` is a list of broker, like the below + +```json +[ + { + "host": "127.0.0.1", + "port": 9092 + } +] +``` + +An optional `client_config` table can be specified. The following options are as follows: + +client config + +* `socket_timeout` + + Specifies the network timeout threshold in milliseconds. *SHOULD* lagrer than the `request_timeout`. + +* `keepalive_timeout` + + Specifies the maximal idle timeout (in milliseconds) for the keepalive connection. + +* `keepalive_size` + + Specifies the maximal number of connections allowed in the connection pool for per Nginx worker. + +* `refresh_interval` + + Specifies the time to auto refresh the metadata in milliseconds. Then metadata will not auto refresh if is nil. + + +[Back to TOC](#table-of-contents) + +#### fetch_metadata +`syntax: brokers, partitions = c:fetch_metadata(topic)` + +In case of success, return the all brokers and partitions of the `topic`. +In case of errors, returns `nil` with a string describing the error. + + +[Back to TOC](#table-of-contents) + +#### refresh +`syntax: brokers, partitions = c:refresh()` + +This will refresh the metadata of all topics which have been fetched by `fetch_metadata`. +In case of success, return all brokers and all partitions of all topics. +In case of errors, returns `nil` with a string describing the error. + + +[Back to TOC](#table-of-contents) + +resty.kafka.producer +---------------------- + +To load this module, just do this + +```lua + local producer = require "resty.kafka.producer" +``` + +[Back to TOC](#table-of-contents) + +### Methods + +#### new + +`syntax: p = producer:new(broker_list, producer_config?, cluster_name?)` + +It's recommend to use async producer_type. + +`broker_list` is the same as in `client` + +An optional options table can be specified. The following options are as follows: + +`socket_timeout`, `keepalive_timeout`, `keepalive_size`, `refresh_interval` are the same as in `client_config` + +producer config, most like in + +* `producer_type` + + Specifies the `producer.type`. "async" or "sync" + +* `request_timeout` + + Specifies the `request.timeout.ms`. Default `2000 ms` + +* `required_acks` + + Specifies the `request.required.acks`, *SHOULD NOT* be zero. Default `1`. + +* `max_retry` + + Specifies the `message.send.max.retries`. Default `3`. + +* `retry_backoff` + + Specifies the `retry.backoff.ms`. Default `100`. + +* `partitioner` + + Specifies the partitioner that choose partition from key and partition num. + `syntax: partitioner = function (key, partition_num, correlation_id) end`, + the correlation_id is an auto increment id in producer. Default partitioner is: + +* `api_version` + + Specifies the produce API version. Default `0`. + If you use Kafka 0.10.0.0 or higher, `api_version` can use `0`, `1` or `2`. + If you use Kafka 0.9.x, `api_version` should be `0` or `1`. + If you use Kafka 0.8.x, `api_version` should be `0`. + + +```lua +local function default_partitioner(key, num, correlation_id) + local id = key and crc32(key) or correlation_id + + -- partition_id is continuous and start from 0 + return id % num +end +``` + +buffer config ( only work `producer_type` = "async" ) + +* `flush_time` + + Specifies the `queue.buffering.max.ms`. Default `1000`. + +* `batch_num` + + Specifies the `batch.num.messages`. Default `200`. + +* `batch_size` + + Specifies the `send.buffer.bytes`. Default `1M`(may reach 2M). + Be careful, *SHOULD* be smaller than the `socket.request.max.bytes / 2 - 10k` config in kafka server. + +* `max_buffering` + + Specifies the `queue.buffering.max.messages`. Default `50,000`. + +* `error_handle` + + Specifies the error handle, handle data when buffer send to kafka error. + `syntax: error_handle = function (topic, partition_id, message_queue, index, err, retryable) end`, + the failed messages in the message_queue is like ```{ key1, msg1, key2, msg2 } ```, + `key` in the message_queue is empty string `""` even if orign is `nil`. + `index` is the message_queue length, should not use `#message_queue`. + when `retryable` is `true` that means kafka server surely not committed this messages, you can safely retry to send; + and else means maybe, recommend to log to somewhere. + +Not support compression now. + +The third optional `cluster_name` specifies the name of the cluster, default `1` (yeah, it's number). You can Specifies different names when you have two or more kafka clusters. And this only works with `async` producer_type. + + +[Back to TOC](#table-of-contents) + +#### send +`syntax: ok, err = p:send(topic, key, message)` + +1. In sync model + + In case of success, returns the offset (** cdata: LL **) of the current broker and partition. + In case of errors, returns `nil` with a string describing the error. + +2. In async model + + The `message` will write to the buffer first. + It will send to the kafka server when the buffer exceed the `batch_num`, + or every `flush_time` flush the buffer. + + It case of success, returns `true`. + In case of errors, returns `nil` with a string describing the error (`buffer overflow`). + + +[Back to TOC](#table-of-contents) + +#### offset + +`syntax: sum, details = p:offset()` + + Return the sum of all the topic-partition offset (return by the ProduceRequest api); + and the details of each topic-partition + + +[Back to TOC](#table-of-contents) + +#### flush + +`syntax: ok = p:flush()` + +Always return `true`. + + +[Back to TOC](#table-of-contents) + +Installation +============ + +You need to configure +the lua_package_path directive to add the path of your lua-resty-kafka source +tree to ngx_lua's LUA_PATH search path, as in + +```nginx + # nginx.conf + http { + lua_package_path "/path/to/lua-resty-kafka/lib/?.lua;;"; + ... + } +``` + +Ensure that the system account running your Nginx ''worker'' proceses have +enough permission to read the `.lua` file. + + +[Back to TOC](#table-of-contents) + +TODO +==== + +1. Fetch API +2. Offset API +3. Offset Commit/Fetch API + + +[Back to TOC](#table-of-contents) + +Author +====== + +Dejiang Zhu (doujiang24) . + + +[Back to TOC](#table-of-contents) + +Copyright and License +===================== + +This module is licensed under the BSD license. + +Copyright (C) 2014-2014, by Dejiang Zhu (doujiang24) . + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. + + +[Back to TOC](#table-of-contents) + +See Also +======== +* the ngx_lua module: http://wiki.nginx.org/HttpLuaModule +* the kafka protocol: https://cwiki.apache.org/confluence/display/KAFKA/A+Guide+To+The+Kafka+Protocol +* the [lua-resty-redis](https://github.com/openresty/lua-resty-redis) library +* the [lua-resty-logger-socket](https://github.com/cloudflare/lua-resty-logger-socket) library +* the [sarama](https://github.com/Shopify/sarama) + +[Back to TOC](#table-of-contents) + diff --git a/deps/lib64/luarocks/rocks/lua-resty-kafka/0.07-0/lua-resty-kafka-0.07-0.rockspec b/deps/lib64/luarocks/rocks/lua-resty-kafka/0.07-0/lua-resty-kafka-0.07-0.rockspec new file mode 100644 index 0000000..3d166fc --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-kafka/0.07-0/lua-resty-kafka-0.07-0.rockspec @@ -0,0 +1,36 @@ +package = "lua-resty-kafka" +version = "0.07-0" +source = { + url = "git://github.com/doujiang24/lua-resty-kafka", + tag = "v0.07" +} +description = { + summary = "Lua Kafka client driver for the ngx_lua based on the cosocket API", + detailed = [[ + This Lua library is a Kafka client driver for the ngx_lua nginx module: + + http://wiki.nginx.org/HttpLuaModule + + This Lua library takes advantage of ngx_lua's cosocket API, which ensures 100% nonblocking behavior. + + Note that at least ngx_lua 0.9.3 or ngx_openresty 1.4.3.7 is required, and unfortunately only LuaJIT supported (--with-luajit). + ]], + homepage = "https://github.com/doujiang24/lua-resty-kafka", + license = "BSD" +} +dependencies = { + "lua >= 5.1" +} +build = { + type = "builtin", + modules = { + ["resty.kafka.broker"] = "lib/resty/kafka/broker.lua", + ["resty.kafka.client"] = "lib/resty/kafka/client.lua", + ["resty.kafka.errors"] = "lib/resty/kafka/errors.lua", + ["resty.kafka.producer"] = "lib/resty/kafka/producer.lua", + ["resty.kafka.request"] = "lib/resty/kafka/request.lua", + ["resty.kafka.response"] = "lib/resty/kafka/response.lua", + ["resty.kafka.ringbuffer"] = "lib/resty/kafka/ringbuffer.lua", + ["resty.kafka.sendbuffer"] = "lib/resty/kafka/sendbuffer.lua" + } +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-kafka/0.07-0/rock_manifest b/deps/lib64/luarocks/rocks/lua-resty-kafka/0.07-0/rock_manifest new file mode 100644 index 0000000..c7a0ef5 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-kafka/0.07-0/rock_manifest @@ -0,0 +1,21 @@ +rock_manifest = { + doc = { + LICENSE = "0974006d6d5c1ea5a5836ccb3b144d64", + ["README.md"] = "d7914c7e2ca6cee17326858ae3a5b49f" + }, + lua = { + resty = { + kafka = { + ["broker.lua"] = "db516f3c85ed883aa9c942856cf69b86", + ["client.lua"] = "b87b80cc47c68985370291cc32b9fd39", + ["errors.lua"] = "9034571631cf7ca290826178b8b7ebda", + ["producer.lua"] = "5184f4242eed8967c1d6f2602f210353", + ["request.lua"] = "45d55015729b6c238c80cc5afbdc3fb7", + ["response.lua"] = "4200473724f7e1574389429535e968ea", + ["ringbuffer.lua"] = "144345060570b79785379cd2ac364a68", + ["sendbuffer.lua"] = "cc478ddaafb842c4f219b58bcdc4d10d" + } + } + }, + ["lua-resty-kafka-0.07-0.rockspec"] = "077f43621f57eb94f57d9ab7577daecb" +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-logger-socket/2.0-0/doc/README.md b/deps/lib64/luarocks/rocks/lua-resty-logger-socket/2.0-0/doc/README.md new file mode 100644 index 0000000..483bedc --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-logger-socket/2.0-0/doc/README.md @@ -0,0 +1,281 @@ +Name +==== + +lua-resty-logger-socket - nonblocking remote access logging for Nginx + +Table of Contents +================= + +* [Name](#name) +* [Status](#status) +* [Description](#description) +* [Synopsis](#synopsis) +* [Methods](#methods) + * [init](#init) + * [initted](#initted) + * [log](#log) + * [flush](#flush) +* [Installation](#installation) +* [TODO](#todo) +* [Authors](#authors) +* [Copyright and License](#copyright-and-license) + +Status +====== + +This library is still experimental and under early development. + +Description +=========== + +This lua library is a remote logging module for ngx_lua: + +http://wiki.nginx.org/HttpLuaModule + +This is aimed to replace Nginx's standard [ngx_http_log_module](http://nginx.org/en/docs/http/ngx_http_log_module.html) to push access logs to a remote server via an nonblocking socket. A common remote log server supporting sockets is [syslog-ng](http://www.balabit.com/network-security/syslog-ng). + +This Lua library takes advantage of ngx_lua's cosocket API, which ensures +100% nonblocking behavior. + +Synopsis +======== + +```lua + lua_package_path "/path/to/lua-resty-logger-socket/lib/?.lua;;"; + + server { + location /t { + log_by_lua ' + local logger_socket = require "resty.logger.socket" + if not logger_socket.initted() then + local ok, err = logger_socket.init{ + host = 'xxx', + port = 1234, + flush_limit = 1234, + drop_limit = 5678, + } + if not ok then + ngx.log(ngx.ERR, "failed to initialize the logger: ", + err) + return + end + end + + -- construct the custom access log message in + -- the Lua variable "msg" + + local bytes, err = logger_socket.log(msg) + if err then + ngx.log(ngx.ERR, "failed to log message: ", err) + return + end + '; + } + + location /m { + log_by_lua ' + local logger_socket = require "resty.logger.socket" + local logger = logger_socket:new() + if not logger:initted() then + local ok, err = logger:init{ + host = 'xxx', + port = 1234, + flush_limit = 1234, + drop_limit = 5678, + } + if not ok then + ngx.log(ngx.ERR, "failed to initialize the logger: ", + err) + return + end + end + + -- construct the custom access log message in + -- the Lua variable "msg" + + local bytes, err = logger:log(msg) + if err then + ngx.log(ngx.ERR, "failed to log message: ", err) + return + end + '; + } + } +``` + +[Back to TOC](#table-of-contents) + +Methods +======= + +This logger module is designed to be shared inside an Nginx worker process by all the requests. So currently only one remote log server is supported. We may support multiple log server sharding in the future. + +[Back to TOC](#table-of-contents) + +new +---- +`syntax: logger = logger_socket.new()` + +Create a logger_socket object. + +[Back to TOC](#table-of-contents) + +init +---- +`syntax: ok, err = logger:init(user_config) + or ok, err = logger_socket.init(user_config)` + +Initialize logger with user configurations. This logger must be initted before use. If you do not initialize the logger, you will get an error. If you do not new a logger object before init, a global logger_socket object will be created by default. + +Available user configurations are listed as follows: + +* `flush_limit` + + If the buffered messages' size plus the current message size reaches (`>=`) this limit (in bytes), the buffered log messages will be written to log server. Default to 4096 (4KB). + +* `drop_limit` + + If the buffered messages' size plus the current message size is larger than this limit (in bytes), the current log message will be dropped because of limited buffer size. Default drop_limit is 1048576 (1MB). + +* `timeout` + + Sets the timeout (in ms) protection for subsequent operations, including the *connect* method. Default value is 1000 (1 sec). + +* `host` + + log server host. + +* `port` + + log server port number. + +* `sock_type` + + IP protocol type to use for transport layer. Can be either "tcp" or "udp". Default is "tcp". + +* `path` + + If the log server uses a stream-typed unix domain socket, `path` is the socket file path. Note that host/port and path cannot both be empty. At least one must be supplied. + +* `max_retry_times` + + Max number of retry times after a connect to a log server failed or send log messages to a log server failed. + +* `retry_interval` + + The time delay (in ms) before retry to connect to a log server or retry to send log messages to a log server, default to 100 (0.1s). + +* `pool_size` + + Keepalive pool size used by sock:keepalive. Default to 10. + +* `max_buffer_reuse` + + Max number of reuse times of internal logging buffer before creating a new one (to prevent memory leak). + +* `periodic_flush` + + Periodic flush interval (in seconds). Set to `nil` to turn off this feature. + +* `ssl` + + Boolean, enable or disable connecting via SSL. Default to false. + +* `ssl_verify` + + Boolean, enable or disable verifying host and certificate match. Default to true. + +* `sni_host` + + Set the hostname to send in SNI and to use when verifying certificate match. + +[Back to TOC](#table-of-contents) + +initted +-------- +`syntax: initted = logger:initted() + or initted = logger_socket.initted()` + +Get a boolean value indicating whether this object or module has been initted (by calling the [init](#init) method). + +[Back to TOC](#table-of-contents) + +log +--- +`syntax: bytes, err = logger:log(msg) + or bytes, err = logger_socket.log(msg)` + +Log a message. By default, the log message will be buffered in the logger object or module until `flush_limit` is reached in which case the logger will flush all the buffered messages to remote log server via a socket. +`bytes` is the number of bytes that successfully buffered in the logger. If `bytes` is nil, `err` is a string describing what kind of error happens this time. If bytes is not nil, then `err` is a previous error message. `err` can be nil when `bytes` is not nil. + +[Back to TOC](#table-of-contents) + +flush +----- +`syntax: bytes, err = logger.flush(_, logger) + or bytes, err = logger_socket.flush()` + +Flushes any buffered messages out to remote immediately. Usually you do not need +to call this manually because flushing happens automatically when the buffer is full. + +[Back to TOC](#table-of-contents) + +Installation +============ + +You need to compile at least [ngx_lua 0.9.0](https://github.com/chaoslawful/lua-nginx-module/tags) with your Nginx. + +You need to configure +the [lua_package_path](https://github.com/chaoslawful/lua-nginx-module#lua_package_path) directive to +add the path of your `lua-resty-logger-socket` source tree to ngx_lua's Lua module search path, as in + + # nginx.conf + http { + lua_package_path "/path/to/lua-resty-logger-socket/lib/?.lua;;"; + ... + } + +and then load the library in Lua: + + local logger_socket = require "resty.logger.socket" + +[Back to TOC](#table-of-contents) + +TODO +==== + +* Multiple log server sharding and/or failover support. +* "match_similar" utf8 support test. + +[Back to TOC](#table-of-contents) + +Authors +======= + +Jiale Zhi , CloudFlare Inc. + +Yichun Zhang (agentzh) , CloudFlare Inc. + +[Back to TOC](#table-of-contents) + +Copyright and License +===================== + +This module is licensed under the BSD license. + +Copyright (C) 2013, by Jiale Zhi , CloudFlare Inc. + +Copyright (C) 2013, by Yichun Zhang , CloudFlare Inc. + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. + +[Back to TOC](#table-of-contents) + diff --git a/deps/lib64/luarocks/rocks/lua-resty-logger-socket/2.0-0/lua-resty-logger-socket-2.0-0.rockspec b/deps/lib64/luarocks/rocks/lua-resty-logger-socket/2.0-0/lua-resty-logger-socket-2.0-0.rockspec new file mode 100644 index 0000000..c575dd2 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-logger-socket/2.0-0/lua-resty-logger-socket-2.0-0.rockspec @@ -0,0 +1,20 @@ +package = "lua-resty-logger-socket" +version = "2.0-0" +source = { + url = "git://github.com/api7/lua-resty-logger-socket", + tag = "v2.0", +} + +description = { + summary = "Raw-socket-based Logger Library for Nginx/Lua", + homepage = "https://github.com/api7/lua-resty-logger-socket", + license = "BSD license", + maintainer = "Yuansheng Wang " +} + +build = { + type = "builtin", + modules = { + ["resty.logger.socket"] = "lib/resty/logger/socket.lua", + } +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-logger-socket/2.0-0/rock_manifest b/deps/lib64/luarocks/rocks/lua-resty-logger-socket/2.0-0/rock_manifest new file mode 100644 index 0000000..e99beec --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-logger-socket/2.0-0/rock_manifest @@ -0,0 +1,13 @@ +rock_manifest = { + doc = { + ["README.md"] = "6910886136dddcf58e2048706a97ed5a" + }, + lua = { + resty = { + logger = { + ["socket.lua"] = "3672f4a33584974957f20ac0ec1a2ad0" + } + } + }, + ["lua-resty-logger-socket-2.0-0.rockspec"] = "ee8bb9df5edabfeb6318956daeafc092" +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-ngxvar/0.5.2-0/doc/LICENSE b/deps/lib64/luarocks/rocks/lua-resty-ngxvar/0.5.2-0/doc/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-ngxvar/0.5.2-0/doc/LICENSE @@ -0,0 +1,201 @@ + 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/deps/lib64/luarocks/rocks/lua-resty-ngxvar/0.5.2-0/doc/README.md b/deps/lib64/luarocks/rocks/lua-resty-ngxvar/0.5.2-0/doc/README.md new file mode 100644 index 0000000..f64d459 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-ngxvar/0.5.2-0/doc/README.md @@ -0,0 +1,78 @@ +lua-var-nginx-module +==================== + +Fetchs Nginx variable by Luajit with FFI way which is fast and cheap. + +Compares to `ngx.var.*`, performance has increased by more than five times. ^_^ + + +Table of Contents +================= +* [Install](#install) +* [Methods](#methods) + * [request](#request) + * [fetch](#fetch) +* [TODO](#todo) + + +Install +======= + +Compiles the nginx c module to OpenResty: + +```shell +./configure --prefix=/opt/openresty \ + --add-module=/path/to/lua-var-nginx-module +``` + +Install the Lua source code, there are two ways: + +```shell +luarocks install lua-resty-ngxvar +``` + +Or we can copy the source lua file to specified directory which OpenResty can +load it normally. + +```shell +make install LUA_LIB_DIR=/opt/openresty/lualib/ +``` + +Method +====== + +### request + +`syntax: req = ngxvar.request()` + +Returns the request object of current request. We can cache it at your Lua code +land if we try to fetch more than one variable in one request. + +[Back to TOC](#table-of-contents) + +### fetch + +`syntax: val = ngxvar.fetch(name, req)` + +Returns the Nginx variable value by name. + +```nginx + location /t { + content_by_lua_block { + local var = require("resty.ngxvar") + local req = var.request() + + ngx.say(var.fetch("host", req)) + ngx.say(var.fetch("uri", req)) + } + } +``` + +[Back to TOC](#table-of-contents) + +TODO +==== + +* support more variables. + +[Back to TOC](#table-of-contents) diff --git a/deps/lib64/luarocks/rocks/lua-resty-ngxvar/0.5.2-0/lua-resty-ngxvar-0.5.2-0.rockspec b/deps/lib64/luarocks/rocks/lua-resty-ngxvar/0.5.2-0/lua-resty-ngxvar-0.5.2-0.rockspec new file mode 100644 index 0000000..3eb2adf --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-ngxvar/0.5.2-0/lua-resty-ngxvar-0.5.2-0.rockspec @@ -0,0 +1,20 @@ +package = "lua-resty-ngxvar" +version = "0.5.2-0" +source = { + url = "git://github.com/api7/lua-var-nginx-module", + tag = "v0.5.2" +} +description = { + summary = "Fetch nginx variable by FFI way for OpenResty which is faster", + homepage = "https://github.com/api7/lua-var-nginx-module", + license = "Apache License 2.0", + maintainer = "Yuansheng Wang " +} +build = { + type = "builtin", + modules = { + ["resty.ngxvar"] = "lib/resty/ngxvar.lua", + ["resty.ngxvar.http"] = "lib/resty/ngxvar/http.lua", + ["resty.ngxvar.stream"] = "lib/resty/ngxvar/stream.lua", + } +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-ngxvar/0.5.2-0/rock_manifest b/deps/lib64/luarocks/rocks/lua-resty-ngxvar/0.5.2-0/rock_manifest new file mode 100644 index 0000000..dfc174a --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-ngxvar/0.5.2-0/rock_manifest @@ -0,0 +1,16 @@ +rock_manifest = { + doc = { + LICENSE = "86d3f3a95c324c9479bd8986968f4327", + ["README.md"] = "615e23335da278e611b7ed6f90d43cee" + }, + lua = { + resty = { + ngxvar = { + ["http.lua"] = "81def76eb48065dfda5ee513c9189b56", + ["stream.lua"] = "ce85430397999c7357f6618af6b23f02" + }, + ["ngxvar.lua"] = "07a8b674a8f8b216da77889770b19acf" + } + }, + ["lua-resty-ngxvar-0.5.2-0.rockspec"] = "ca4d0b1cd45a078078535562023d3db8" +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-openidc/1.7.2-1/doc/LICENSE.txt b/deps/lib64/luarocks/rocks/lua-resty-openidc/1.7.2-1/doc/LICENSE.txt new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-openidc/1.7.2-1/doc/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/deps/lib64/luarocks/rocks/lua-resty-openidc/1.7.2-1/doc/README.md b/deps/lib64/luarocks/rocks/lua-resty-openidc/1.7.2-1/doc/README.md new file mode 100644 index 0000000..8f4cbd7 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-openidc/1.7.2-1/doc/README.md @@ -0,0 +1,600 @@ +[![Build Status](https://travis-ci.org/zmartzone/lua-resty-openidc.svg?branch=master)](https://travis-ci.org/zmartzone/lua-resty-openidc) +[OpenID Certification](https://openid.net/certification) + +# lua-resty-openidc + +**lua-resty-openidc** is a library for [NGINX](http://nginx.org/) implementing the +[OpenID Connect](http://openid.net/specs/openid-connect-core-1_0.html) **Relying Party (RP)** +and/or the [OAuth 2.0](https://tools.ietf.org/html/rfc6749) **Resource Server (RS)** functionality. + +When used as an OpenID Connect Relying Party it authenticates users against an OpenID Connect +Provider using [OpenID Connect Discovery](http://openid.net/specs/openid-connect-discovery-1_0.html) +and the Basic Client Profile (i.e. the Authorization Code flow). When used as an OAuth 2.0 +Resource Server it can validate OAuth 2.0 Bearer Access Tokens against an Authorization Server or, in +case a JSON Web Token is used for an Access Token, verification can happen against a pre-configured secret/key . + +It maintains sessions for authenticated users by leveraging `lua-resty-session` thus offering +a configurable choice between storing the session state in a client-side browser cookie or use +in of the server-side storage mechanisms `shared-memory|memcache|redis`. + +It supports server-wide caching of resolved Discovery documents and validated Access Tokens. + +It can be used as a reverse proxy terminating OAuth/OpenID Connect in front of an origin server so that +the origin server/services can be protected with the relevant standards without implementing those on +the server itself. + +## Dependencies + +**lua-resty-openidc** depends on the following packages: + +- [NGINX](http://nginx.org/) and [`ngx_devel_kit`](https://github.com/simpl/ngx_devel_kit) +- [Lua](http://www.lua.org/) or [LuaJIT](http://luajit.org/luajit.html) +- [`lua-nginx-module`](https://github.com/openresty/lua-nginx-module) +- [`lua-cjson`](http://www.kyne.com.au/~mark/software/lua-cjson.php) +- [`lua-resty-string`](https://github.com/openresty/lua-resty-string) + +The dependencies above come automatically with [OpenResty](http://openresty.org/). You will need +to install two extra pure-Lua dependencies that implement session management and HTTP client functions: + +- [`lua-resty-http`](https://github.com/pintsized/lua-resty-http) +- [`lua-resty-session`](https://github.com/bungle/lua-resty-session) + +Typically - when running as an OpenID Connect RP or an OAuth 2.0 server that consumes JWT +access tokens - you'll also need to install the following dependency: + +- [`lua-resty-jwt`](https://github.com/cdbattags/lua-resty-jwt) + +The `lua-resty-jwt` dependency above is *not* required when running as an OAuth 2.0 Resource Server (only) using remote +introspection for access token validation. + +## Installation + +If you're using `opm` execute the following: + + opm install zmartzone/lua-resty-openidc + +If you're using `luarocks` execute the following: + + luarocks install lua-resty-openidc + +Otherwise copy `openidc.lua` somewhere in your `lua_package_path` under a directory named `resty`. +If you are using [OpenResty](http://openresty.org/), the default location would be `/usr/local/openresty/lualib/resty`. + + +## Support + +#### Community Support +For generic questions, see the Wiki pages with Frequently Asked Questions at: + [https://github.com/zmartzone/lua-resty-openidc/wiki](https://github.com/zmartzone/lua-resty-openidc/wiki) +Any questions/issues should go to issues tracker. + +#### Commercial Services +For commercial Support contracts, Professional Services, Training and use-case specific support you can contact: + [sales@zmartzone.eu](mailto:sales@zmartzone.eu) + + +## Sample Configuration for Google+ Signin + +Sample `nginx.conf` configuration for authenticating users against Google+ Signin, protecting a reverse-proxied path. + +``` +events { + worker_connections 128; +} + +http { + + lua_package_path '~/lua/?.lua;;'; + + resolver 8.8.8.8; + + lua_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt; + lua_ssl_verify_depth 5; + + # cache for discovery metadata documents + lua_shared_dict discovery 1m; + # cache for JWKs + lua_shared_dict jwks 1m; + + # NB: if you have "lua_code_cache off;", use: + # set $session_secret xxxxxxxxxxxxxxxxxxx; + # see: https://github.com/bungle/lua-resty-session#notes-about-turning-lua-code-cache-off + + server { + listen 8080; + + location / { + + access_by_lua_block { + + local opts = { + -- the full redirect URI must be protected by this script + -- if the URI starts with a / the full redirect URI becomes + -- ngx.var.scheme.."://"..ngx.var.http_host..opts.redirect_uri + -- unless the scheme was overridden using opts.redirect_uri_scheme or an X-Forwarded-Proto header in the incoming request + redirect_uri = "https://MY_HOST_NAME/redirect_uri", + -- up until version 1.6.1 you'd specify + -- redirect_uri_path = "/redirect_uri", + -- and could not set the hostname + + -- The discovery endpoint of the OP. Enable to get the URI of all endpoints (Token, introspection, logout...) + discovery = "https://accounts.google.com/.well-known/openid-configuration", + + -- Access to OP Token endpoint requires an authentication. Several authentication modes are supported: + --token_endpoint_auth_method = ["client_secret_basic"|"client_secret_post"|"private_key_jwt"|"client_secret_jwt"], + -- o If token_endpoint_auth_method is set to "client_secret_basic", "client_secret_post", or "client_secret_jwt", authentication to Token endpoint is using client_id and client_secret + -- For non compliant OPs to OAuth 2.0 RFC 6749 for client Authentication (cf. https://tools.ietf.org/html/rfc6749#section-2.3.1) + -- client_id and client_secret MUST be invariant when url encoded + client_id = "", + client_secret = "", + -- o If token_endpoint_auth_method is set to "private_key_jwt" authentication to Token endpoint is using client_id, client_rsa_private_key and client_rsa_private_key_id to compute a signed JWT + -- client_rsa_private_key is the RSA private key to be used to sign the JWT generated by lua-resty-openidc for authentication to the OP + -- client_rsa_private_key_id (optional) is the key id to be set in the JWT header to identify which public key the OP shall use to verify the JWT signature + --client_id = "", + --client_rsa_private_key=[[-----BEGIN RSA PRIVATE KEY----- +MIIEogIBAAKCAQEAiThmpvXBYdur716D2q7fYKirKxzZIU5QrkBGDvUOwg5izcTv +[...] +h2JHukolz9xf6qN61QMLSd83+kwoBr2drp6xg3eGDLIkQCQLrkY= +-----END RSA PRIVATE KEY-----]], + --client_rsa_private_key_id="key id#1", + -- Life duration expressed in seconds of the signed JWT generated by lua-resty-openidc for authentication to the OP. + -- (used when token_endpoint_auth_method is set to "private_key_jwt" or "client_secret_jwt" authentication). Default is 60 seconds. + --client_jwt_assertion_expires_in = 60, + -- When using https to any OP endpoints, enforcement of SSL certificate check can be mandated ("yes") or not ("no"). + --ssl_verify = "no", + + --authorization_params = { hd="zmartzone.eu" }, + --scope = "openid email profile", + -- Refresh the users id_token after 900 seconds without requiring re-authentication + --refresh_session_interval = 900, + --iat_slack = 600, + --redirect_uri_scheme = "https", + --logout_path = "/logout", + --redirect_after_logout_uri = "/", + -- Where should the user be redirected after logout from the RP. This option overides any end_session_endpoint that the OP may have provided in the discovery response. + --redirect_after_logout_with_id_token_hint = true, + -- Whether the redirection after logout should include the id token as an hint (if available). This option is used only if redirect_after_logout_uri is set. + --post_logout_redirect_uri = "https://www.zmartzone.eu/logoutSuccessful", + -- Where does the RP requests that the OP redirects the user after logout. If this option is set to a relative URI, it will be relative to the OP's logout endpoint, not the RP's. + + --accept_none_alg = false + -- if your OpenID Connect Provider doesn't sign its id tokens + -- (uses the "none" signature algorithm) then set this to true. + + --accept_unsupported_alg = true + -- if you want to reject tokens signed using an algorithm + -- not supported by lua-resty-jwt set this to false. If + -- you leave it unset or set it to true, the token signature will not be + -- verified when an unsupported algorithm is used. + + --renew_access_token_on_expiry = true + -- whether this plugin shall try to silently renew the access token once it is expired if a refresh token is available. + -- if it fails to renew the token, the user will be redirected to the authorization endpoint. + --access_token_expires_in = 3600 + -- Default lifetime in seconds of the access_token if no expires_in attribute is present in the token endpoint response. + + --access_token_expires_leeway = 0 + -- Expiration leeway for access_token renewal. If this is set, renewal will happen access_token_expires_leeway seconds before the token expiration. This avoids errors in case the access_token just expires when arriving to the OAuth Resource Server. + + --force_reauthorize = false + -- When force_reauthorize is set to true the authorization flow will be executed even if a token has been cached already + --session_contents = {id_token=true} + -- Whitelist of session content to enable. This can be used to reduce the session size. + -- When not set everything will be included in the session. + -- Available are: + -- id_token, enc_id_token, user, access_token (includes refresh token) + + -- You can specify timeouts for connect/send/read as a single number (setting all timeouts) or as a table. Values are in milliseconds + -- timeout = 1000 + -- timeout = { connect = 500, send = 1000, read = 1000 } + + --use_nonce = false + -- By default the authorization request includes the + -- nonce paramter. You can use this option to disable it + -- which may be necessary when talking to a broken OpenID + -- Connect provider that ignores the paramter as the + -- id_token will be rejected otherwise. + + --revoke_tokens_on_logout = false + -- When revoke_tokens_on_logout is set to true a logout notifies the authorization server that previously obtained refresh and access tokens are no longer needed. This requires that revocation_endpoint is discoverable. + -- If there is no revocation endpoint supplied or if there are errors on revocation the user will not be notified and the logout process continues normally. + + -- Optional : use outgoing proxy to the OpenID Connect provider endpoints with the proxy_opts table : + -- this requires lua-resty-http >= 0.12 + -- proxy_opts = { + -- http_proxy = "http://:/", + -- https_proxy = "http://:/" + -- } + + -- Lifecycle Hooks + -- + -- lifecycle = { + -- on_created = handle_created, + -- on_authenticated = handle_authenticated, + -- on_regenerated = handle_regenerated + -- on_logout = handle_logout + -- } + -- + -- where `handle_created`, `handle_authenticated`, `handle_regenerated` and `handle_logout` are callables + -- accepting a single argument `session` + -- + -- -- `on_created` hook is invoked *after* a session has been created in + -- `openidc_authorize` immediately prior to saving the session + -- -- `on_authenticated` hook is invoked *after* receiving authorization response in + -- `openidc_authorization_response` immediately prior to saving the session + -- -- `on_regenerated` is invoked immediately after the + a new access token has been obtained via token + refresh and is called with the regenerated session table + -- -- `on_logout` hook is invoked *before* a session is destroyed in + -- `openidc_logout` + -- + -- Any, all or none of the hooks may be used. Empty `lifecycle` does nothing. + + -- Optional : add decorator for HTTP request that is + -- applied when lua-resty-openidc talks to the OpenID Connect + -- provider directly. Can be used to provide extra HTTP headers + -- or add other similar behavior. + -- http_request_decorator = function(req) + -- local h = req.headers or {} + -- h[EXTRA_HEADER] = 'my extra header' + -- req.headers = h + -- return req + -- end, + + } + + -- call authenticate for OpenID Connect user authentication + local res, err = require("resty.openidc").authenticate(opts) + + if err then + ngx.status = 500 + ngx.say(err) + ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR) + end + + -- at this point res is a Lua table with 3 keys: + -- id_token : a Lua table with the claims from the id_token (required) + -- access_token: the access token (optional) + -- user : a Lua table with the claims returned from the user info endpoint (optional) + + --if res.id_token.hd ~= "zmartzone.eu" then + -- ngx.exit(ngx.HTTP_FORBIDDEN) + --end + + --if res.user.email ~= "hans.zandbelt@zmartzone.eu" then + -- ngx.exit(ngx.HTTP_FORBIDDEN) + --end + + -- set headers with user info: this will overwrite any existing headers + -- but also scrub(!) them in case no value is provided in the token + ngx.req.set_header("X-USER", res.id_token.sub) + } + + proxy_pass http://localhost:80; + } + } +} +``` + +## Check authentication only + +``` +-- check session, but do not redirect to auth if not already logged in +local res, err = require("resty.openidc").authenticate(opts, nil, "pass") +``` + +## Check authentication only and deny unauthenticated access + +``` +-- check session, do not redirect to auth if not already logged in but return an error instead +local res, err = require("resty.openidc").authenticate(opts, nil, "deny") +``` + +## Sample Configuration for OAuth 2.0 JWT Token Validation + +Sample `nginx.conf` configuration for verifying Bearer JWT Access Tokens against a pre-configured secret/key. +Once successfully verified, the NGINX server may function as a reverse proxy to an internal origin server. + +``` +events { + worker_connections 128; +} + +http { + + lua_package_path '~/lua/?.lua;;'; + + resolver 8.8.8.8; + + # cache for JWT verification results + lua_shared_dict introspection 10m; + + server { + listen 8080; + + location /api { + + access_by_lua ' + + local opts = { + + -- 1. example of a shared secret for HS??? signature verification + --symmetric_key = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + -- in versions up to 1.6.1 this option's key would have been secret + -- rather than symmetric_key + + -- 2. another example of a public cert for RS??? signature verification + public_key = [[-----BEGIN CERTIFICATE----- +MIIC0DCCAbigAwIBAgIGAVSbMZs1MA0GCSqGSIb3DQEBCwUAMCkxCzAJBgNVBAYTAlVTMQwwCgYD +VQQKEwNibGExDDAKBgNVBAMTA2JsYTAeFw0xNjA1MTAxNTAzMjBaFw0yNjA1MDgxNTAzMjBaMCkx +CzAJBgNVBAYTAlVTMQwwCgYDVQQKEwNibGExDDAKBgNVBAMTA2JsYTCCASIwDQYJKoZIhvcNAQEB +BQADggEPADCCAQoCggEBAIcLtHjX2GFxYv1033dvfohyCU6nsuR1qoDXfHTG3Mf/Yj4BfLHtMjJr +nR3sgHItH3B6qZPnfErfsN0LP4uZ10/74CrWVqT5dy6ecXMqYtz/KNJ8rG0vY8vltc417AU4fie8 +gyeWv/Z6wHWUCf3NHRV8GfFgfuvywgUpHo8ujpUPFr+zrPr8butrzJPq1h3+r0f5P45tfWOdpjCT +gsTzK6urUG0k3WkwdDYapL3wRCAw597nYfgKzzXuh9N0ZL3Uj+eJ6BgCzUZDLXABpMBZfk6hmmzp +cAFV4nTf1AaAs/EOwVE0YgZBJiBrueMcteAIxKrKjEHgThU2Zs9gN9cSFicCAwEAATANBgkqhkiG +9w0BAQsFAAOCAQEAQLU1A58TrSwrEccCIy0wxiGdCwQbaNMohzirc41zRMCXleJXbtsn1vv85J6A +RmejeH5f/JbDqRRRArGMdLooGbqjWG/lwZT456Q6DXqF2plkBvh37kp/GjthGyR8ODJn5ekZwxuB +OcTuruRhqYOIJjiYZSgK/P0zUw1cjLwUJ9ig/O6ozYmof83974fygA/wK3SgFNEoFlTkTpOvZhVW +9kLfCVA/CRBfJNKnz5PWBBxd/3XSEuP/fcWqKGTy7zZso4MTB0NKgWO4duGTgMyZbM4onJPyA0CY +lAc5Csj0o5Q+oEhPUAVBIF07m4rd0OvAVPOCQ2NJhQSL1oWASbf+fg== +-----END CERTIFICATE-----]], + -- in versions up to 1.6.1 this option's key would have been secret + -- rather than public_key + + -- 3. alternatively one can point to a so-called Discovery document that + -- contains "jwks_uri" entry; the jwks endpoint must provide either an "x5c" entry + -- or both the "n" modulus and "e" exponent entries for RSA signature verification + -- discovery = "https://accounts.google.com/.well-known/openid-configuration", + + -- the signature algorithm that you expect has been used; + -- can be a single string or a table. + -- You should set this for security reasons in order to + -- avoid accepting a token claiming to be signed by HMAC + -- using a public RSA key. + --token_signing_alg_values_expected = { "RS256" } + + -- if you want to accept unsigned tokens (using the + -- "none" signature algorithm) then set this to true. + --accept_none_alg = false + + -- if you want to reject tokens signed using an algorithm + -- not supported by lua-resty-jwt set this to false. If + -- you leave it unset, the token signature will not be + -- verified at all. + --accept_unsupported_alg = true + + -- the expiration time in seconds for jwk cache, default is 1 day. + --jwk_expires_in = 24 * 60 * 60 + + } + + -- call bearer_jwt_verify for OAuth 2.0 JWT validation + local res, err = require("resty.openidc").bearer_jwt_verify(opts) + + if err or not res then + ngx.status = 403 + ngx.say(err and err or "no access_token provided") + ngx.exit(ngx.HTTP_FORBIDDEN) + end + + -- at this point res is a Lua table that represents the (validated) JSON + -- payload in the JWT token; now we typically do not want to allow just any + -- token that was issued by the Authorization Server but we want to apply + -- some access restrictions via client IDs or scopes + + --if res.scope ~= "edit" then + -- ngx.exit(ngx.HTTP_FORBIDDEN) + --end + + --if res.client_id ~= "ro_client" then + -- ngx.exit(ngx.HTTP_FORBIDDEN) + --end + '; + + proxy_pass http://localhost:80; + } + } +} +``` + +## Sample Configuration for PingFederate OAuth 2.0 + +Sample `nginx.conf` configuration for validating Bearer Access Tokens against a PingFederate OAuth 2.0 Authorization Server. + +``` +events { + worker_connections 128; +} + +http { + + lua_package_path '~/lua/?.lua;;'; + + resolver 8.8.8.8; + + lua_ssl_trusted_certificate /opt/local/etc/openssl/cert.pem; + lua_ssl_verify_depth 5; + + # cache for validation results + lua_shared_dict introspection 10m; + + server { + listen 8080; + + location /api { + + access_by_lua ' + + local opts = { + introspection_endpoint="https://localhost:9031/as/introspect.oauth2", + client_id="rs_client", + client_secret="2Federate", + ssl_verify = "no", + + -- Defaults to "exp" - Controls the TTL of the introspection cache + -- https://tools.ietf.org/html/rfc7662#section-2.2 + -- introspection_expiry_claim = "exp" + } + + -- call introspect for OAuth 2.0 Bearer Access Token validation + local res, err = require("resty.openidc").introspect(opts) + + if err then + ngx.status = 403 + ngx.say(err) + ngx.exit(ngx.HTTP_FORBIDDEN) + end + + -- at this point res is a Lua table that represents the JSON + -- object returned from the introspection/validation endpoint + + --if res.scope ~= "edit" then + -- ngx.exit(ngx.HTTP_FORBIDDEN) + --end + + --if res.client_id ~= "ro_client" then + -- ngx.exit(ngx.HTTP_FORBIDDEN) + --end + '; + } + } +} +``` +## Sample Configuration for passing bearer OAuth 2.0 access tokens as cookie + +Sample `nginx.conf` configuration for validating Bearer Access Tokens passed as cookie against a ORY/Hydra Authorization Server. + +``` +events { + worker_connections 128; +} + +http { + + lua_package_path '~/lua/?.lua;;'; + + resolver 8.8.8.8; + + lua_ssl_trusted_certificate /opt/local/etc/openssl/cert.pem; + lua_ssl_verify_depth 5; + + # cache for validation results + lua_shared_dict introspection 10m; + + server { + listen 8080; + + location /api { + + access_by_lua ' + + local opts = { + -- sets the URI of the introspection endpoint + introspection_endpoint="https://localhost:9031/oauth2/introspect", + + -- alternatively if your OAuth2 Provider provides a discovery document that contains the + -- introspection_endpoint claim you can leave the introspection_endpoint option + -- unset and instead use + -- discovery = "https://my-oauth2-provider/.well-known/oauth-authorization-server", + + client_id="admin", + client_secret="demo-password", + ssl_verify = "no", + + -- Defines the interval in seconds after which a cached and introspected access token needs + -- to be refreshed by introspecting (and validating) it again against the Authorization Server. + -- When not defined the value is 0, which means it only expires after the `exp` (or alternative, + -- see introspection_expiry_claim) hint as returned by the Authorization Server + -- introspection_interval = 60, + + -- Defines the way in which bearer OAuth 2.0 access tokens can be passed to this Resource Server. + -- "cookie" as a cookie header called "PA.global" or using the name specified after ":" + -- "header" "Authorization: bearer" header + -- When not defined the default "Authorization: bearer" header is used + -- auth_accept_token_as = "cookie:PA", + + -- If header is used header field is Authorization + -- auth_accept_token_as_header_name = "cf-Access-Jwt-Assertion" + + -- Authentication method for the OAuth 2.0 Authorization Server introspection endpoint, + -- Used to authenticate the client to the introspection endpoint with a client_id/client_secret + -- Defaults to "client_secret_post" + -- introspection_endpoint_auth_method = "client_secret_basic", + + -- Specify the names of cookies separated by whitespace to pickup from the browser and send along on backchannel + -- calls to the OP and AS endpoints. + -- When not defined, no such cookies are sent. + -- pass_cookies = "JSESSION" + + -- Defaults to "exp" - Controls the TTL of the introspection cache + -- https://tools.ietf.org/html/rfc7662#section-2.2 + -- introspection_expiry_claim = "exp" + + -- It may be necessary to force an introspection call for an access_token and ignore the existing cached + -- introspection results. If so you need to set set the introspection_cache_ignore option to true. + -- introspection_cache_ignore = true + } + + -- call introspect for OAuth 2.0 Bearer Access Token validation + local res, err = require("resty.openidc").introspect(opts) + + if err then + ngx.status = 403 + ngx.say(err) + ngx.exit(ngx.HTTP_FORBIDDEN) + end + + -- at this point res is a Lua table that represents the JSON + -- object returned from the introspection/validation endpoint + + --if res.scope ~= "edit" then + -- ngx.exit(ngx.HTTP_FORBIDDEN) + --end + + --if res.client_id ~= "ro_client" then + -- ngx.exit(ngx.HTTP_FORBIDDEN) + --end + '; + } + } +} +``` + +## Logging + +Logging can be customized, including using custom logger and remapping OpenIDC's +default log levels, e.g: + +```lua +local openidc = require("resty.openidc") +openidc.set_logging(nil, { DEBUG = ngx.INFO }) +``` + +## Running Tests + +We've created a dockerized setup for the test in order to simplify the +installation of dependencies. + +In order to run the tests perform + +```shell +$ docker build -f tests/Dockerfile . -t lua-resty-openidc/test +$ docker run -it --rm lua-resty-openidc/test:latest +``` + +if you want to create +[luacov](https://keplerproject.github.io/luacov/) coverage while +testing use + +```shell +$ docker run -it --rm -e coverage=t lua-resty-openidc/test:latest +``` + +as the second command + +Disclaimer +---------- + +*This software is open sourced by ZmartZone IAM. For commercial support +you can contact [ZmartZone IAM](https://www.zmartzone.eu) as described above in the [Support](#support) section.* diff --git a/deps/lib64/luarocks/rocks/lua-resty-openidc/1.7.2-1/lua-resty-openidc-1.7.2-1.rockspec b/deps/lib64/luarocks/rocks/lua-resty-openidc/1.7.2-1/lua-resty-openidc-1.7.2-1.rockspec new file mode 100644 index 0000000..d2d4234 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-openidc/1.7.2-1/lua-resty-openidc-1.7.2-1.rockspec @@ -0,0 +1,35 @@ +package = "lua-resty-openidc" +version = "1.7.2-1" +source = { + url = "git://github.com/zmartzone/lua-resty-openidc", + tag = "v1.7.2", + dir = "lua-resty-openidc" +} +description = { + summary = "A library for NGINX implementing the OpenID Connect Relying Party (RP) and the OAuth 2.0 Resource Server (RS) functionality", + detailed = [[ + lua-resty-openidc is a library for NGINX implementing the OpenID Connect Relying Party (RP) and the OAuth 2.0 Resource Server (RS) functionality. + + When used as an OpenID Connect Relying Party it authenticates users against an OpenID Connect Provider using OpenID Connect Discovery and the Basic Client Profile (i.e. the Authorization Code flow). When used as an OAuth 2.0 Resource Server it can validate OAuth 2.0 Bearer Access Tokens against an Authorization Server or, in case a JSON Web Token is used for an Access Token, verification can happen against a pre-configured secret/key . + + It maintains sessions for authenticated users by leveraging lua-resty-session thus offering a configurable choice between storing the session state in a client-side browser cookie or use in of the server-side storage mechanisms shared-memory|memcache|redis. + + It supports server-wide caching of resolved Discovery documents and validated Access Tokens. + + It can be used as a reverse proxy terminating OAuth/OpenID Connect in front of an origin server so that the origin server/services can be protected with the relevant standards without implementing those on the server itself. + ]], + homepage = "https://github.com/zmartzone/lua-resty-openidc", + license = "Apache 2.0" +} +dependencies = { + "lua >= 5.1", + "lua-resty-http >= 0.08", + "lua-resty-session >= 2.8", + "lua-resty-jwt >= 0.2.0" +} +build = { + type = "builtin", + modules = { + ["resty.openidc"] = "lib/resty/openidc.lua" + } +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-openidc/1.7.2-1/rock_manifest b/deps/lib64/luarocks/rocks/lua-resty-openidc/1.7.2-1/rock_manifest new file mode 100644 index 0000000..4722a3f --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-openidc/1.7.2-1/rock_manifest @@ -0,0 +1,12 @@ +rock_manifest = { + doc = { + ["LICENSE.txt"] = "3b83ef96387f14655fc854ddc3c6bd57", + ["README.md"] = "fa238368b8b7b750070435fb1db221c1" + }, + lua = { + resty = { + ["openidc.lua"] = "a3b837006a3315afb80d782280a90c28" + } + }, + ["lua-resty-openidc-1.7.2-1.rockspec"] = "29cf608ba5ecf949175c3c5bb29fc2fe" +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-prometheus/1.1-0/doc/LICENSE b/deps/lib64/luarocks/rocks/lua-resty-prometheus/1.1-0/doc/LICENSE new file mode 100644 index 0000000..bcf2ddf --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-prometheus/1.1-0/doc/LICENSE @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2016-2019 Anton Tolchanov + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/deps/lib64/luarocks/rocks/lua-resty-prometheus/1.1-0/doc/README.md b/deps/lib64/luarocks/rocks/lua-resty-prometheus/1.1-0/doc/README.md new file mode 100644 index 0000000..9bc06a8 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-prometheus/1.1-0/doc/README.md @@ -0,0 +1,455 @@ +[![Build Status](https://secure.travis-ci.org/knyar/nginx-lua-prometheus.svg?branch=master)](http://travis-ci.org/knyar/nginx-lua-prometheus?branch=master) +[![Coverage Status](https://coveralls.io/repos/github/knyar/nginx-lua-prometheus/badge.svg?branch=master)](https://coveralls.io/github/knyar/nginx-lua-prometheus?branch=master) + +# Prometheus metric library for Nginx + +This is a Lua library that can be used with Nginx to keep track of metrics and +expose them on a separate web page to be pulled by +[Prometheus](https://prometheus.io). + +## Installation + +You need to install nginx package with lua support (`libnginx-mod-http-lua` on +newer Debian versions, or `nginx-extras` on older ones). The library file, +`prometheus.lua`, needs to be available in `LUA_PATH`. If this is the only Lua +library you use, you can just point `lua_package_path` to the directory with +this git repo checked out (see example below). + +OpenResty users will find this library in [opm](https://opm.openresty.org/). It +is also available via +[luarocks](https://luarocks.org/modules/knyar/nginx-lua-prometheus). + +## Quick start guide + +To track request latency broken down by server name and request count +broken down by server name and status, add the following to the `http` section +of `nginx.conf`: + +``` +lua_shared_dict prometheus_metrics 10M; +lua_package_path "/path/to/nginx-lua-prometheus/?.lua;;"; +init_worker_by_lua_block { + prometheus = require("prometheus").init("prometheus_metrics") + metric_requests = prometheus:counter( + "nginx_http_requests_total", "Number of HTTP requests", {"host", "status"}) + metric_latency = prometheus:histogram( + "nginx_http_request_duration_seconds", "HTTP request latency", {"host"}) + metric_connections = prometheus:gauge( + "nginx_http_connections", "Number of HTTP connections", {"state"}) +} +log_by_lua_block { + metric_requests:inc(1, {ngx.var.server_name, ngx.var.status}) + metric_latency:observe(tonumber(ngx.var.request_time), {ngx.var.server_name}) +} +``` + +This: +* configures a shared dictionary for your metrics called `prometheus_metrics` + with a 10MB size limit; +* registers a counter called `nginx_http_requests_total` with two labels: + `host` and `status`; +* registers a histogram called `nginx_http_request_duration_seconds` with one + label `host`; +* registers a gauge called `nginx_http_connections` with one label `state`; +* on each HTTP request measures its latency, recording it in the histogram and + increments the counter, setting current server name as the `host` label and + HTTP status code as the `status` label. + +Last step is to configure a separate server that will expose the metrics. +Please make sure to only make it reachable from your Prometheus server: + +``` +server { + listen 9145; + allow 192.168.0.0/16; + deny all; + location /metrics { + content_by_lua_block { + metric_connections:set(ngx.var.connections_reading, {"reading"}) + metric_connections:set(ngx.var.connections_waiting, {"waiting"}) + metric_connections:set(ngx.var.connections_writing, {"writing"}) + prometheus:collect() + } + } +} +``` + +Metrics will be available at `http://your.nginx:9145/metrics`. Note that the +gauge metric in this example contains values obtained from nginx global state, +so they get set immediately before metrics are returned to the client. + +## API reference + +### init() + +**syntax:** require("prometheus").init(*dict_name*, [*options*]]) + +Initializes the module. This should be called once from the +[init_worker_by_lua_block](https://github.com/openresty/lua-nginx-module#init_worker_by_lua_block) +section of nginx configuration. + +* `dict_name` is the name of the nginx shared dictionary which will be used to + store all metrics. Defaults to `prometheus_metrics` if not specified. +* `options` is a table of configuration options that can be provided. Accepted + options are: + * `prefix` (string): metric name prefix. This string will be prepended to + metric names on output. + * `error_metric_name` (string): Can be used to change the default name of + error metric (see [Built-in metrics](#built-in-metrics) for details). + * `sync_interval` (number): sets per-worker counter sync interval in seconds. + This sets the boundary on eventual consistency of counter metrics. Defaults + to 1. + +Returns a `prometheus` object that should be used to register metrics. + +Example: +``` +init_worker_by_lua_block { + prometheus = require("prometheus").init("prometheus_metrics", {sync_interval=3}) +} +``` + +### prometheus:counter() + +**syntax:** prometheus:counter(*name*, *description*, *label_names*) + +Registers a counter. Should be called once for each counter from the +[init_worker_by_lua_block]( +https://github.com/openresty/lua-nginx-module#init_worker_by_lua_block) +section. + +* `name` is the name of the metric. +* `description` is the text description that will be presented to Prometheus + along with the metric. Optional (pass `nil` if you still need to define + label names). +* `label_names` is an array of label names for the metric. Optional. + +[Naming section](https://prometheus.io/docs/practices/naming/) of Prometheus +documentation provides good guidelines on choosing metric and label names. + +Returns a `counter` object that can later be incremented. + +Example: +``` +init_worker_by_lua_block { + prometheus = require("prometheus").init("prometheus_metrics") + metric_bytes = prometheus:counter( + "nginx_http_request_size_bytes", "Total size of incoming requests") + metric_requests = prometheus:counter( + "nginx_http_requests_total", "Number of HTTP requests", {"host", "status"}) +} +``` + +### prometheus:gauge() + +**syntax:** prometheus:gauge(*name*, *description*, *label_names*) + +Registers a gauge. Should be called once for each gauge from the +[init_worker_by_lua_block]( +https://github.com/openresty/lua-nginx-module#init_worker_by_lua_block) +section. + +* `name` is the name of the metric. +* `description` is the text description that will be presented to Prometheus + along with the metric. Optional (pass `nil` if you still need to define + label names). +* `label_names` is an array of label names for the metric. Optional. + +Returns a `gauge` object that can later be set. + +Example: +``` +init_worker_by_lua_block { + prometheus = require("prometheus").init("prometheus_metrics") + metric_connections = prometheus:gauge( + "nginx_http_connections", "Number of HTTP connections", {"state"}) +} +``` + +### prometheus:histogram() + +**syntax:** prometheus:histogram(*name*, *description*, *label_names*, + *buckets*) + +Registers a histogram. Should be called once for each histogram from the +[init_worker_by_lua_block]( +https://github.com/openresty/lua-nginx-module#init_worker_by_lua_block) +section. + +* `name` is the name of the metric. +* `description` is the text description. Optional. +* `label_names` is an array of label names for the metric. Optional. +* `buckets` is an array of numbers defining bucket boundaries. Optional, + defaults to 20 latency buckets covering a range from 5ms to 10s (in seconds). + +Returns a `histogram` object that can later be used to record samples. + +Example: +``` +init_worker_by_lua_block { + prometheus = require("prometheus").init("prometheus_metrics") + metric_latency = prometheus:histogram( + "nginx_http_request_duration_seconds", "HTTP request latency", {"host"}) + metric_response_sizes = prometheus:histogram( + "nginx_http_response_size_bytes", "Size of HTTP responses", nil, + {10,100,1000,10000,100000,1000000}) +} +``` + +### prometheus:collect() + +**syntax:** prometheus:collect() + +Presents all metrics in a text format compatible with Prometheus. This should be +called in +[content_by_lua_block](https://github.com/openresty/lua-nginx-module#content_by_lua_block) +to expose the metrics on a separate HTTP page. + +Example: +``` +location /metrics { + content_by_lua_block { prometheus:collect() } + allow 192.168.0.0/16; + deny all; +} +``` + +### prometheus:metric_data() + +**syntax:** prometheus:metric_data() + +Returns metric data as an array of strings. + +### counter:inc() + +**syntax:** counter:inc(*value*, *label_values*) + +Increments a previously registered counter. This is usually called from +[log_by_lua_block](https://github.com/openresty/lua-nginx-module#log_by_lua_block) +globally or per server/location. + +* `value` is a value that should be added to the counter. Defaults to 1. +* `label_values` is an array of label values. + +The number of label values should match the number of label names defined when +the counter was registered using `prometheus:counter()`. No label values should +be provided for counters with no labels. Non-printable characters will be +stripped from label values. + +Example: +``` +log_by_lua_block { + metric_bytes:inc(tonumber(ngx.var.request_length)) + metric_requests:inc(1, {ngx.var.server_name, ngx.var.status}) +} +``` + +### counter:del() + +**syntax:** counter:del(*label_values*) + +Delete a previously registered counter. This is usually called when you don't +need to observe such counter (or a metric with specific label values in this +counter) any more. If this counter has labels, you have to pass `label_values` +to delete the specific metric of this counter. If you want to delete all the +metrics of a counter with labels, you should call `Counter:reset()`. + +* `label_values` is an array of label values. + +The number of label values should match the number of label names defined when +the counter was registered using `prometheus:counter()`. No label values should +be provided for counters with no labels. Non-printable characters will be +stripped from label values. + +This function will wait for `sync_interval` before deleting the metric to +allow all workers to sync their counters. + +### counter:reset() + +**syntax:** counter:reset() + +Delete all metrics for a previously registered counter. If this counter have no +labels, it is just the same as `Counter:del()` function. If this counter have labels, +it will delete all the metrics with different label values. + +This function will wait for `sync_interval` before deleting the metrics to +allow all workers to sync their counters. + +### gauge:set() + +**syntax:** gauge:set(*value*, *label_values*) + +Sets the current value of a previously registered gauge. This could be called +from [log_by_lua_block](https://github.com/openresty/lua-nginx-module#log_by_lua_block) +globally or per server/location to modify a gauge on each request, or from +[content_by_lua_block](https://github.com/openresty/lua-nginx-module#content_by_lua_block) +just before `prometheus::collect()` to return a real-time value. + +* `value` is a value that the gauge should be set to. Required. +* `label_values` is an array of label values. + +### gauge:inc() + +**syntax:** gauge:inc(*value*, *label_values*) + +Increments or decrements a previously registered gauge. This is usually called +when you want to observe the real-time value of a metric that can both be +increased and decreased. + +* `value` is a value that should be added to the gauge. It could be a negative +value when you need to decrease the value of the gauge. Defaults to 1. +* `label_values` is an array of label values. + +The number of label values should match the number of label names defined when +the gauge was registered using `prometheus:gauge()`. No label values should +be provided for gauges with no labels. Non-printable characters will be +stripped from label values. + +### gauge:del() + +**syntax:** gauge:del(*label_values*) + +Delete a previously registered gauge. This is usually called when you don't +need to observe such gauge (or a metric with specific label values in this +gauge) any more. If this gauge has labels, you have to pass `label_values` +to delete the specific metric of this gauge. If you want to delete all the +metrics of a gauge with labels, you should call `Gauge:reset()`. + +* `label_values` is an array of label values. + +The number of label values should match the number of label names defined when +the gauge was registered using `prometheus:gauge()`. No label values should +be provided for gauges with no labels. Non-printable characters will be +stripped from label values. + +### gauge:reset() + +**syntax:** gauge:reset() + +Delete all metrics for a previously registered gauge. If this gauge have no +labels, it is just the same as `Gauge:del()` function. If this gauge have labels, +it will delete all the metrics with different label values. + +### histogram:observe() + +**syntax:** histogram:observe(*value*, *label_values*) + +Records a value in a previously registered histogram. Usually called from +[log_by_lua_block](https://github.com/openresty/lua-nginx-module#log_by_lua_block) +globally or per server/location. + +* `value` is a value that should be recorded. Required. +* `label_values` is an array of label values. + +Example: +``` +log_by_lua_block { + metric_latency:observe(tonumber(ngx.var.request_time), {ngx.var.server_name}) + metric_response_sizes:observe(tonumber(ngx.var.bytes_sent)) +} +``` + +### Built-in metrics + +The module increments an error metric called `nginx_metric_errors_total` +(unless another name was configured in [init()](#init)) if it encounters +an error (for example, when `lua_shared_dict` becomes full). You might want +to configure an alert on that metric. + +## Caveats + +### Usage in stream module + +For now, there is no way to share a dictionary between HTTP and Stream modules +in Nginx. If you are using this library to collect metrics from stream module, +you will need to configure a separate endpoint to return them. Here's an +example. + +``` +server { + listen 9145; + content_by_lua_block { + local sock = assert(ngx.req.socket(true)) + local data = sock:receive() + local location = "GET /metrics" + if string.sub(data, 1, string.len(location)) == location then + ngx.say("HTTP/1.1 200 OK") + ngx.say("Content-Type: text/plain") + ngx.say("") + ngx.say(table.concat(prometheus:metric_data(), "")) + else + ngx.say("HTTP/1.1 404 Not Found") + end + } +} +``` + +## Troubleshooting + +### Make sure that nginx lua module is enabled + +If you experience problems indicating that nginx doesn't know how to interpret +lua scripts, please make sure that [the lua +module](https://github.com/openresty/lua-nginx-module) is enabled. You might +need something like this in your `nginx.conf`: + + load_module modules/ndk_http_module.so; + load_module modules/ngx_http_lua_module.so; + +### Keep lua code cache enabled + +This module expects the +[lua_code_cache](https://github.com/openresty/lua-nginx-module#lua_code_cache) +option to be `on` (which is the default). + +## Development + +### Install dependencies for testing + +- `luarocks install luacheck` +- `luarocks install luaunit` + +### Run tests + +- `luacheck --globals ngx -- prometheus.lua` +- `lua prometheus_test.lua` +- `cd integration && ./test.sh` (requires Docker and Go) + +### Releasing new version + +- update version in the `dist.ini` +- rename `.rockspec` file and update version inside it +- commit changes +- push to luarocks: `luarocks upload nginx-lua-prometheus-0.20181120-1.rockspec` +- upload to OPM: `opm build && opm upload` +- create a new Git tag: `git tag 0.XXXXXXXX-X && git push origin 0.XXXXXXXX-X` + +## Credits + +- Created and maintained by Anton Tolchanov ([@knyar](https://github.com/knyar)) +- Metrix prefix support contributed by david birdsong ([@davidbirdsong]( + https://github.com/davidbirdsong)) +- Gauge support contributed by Cosmo Petrich ([@cosmopetrich]( + https://github.com/cosmopetrich)) +- Performance improvements and per-worker counters are contributed by Wangchong + Zhou ([@fffonion](https://github.com/fffonion)) / [@Kong]( + https://github.com/Kong). +- Metric name tracking improvements contributed by Jan Dolinár ([@dolik-rce]( + https://github.com/dolik-rce)) + +## License + +Licensed under MIT license. + +### Third Party License + +Following third party modules are used in this library: + +- [Kong/lua-resty-counter](https://github.com/Kong/lua-resty-counter) + +This module is licensed under the Apache 2.0 license. + +Copyright (C) 2019, Kong Inc. + +All rights reserved. + diff --git a/deps/lib64/luarocks/rocks/lua-resty-prometheus/1.1-0/lua-resty-prometheus-1.1-0.rockspec b/deps/lib64/luarocks/rocks/lua-resty-prometheus/1.1-0/lua-resty-prometheus-1.1-0.rockspec new file mode 100644 index 0000000..2d7a35c --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-prometheus/1.1-0/lua-resty-prometheus-1.1-0.rockspec @@ -0,0 +1,22 @@ +package = "lua-resty-prometheus" +version = "1.1-0" + +source = { + url = "git://github.com/api7/lua-resty-prometheus.git", + tag = "1.1", +} + +description = { + summary = "Prometheus metric library for OpenResty", + homepage = "https://github.com/api7/lua-resty-prometheus", + license = "MIT" +} + +build = { + type = "builtin", + modules = { + ["prometheus"] = "prometheus.lua", + ["prometheus_resty_counter"] = "prometheus_resty_counter.lua", + ["prometheus_keys"] = "prometheus_keys.lua", + } +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-prometheus/1.1-0/rock_manifest b/deps/lib64/luarocks/rocks/lua-resty-prometheus/1.1-0/rock_manifest new file mode 100644 index 0000000..f9757c2 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-prometheus/1.1-0/rock_manifest @@ -0,0 +1,12 @@ +rock_manifest = { + doc = { + LICENSE = "d01a98470cdd2f3c0e4c16a52e64c1fb", + ["README.md"] = "7b84d5385685528c5c04317667ea970f" + }, + lua = { + ["prometheus.lua"] = "df38fd875e8ec85dcaa5c95de1072f05", + ["prometheus_keys.lua"] = "0a52ca43538b5a84e140adb8cdeb2c74", + ["prometheus_resty_counter.lua"] = "2852321bc42c146004bf90474851a005" + }, + ["lua-resty-prometheus-1.1-0.rockspec"] = "bae3dd3a1701701fc222fc93eb4f5b39" +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-radixtree/2.5-0/doc/LICENSE b/deps/lib64/luarocks/rocks/lua-resty-radixtree/2.5-0/doc/LICENSE new file mode 100644 index 0000000..c2f0ea0 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-radixtree/2.5-0/doc/LICENSE @@ -0,0 +1,218 @@ + 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 2019-2020 Shenzhen ZhiLiu Technology Co., Ltd. https://www.apiseven.com + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +======================================================================= +lua-resty-radixtree Subcomponents: + +The lua-resty-radixtree project contains subcomponents with separate copyright +notices and license terms. Your use of the source code for the these +subcomponents is subject to the terms and conditions of the following +licenses. + +======================================================================== +BSD licenses +======================================================================== + +The following components are provided under a BSD license. See project link for details. +The text of each license is also included at licenses/LICENSE-[project].txt. + + rax files from https://github.com/antirez/rax BSD-2-Clause License diff --git a/deps/lib64/luarocks/rocks/lua-resty-radixtree/2.5-0/doc/README.md b/deps/lib64/luarocks/rocks/lua-resty-radixtree/2.5-0/doc/README.md new file mode 100644 index 0000000..e8a37cc --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-radixtree/2.5-0/doc/README.md @@ -0,0 +1,270 @@ +# Table of Contents + +- [Table of Contents](#table-of-contents) + - [Name](#name) + - [Synopsis](#synopsis) + - [Methods](#methods) + - [new](#new) + - [Path](#path) + - [Full path match](#full-path-match) + - [Prefix match](#prefix-match) + - [Parameters in path](#parameters-in-path) + - [match](#match) + - [dispatch](#dispatch) + - [Install](#install) + - [Compile and install](#compile-and-install) + - [DEV ENV](#dev-env) + - [Install Dependencies](#install-dependencies) + - [Benchmark](#benchmark) + +## Name + +This is Lua implementation library base on FFI for [rax](https://github.com/antirez/rax). + +[![Build Status](https://travis-ci.org/iresty/lua-resty-radixtree.svg?branch=master)](https://travis-ci.org/iresty/lua-resty-radixtree) +[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/iresty/lua-resty-radixtree/blob/master/LICENSE) + +This project depends on [lua-resty-ipmatcher](https://github.com/iresty/lua-resty-ipmatcher). + +This project has been working in microservices API gateway [Apache APISIX](https://github.com/apache/incubator-apisix). + +The project is open sourced by [Shenzhen ZhiLiu](https://www.apiseven.com/) Technology Co., Ltd. + +In addition to this open source version, our company also provides a more powerful and performing commercial version, and provides technical support. If you are interested in our commercial version, please [contact us](https://www.apiseven.com/). + +## Synopsis + +```lua + location / { + content_by_lua_block { + local radix = require("resty.radixtree") + local rx = radix.new({ + { + paths = {"/aa", "/bb*", "/name/:name/*other"}, + hosts = {"*.bar.com", "foo.com"}, + methods = {"GET", "POST", "PUT"}, + remote_addrs = {"127.0.0.1","192.168.0.0/16", + "::1", "fe80::/32"}, + vars = { + {"arg_name", "==", "json"}, + {"arg_weight", ">", 10}, + }, + filter_fun = function(vars, opts) + return vars["arg_name"] == "json" + end, + + metadata = "metadata /bb", + } + }) + + -- try to match + local opts = { + host = "foo.com", + method = "GET", + remote_addr = "127.0.0.1", + vars = ngx.var, + } + ngx.say(rx:match("/aa", opts)) + + -- try to match and store the cached value + local opts = { + host = "foo.com", + method = "GET", + remote_addr = "127.0.0.1", + vars = ngx.var, + matched = {} + } + ngx.say(rx:match("/name/json/foo/bar/gloo", opts)) + ngx.say("name: ", opts.matched.name, " other:", opts.matched.other) + } + } +``` + +[Back to TOC](#table-of-contents) + +## Methods + +### new + +`syntax: rx, err = radix.new(routes)` + +The routes is a array table, like `{ {...}, {...}, {...} }`, Each element in the array is a route, which is a hash table. + +The attributes of each element may contain these: + +|name |option |description|example| +|:-------- |:--------|:-----------|:-----| +|paths |required|A list of client request path. The default is a full match, but if the end of the path is `*`, it means that this is a prefix path. For example `/foo*`, it'll match `/foo/bar` or `/foo/glo/grey` etc.|{"/", "/aa", "/bb"}| +|hosts |option |A list of client request host, not only supports normal domain name, but also supports wildcard name.|{"foo.com", "*.bar.com"}| +|remote_addrs|option |A list of client remote address(IPv4 and IPv6), and we can use CIDR format, eg `192.168.1.0/24`.|{"127.0.0.1", "192.0.0.0/8", "::1", "fe80::/32"}| +|methods |option |A list of method name. Here is full valid method list: "GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS", "CONNECT" and "TRACE".|{"GET", "POST"}| +|vars |option |A DSL to evaluate with the given `opts.vars` or `ngx.var`. See https://github.com/api7/lua-resty-expr#new |{{"arg_name", "==", "json"}, {"arg_age", ">", 18}}| +|filter_fun |option |User defined filter function, We can use it to achieve matching logic for special scenes. `radixtree` will pass `vars` and other arguments when matching route.|function(vars) return vars["arg_name"] == "json" end| +|priority |option |Routing priority, default is 0.|priority = 100| +|metadata |option |Will return this field if using `rx:match` to match route.|| +|handler |option |Will call this function using `rx:dispatch` to match route.|| + +### Path + +#### Full path match + +```lua +local rx = radix.new({ + { + paths = {"/aa", "/bb/cc", "/dd/ee/index.html"}, + metadata = "metadata /aa", + }, + { + paths = {"/gg"}, + metadata = "metadata /gg", + }, + { + paths = {"/index.html"}, + metadata = "metadata /index.html", + }, +}) +``` + +Full path matching, allowing multiple paths to be specified at the same time. + +#### Prefix match + +```lua +local rx = radix.new({ + { + paths = {"/aa/*", "/bb/cc/*"}, + metadata = "metadata /aa", + }, + { + paths = {"/gg/*"}, + metadata = "metadata /gg", + }, +}) +``` + +Path prefix matching, allowing multiple paths to be specified at the same time. + +#### Parameters in path + +```lua +local rx = radix.new({ + { + -- This handler will match /user/john but will not match /user/ or /user + paths = {"/user/:user"}, + metadata = "metadata /user", + }, + { + -- However, this one will match /user/john/ and also /user/john/send/data + paths = {"/user/:user/*action"}, + metadata = "metadata action", + }, +}) +``` + +### match + +`syntax: metadata = rx:match(path, opts)` + +* `path`: client request path. +* `opts`: a Lua table (optional). + * `method`: optional, method name of client request. + * `host`: optional, client request host. + * `remote_addr`: optional, client remote address like `192.168.1.100`. + * `paths`: optional, a list of client request path. + * `vars`: optional, a Lua table to fetch variable, default value is `ngx.var` to fetch Ningx builtin variable. + +Matchs the route by `method`, `path` and `host` etc, and return `metadata` if successful. + +```lua +local metadata = rx:match(ngx.var.uri, {...}) +``` + +[Back to TOC](#table-of-contents) + +### dispatch + +`syntax: ok = rx:dispatch(path, opts, ...)` + +* `path`: client request path. +* `opts`: a Lua table (optional). + * `method`: optional, method name of client request. + * `host`: optional, client request host. + * `remote_addr`: optional, client remote address like `192.168.1.100`. + * `vars`: optional, a Lua table to fetch variable, default value is `ngx.var` to fetch Nginx builtin variable. + +Matchs the route by `method`, `path` and `host` etc, and call `handler` function if successful. + +```lua +local ok = rx:dispatch(ngx.var.uri, {...}) +``` + +[Back to TOC](#table-of-contents) + +## Install + +### Compile and install + +```shell +make install +``` + +[Back to TOC](#table-of-contents) + +## DEV ENV + +### Install Dependencies + +```shell +make deps +``` + +## Benchmark + +We wrote some simple benchmark scripts. +Machine environment: MacBook Pro (16-inch, 2019), CPU 2.3 GHz Intel Core i9. + +```shell +$ make +cc -O2 -g -Wall -fpic -std=c99 -Wno-pointer-to-int-cast -Wno-int-to-pointer-cast -DBUILDING_SO -c src/rax.c -o src/rax.o +cc -O2 -g -Wall -fpic -std=c99 -Wno-pointer-to-int-cast -Wno-int-to-pointer-cast -DBUILDING_SO -c src/easy_rax.c -o src/easy_rax.o +cc -shared -fvisibility=hidden src/rax.o src/easy_rax.o -o librestyradixtree.so + +$ make bench +resty -I=./lib -I=./deps/share/lua/5.1 benchmark/match-parameter.lua +matched res: 1 +route count: 100000 +match times: 10000000 +time used : 3.3849999904633 sec +QPS : 2954209 +each time : 0.33849999904633 ns + +resty -I=./lib -I=./deps/share/lua/5.1 benchmark/match-prefix.lua +matched res: 500 +route count: 100000 +match times: 1000000 +time used : 0.4229998588562 sec +QPS : 2364066 + +resty -I=./lib -I=./deps/share/lua/5.1 benchmark/match-static.lua +matched res: 500 +route count: 100000 +match times: 10000000 +time used : 0.78799986839294 sec +QPS : 12690357 + +resty -I=./lib -I=./deps/share/lua/5.1 benchmark/match-hosts.lua +matched res: 500 +route count: 1000 +match times: 100000 +time used : 1.6989998817444 sec +QPS : 58858 + +resty -I=./lib -I=./deps/share/lua/5.1 benchmark/match-wildcard-hosts.lua +matched res: 500 +route count: 1000 +match times: 50000 +time used : 1.2469999790192 sec +QPS : 40096 +``` + +[Back to TOC](#table-of-contents) diff --git a/deps/lib64/luarocks/rocks/lua-resty-radixtree/2.5-0/doc/licenses b/deps/lib64/luarocks/rocks/lua-resty-radixtree/2.5-0/doc/licenses new file mode 100644 index 0000000..e69de29 diff --git a/deps/lib64/luarocks/rocks/lua-resty-radixtree/2.5-0/lua-resty-radixtree-2.5-0.rockspec b/deps/lib64/luarocks/rocks/lua-resty-radixtree/2.5-0/lua-resty-radixtree-2.5-0.rockspec new file mode 100644 index 0000000..612bdfa --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-radixtree/2.5-0/lua-resty-radixtree-2.5-0.rockspec @@ -0,0 +1,37 @@ +package = "lua-resty-radixtree" +version = "2.5-0" +source = { + url = "git://github.com/api7/lua-resty-radixtree", + tag = "v2.5", +} + +description = { + summary = "Adaptive Radix Trees implemented in Lua for Nginx + Lua", + homepage = "https://github.com/api7/lua-resty-radixtree", + license = "Apache License 2.0", + maintainer = "Yuansheng Wang " +} + +dependencies = { + "lua-resty-ipmatcher", + "lua-resty-expr = 1.0.0", +} + +build = { + type = "make", + build_variables = { + CFLAGS="$(CFLAGS) -std=c99 -g -Wno-pointer-to-int-cast -Wno-int-to-pointer-cast", + LIBFLAG="$(LIBFLAG)", + LUA_LIBDIR="$(LUA_LIBDIR)", + LUA_BINDIR="$(LUA_BINDIR)", + LUA_INCDIR="$(LUA_INCDIR)", + LUA="$(LUA)", + }, + install_variables = { + INST_PREFIX="$(PREFIX)", + INST_BINDIR="$(BINDIR)", + INST_LIBDIR="$(LIBDIR)", + INST_LUADIR="$(LUADIR)", + INST_CONFDIR="$(CONFDIR)", + }, +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-radixtree/2.5-0/rock_manifest b/deps/lib64/luarocks/rocks/lua-resty-radixtree/2.5-0/rock_manifest new file mode 100644 index 0000000..6930963 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-radixtree/2.5-0/rock_manifest @@ -0,0 +1,16 @@ +rock_manifest = { + doc = { + LICENSE = "c37474feeec430e9e82d46017bca3f61", + ["README.md"] = "9d802cff70a748ab18731c99fee6b8b1", + licenses = "d41d8cd98f00b204e9800998ecf8427e" + }, + lib = { + ["librestyradixtree.so"] = "c99da51aea250e4463f3e3183f1be421" + }, + lua = { + resty = { + ["radixtree.lua"] = "af55fbacc6f86a1b2c02cdfebe6b8b72" + } + }, + ["lua-resty-radixtree-2.5-0.rockspec"] = "3d46127bd9a88bb953172f69da08ae76" +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-session/2.24-1/doc/Changes.md b/deps/lib64/luarocks/rocks/lua-resty-session/2.24-1/doc/Changes.md new file mode 100644 index 0000000..057d857 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-session/2.24-1/doc/Changes.md @@ -0,0 +1,274 @@ +# Changelog + +All notable changes to `lua-resty-session` will be documented in this file. + +## [2.24] - Upcoming +### Fixed +- Avoid use unix socket and redis password with empty string +- Provide session id when closing, otherwise the lock is not deleted + +### Added +- Added a configuration for session cookie max size (`session.cookie.maxsize`) + +## [2.23] - 2018-12-12 +### Added +- Added pluggable strategies with `default` and a new `regenerate` strategy +- Added pluggable `hmac`s +- Added `session.close` +- Added `ttl` to `storages` +- Added `session.cookie.discard`, a `ttl` how long to keep old sessions when + renewing (used by `regenerate` strategy + +## [2.22] - 2018-03-17 +### Fixed +- Only sets self.cookie.secure if not defined. + +## [2.21] - 2018-03-16 +### Screwed +- Forgot to bump version number. + +## [2.20] - 2018-03-16 +### Fixed +- Fixes issue where check addr and check scheme could be faked. + See also: https://github.com/bungle/lua-resty-session/issues/47 + Thanks @nielsole + +## [2.19] - 2017-09-19 +### Fixed +- Fixes small bug where aes could generate invalid salt on invalid input + that further crashes Lua with error: bad argument #2 to 'salt' (number + expected, got no value) + +## [2.18] - 2017-07-10 +### Fixed +- Automatically creates exactly 64 bits salt as required by the latest + lua-resty-string. + See also: https://github.com/bungle/lua-resty-session/issues/40 + Thanks @peturorri + +## [2.17] - 2017-06-12 +### Added +- Added session.hide() function to hide session cookies from upstream + on reverse proxy scenarios. + +## [2.16] - 2017-05-31 +### Changed +- Delays setting the defaults until needed, allowing users to safely + require "resty.session" in different contexts. + +## [2.15] - 2017-02-13 +## Added +- Added a support for chunked cookies. + See also: https://github.com/bungle/lua-resty-session/issues/35 + Thanks @zandbelt + +## [2.14] - 2016-12-16 +### Fixed +- Lua code configuration parsing corrections (especially on boolean + options). + +## Added +- Added a more natural way to pass config arguments to storage + adapters and ciphers in Lua code. + See also: https://github.com/bungle/lua-resty-session/issues/34 + Thanks @hanxi + +## [2.13] - 2016-11-21 +### Changed +- On start we do send cookie now also if the settings have changed + and the cookie expiry time needs to be reduced. + +### Fixed +- Memcache storage adapter had a missing ngx.null. + +## [2.12] - 2016-11-21 +### Added +- Implemented pluggable session identifier generators. +- Implemented random session idenfier generator. + +### Changed +- Now checks if headers were already sent before trying to set the + cookie headers. +- SSL session identifier is not checked by default anymore. +- Lua session.identifier.length changed to session.random.length. +- Nginx $session_identifier_length changed to $session_random_length. + +## [2.11] - 2016-09-30 +### Changed +- Just another OPM release to correct the name. + +## [2.10] - 2016-09-29 +### Added +- Support for the official OpenResty package manager (opm). + +### Changed +- Changed the change log format to keep-a-changelog. + +## [2.9] - 2016-09-01 +### Fixed +- Bugfix: Weird bug where RAND_bytes was not working on Windows platform. + Code changed to use resty.random. See Also: + https://github.com/bungle/lua-resty-session/issues/31 + Thanks @gtuxyco + +## [2.8] - 2016-07-05 +### Fixed +- Bugfix: AES Cipher used a wrong table for cipher sizes. + See Also: https://github.com/bungle/lua-resty-session/issues/30 + Thanks @pronan + +## [2.7] - 2016-05-18 +### Added +- Redis storage adapter now supports Redis authentication. + See Also: https://github.com/bungle/lua-resty-session/pull/28 + Thanks @cheng5533062 + +## [2.6] - 2016-04-18 +### Changed +- Just cleanups and changed _VERSION to point correct version. + +## [2.5] - 2016-04-18 +### Fixed +- session.save close argument was not defaulting to true. + +## [2.4] - 2016-04-17 +### Added +- Cookie will now have SameSite attribute set as "Lax" by default. + You can turn it off or set to "Strict" by configuration. + +### Changed +- Calling save will now also set session.id if the save was called + without calling start first. + See Also: https://github.com/bungle/lua-resty-session/issues/27 + Thanks @hcaihao + +## [2.3] - 2015-10-16 +### Fixed +- Fixes issue #19 where regenerating session would throw an error + when using cookie storage. + See Also: https://github.com/bungle/lua-resty-session/issues/19 + Thanks @hulu1522 + +## [2.2] - 2015-09-17 +### Changed +- Removed all session_cipher_* deprecated settings (it was somewhat + broken in 2.1). +- Changed session secret to be by default 32 bytes random data + See Also: https://github.com/bungle/lua-resty-session/issues/18 + Thanks @iain-buclaw-sociomantic + +### Added +- Added documentation about removed features and corrected about + session secret size accordingly. + +## [2.1] - 2015-09-07 +### Added +- Added architecture for Cipher adapter plugins. + See Also: https://github.com/bungle/lua-resty-session/issues/16 + Thanks @mingfang +- Implemented AES cipher adapter (just like it was before) +- Implemented None cipher adapter (no encryption) +- Added documentation about pluggable ciphers + +### Changed +- Changed JSON serializer to use cjson.safe instead + +## [2.0] - 2015-08-31 +### Added +- Added architecture for Storage adapter plugins. + See Also: https://github.com/bungle/lua-resty-session/issues/13 +- Implemented Client Side Cookie storage adapter. +- Implemented Memcache storage adapter. + See Also: https://github.com/bungle/lua-resty-session/pull/14 + Thanks @zandbelt +- Implemented Redis storage adapter. +- Implemented Shared Dictionary (shm) storage adapter. +- Added architecture for Encoder and Decoder plugins. +- Implemented Base 64 encoder / decoder. +- Implemented Base 16 (hex) encoder / decoder. +- Added architecture for Serializer plugins +- Implemented JSON serializer. +- Persistent cookies will now also contain Max-Age in addition to Expires. +- Cookie domain attribute is not set anymore if not specified. +- Added notes about using lua-resty-session with Lua code cache turned off. + See also: https://github.com/bungle/lua-resty-session/issues/15 + Thanks @BizShuk + +## [1.7] - 2015-08-03 +### Added +- Added session.open() function that only opens a session but doesn't send + the cookie (until start is called). + See also: https://github.com/bungle/lua-resty-session/issues/12 + Thanks @junhanamaki + +### Fixed +- Fixed cookie expiration time format on Firefox bug: + https://github.com/bungle/lua-resty-session/pull/10 + Thanks @junhanamaki +- Bugfix: Fixed an issue of overwriting a variable: + https://github.com/bungle/lua-resty-session/pull/11 + Thanks @junhanamaki + +## [1.6] - 2015-05-05 +### Fixed +- Fixed truncated cookie value bug: + https://github.com/bungle/lua-resty-session/pull/8 + Thanks @kipras + +## [1.5] - 2014-11-27 +### Fixed +- Cookies are not always "secure": + https://github.com/bungle/lua-resty-session/issues/5 + Thanks @vladimir-smirnov-sociomantic + +### Added +- Added documentation about Nginx SSL/TLS configuration settings related + to session lifetime and ssl session ids. + + +## [1.4] - 2014-11-26 +### Fixed +- Bugfix: Fixed an issue where session configurations did get cached + on a module level. This issue is discussed in pull-request #4: + https://github.com/bungle/lua-resty-session/pull/4 + Thanks @kipras. + +### Added +- Added session.new function. +- Added documentation about Nginx configuration used as defaults (not read + on every request), and documented session.new. + +### Changed +- session.start{ ... } (a call with config parameters) works now as expected. +- session.start now returns additional extra boolean parameter that can be + used to check if the session is s new session (false) or a previously + started one (true). + +## [1.3] - 2014-11-14 +### Added +- Added support for persistent sessions. See issue #2. +- Added session.check.ssi, session.cookie.persistent and the related Nginx + configuration variables. +- Added Max-Age=0 to expiration code. + +## [1.2] - 2014-10-12 +### Fixed +- Changed encode and decode functions to operate with correct number of + arguments. See issue #1. + +## [1.1] - 2014-10-03 +### Security +- There was a bug where additional user agent, scheme, and remote addr + (disabled by default) was not checked. + +### Added +- Added _VERSION field. + +### Changed +- Simplied a code a lot (e.g. internal setcookie and getcookie functions are + now cleaner). Removed a lot of unneccessary lines from session.start by + adding configs directly to session prototype. + +## [1.0] - 2014-09-24 +### Added +- LuaRocks Support via MoonRocks. diff --git a/deps/lib64/luarocks/rocks/lua-resty-session/2.24-1/doc/LICENSE b/deps/lib64/luarocks/rocks/lua-resty-session/2.24-1/doc/LICENSE new file mode 100644 index 0000000..b1adba4 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-session/2.24-1/doc/LICENSE @@ -0,0 +1,23 @@ +Copyright (c) 2014 – 2017, Aapo Talvensaari +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. \ No newline at end of file diff --git a/deps/lib64/luarocks/rocks/lua-resty-session/2.24-1/doc/README.md b/deps/lib64/luarocks/rocks/lua-resty-session/2.24-1/doc/README.md new file mode 100644 index 0000000..689a3d6 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-session/2.24-1/doc/README.md @@ -0,0 +1,1049 @@ +# lua-resty-session + +**lua-resty-session** is a secure, and flexible session library for OpenResty. + +## Hello World with lua-resty-session + +```nginx +worker_processes 1; + +events { + worker_connections 1024; +} + +http { + server { + listen 8080; + server_name localhost; + default_type text/html; + location / { + content_by_lua ' + ngx.say("Start the test!") + '; + } + location /start { + content_by_lua ' + local session = require "resty.session".start() + session.data.name = "OpenResty Fan" + session:save() + ngx.say("Session started. ", + "Check if it is working!") + '; + } + location /test { + content_by_lua ' + local session = require "resty.session".open() + ngx.say("Session was started by ", + session.data.name or "Anonymous", + "! Destroy the session.") + '; + } + location /destroy { + content_by_lua ' + local session = require "resty.session".start() + session:destroy() + ngx.say("Session was destroyed. ", + "Is it really so?") + '; + } + location /check { + content_by_lua ' + local session = require "resty.session".open() + ngx.say("Session was really destroyed, you are known as ", + "", + session.data.name or "Anonymous", + "! Start again.") + '; + } + } +} +``` + +## Roadmap + +* Add support for different schemes: + * Encrypt-and-MAC: The ciphertext is generated by encrypting the plaintext and then appending a MAC of the plaintext. + * MAC-then-encrypt: The ciphertext is generated by appending a MAC to the plaintext and then encrypting everything. + * Encrypt-then-MAC: The ciphertext is generated by encrypting the plaintext and then appending a MAC of the encrypted plaintext. + * Authenticated Encryption with Associated Data (AEAD) +* Add support for HMAC plugins +* Add support for `lua-resty-nettle` for more wide variety of encryption algorithms as a plugin. +* Implement cookieless server-side session support using `ssl_session_id` as a `session.id` (using a server-side storage). + +## Installation + +Just place [`session.lua`](https://github.com/bungle/lua-resty-session/blob/master/lib/resty/session.lua) and [`session`](https://github.com/bungle/lua-resty-session/tree/master/lib/resty/session) directory somewhere in your `package.path`, under `resty` directory. If you are using OpenResty, the default location would be `/usr/local/openresty/lualib/resty`. + +### Using OpenResty Package Manager (opm) + +```Shell +$ opm get bungle/lua-resty-session +``` + +### Using LuaRocks + +```Shell +$ luarocks install lua-resty-session +``` + +LuaRocks repository for `lua-resty-session` is located at https://luarocks.org/modules/bungle/lua-resty-session. + +## About The Defaults + +`lua-resty-session` does by default set session only cookies (non-persistent, and `HttpOnly`) so that +the cookies are not readable from Javascript (not subjectible to XSS in that matter). It will also set +`Secure` flag by default when the request was made via SSL/TLS connection. Cookies send via SSL/TLS +don't work when sent via HTTP and vice-versa (unless the checks are disabled). By default the HMAC key +is generated from session id (random bytes generated with OpenSSL), expiration time, unencrypted +data, and Nginx variables `ssl_session_id` (if requested with TLS/SSL), `http_user_agent` and `scheme`. +You may also configure it to use `remote_addr` as well by setting `set $session_check_addr on;` +(but this may be problematic with clients behind proxies or NATs that change the remote address +between requests). + +The data part is encrypted with AES-algorithm (by default it uses OpenSSL `EVP_aes_256_cbc` and +`EVP_sha512` functions that are provided with `lua-resty-string`. They come pre-installed with +the default OpenResty bundle. The `lua-resty-session` library is not tested with all the +`resty.aes` functions (but the defaults are tested to be working). Please let me know or contact +`lua-resty-string` project if you hit any problems with different algorithms. We also support +pluggable cipher adapters. You can also disable encryption by choosing `none` adapter. + +Session identifier length is by default 16 bytes (randomly generated data with OpenSSL +`RAND_bytes` function). The server secret is also generated by default with this same +function and it's default length is 32 bytes. This will work until Nginx is restarted, but you +might want to consider setting your own secret using `set $session_secret 623q4hR325t36VsCD3g567922IC0073T;`, +for example (this will work in farms installations as well, but you are then responsible for +rotating the secret). On farm installations you should also configure other session configuration +variables the same on all the servers in the farm. + +Cookie parts are encoded with cookie safe Base64 encoding (we also support pluggable encoders). +Before encrypting and encoding the data part, the data is serialized with JSON encoding (so you can +use basic Lua types in data, and expect to receive them back as the same Lua types). JSON encoding +is done by the bundled OpenResty cJSON library (Lua cJSON). We do support pluggable serializers as +well, though only serializer currently supplied is JSON. Cookie's path scope is by default `/` +(meaning that it will be send to all paths in the server. The domain scope is not set by default, +and it means that the cookie will only be sent back to same domain where it originated. + +For session data we do support pluggable storage adapters. The default adapter is `cookie` that +stores data to client-side cookie. Currently we do also support a few server side storages: `shm` +(aka a shared dictionary), `memcache`, and `redis`. + +## Notes About Turning Lua Code Cache Off + +In issue ([#15](https://github.com/bungle/lua-resty-session/issues/15)) it was raised that there may +be problems of using `lua-resty-session` when the `lua_code_cache` setting has been turned off. + +Nginx: + +```nginx +lua_code_cache off; +``` + +The problem is caused by the fact that by default we do generate session secret automatically with +a random generator (on first use of the library). If the code cache is turned off, we regenerate +the secret on each request. That will invalidate the cookies aka making sessions non-functioning. +The cure for this problem is to define the secret in Nginx or in Lua code (it is a good idea to +always have session secret defined). + +Nginx: + +```nginx +set $session_secret 623q4hR325t36VsCD3g567922IC0073T; +``` + +Lua: + +```lua +local session = require "resty.session".start{ secret = "623q4hR325t36VsCD3g567922IC0073T" } +-- or +local session = require "resty.session".new() +session.secret = "623q4hR325t36VsCD3g567922IC0073T" +``` + + +## Pluggable Session Strategies + +Strategies can be a bit cumbersome to do with just configuration, and that's why you can +implement them with the code. Currently `lua-resty-session` comes with two strategies: + +* `default` — the default strategy (original implementation) +* `regenerate` — similar to default strategy, but does not use `expires` with `HMAC` + functions, and instead generates a new session identifier on each `save`. + +The `default` one has been here from the beginning, but recently I got information about +use case of Javascript application with parallel asynchronous queries, where the session +was saved to a database with a custom storage adapter using `header_filter` phase, which resulted +the need to use the asynchronous `ngx.timer`. And that resulted that the JS XHR requests may +have sent an old cookie, or perhaps a new cookie that was not yet found in db because of async +timer. This resulted issues because cryptographic functions in `default` strategy used `expires`, +and every time you saved a cookie it got a new `expiry`. The `regenerate` adapter does not use +`expiry` anymore, but it instead generates a new `session id` on each `save` call. This makes +a new row in a database while the previous `session` will still function. If your storage adapter +implements `ttl` the `regenerate` strategy will call that with the old id and `10` seconds +of `ttl`. `default` strategy is still adequate if you use `cookie` storage adapter as that +is not issue with it, but if using server side storage adapter like `redis` or `memcache` +you may want to consider using `regenerate` if you have a heavily JS based application with +a lot of asynchronous queries at the same time. This issue happens usually when session +is about to be renewed, so it is quite rare even when using `default` strategy. + +Strategy can be selected with configuration (if no configuration is present, the `default` strategy is picked up): + +```nginx +set $session_strategy regenerate; +``` + +To implement a custom strategy, please checkout the existing ones. + +## Pluggable HMAC Algorithms + +If your strategy happens to be using `HMAC`, like the `default` and `regenerate` ones do, +you can tell them what `HMAC` algorithm to use. At the moment only `HMAC SHA1` is available +as that comes with OpenResty and works without additional dependencies. You may implement +your own custom HMAC algorithms (preferrably binding to some existing crypto library, +such as OpenSSL), and the strategies will pick up from there. + +HMAC can be selected with configuration (if no configuration is present, the `sha1` strategy is picked up): + +```nginx +set $session_hmac sha1; +``` + +## Pluggable Storage Adapters + +With version 2.0 we started to support pluggable session data storage adapters. We do currently have +support for these backends: + +* `cookie` aka Client Side Cookie (this is the default adapter) +* `shm` aka Lua Shared Dictionary +* `memcache` aka Memcached Storage Backend (thanks [@zandbelt](https://github.com/zandbelt)) +* `redis` aka Redis Backend + +Here are some comparisons about the backends: + +| | cookie | shm | memcache | redis | +| :---------------------------- | :----: | :--: | :------: | :---: | +| Stateless | ✓ | | | | +| Lockless | ✓ | ¹ | ¹ | ¹ | +| Works with Web Farms | ✓ | | ✓ | ✓ | +| Session Data Stored on Client | ✓ | | | | +| Zero Configuration | ✓ | | | | +| Extra Dependencies | | | ✓ | ✓ | +| Extra Security ² | | ✓ | ✓ | ✓ | + +¹ Can be configured lockless. + +² HMAC is stored on a client but the data is stored on a server. That means that you are unable to edit + cookie if you cannot edit server side storage as well, and vice-versa. + +The storage adapter can be selected from Nginx config like this: + +```nginx +set $session_storage shm; +``` + +Or with Lua code like this: + +```lua +local session = require "resty.session".new() +-- After new you cannot specify storage as a string, you need to give actual implementation +session.storage = require "resty.session.storage.shm" +-- or +local session = require "resty.session".new({ storage = "shm" }) +``` + +#### Cookie Storage Adapter + +Cookie storage adapter is the default adapter that is used if storage adapter has not been configured. Cookie +adapter does not have any settings. + +Cookie adapter can be selected with configuration (if no configuration is present, the cookie adapter is picked up): + +```nginx +set $session_storage cookie; +``` + +**NOTE:** + +If you store large amounts of data in a cookie, this library will automatically split the cookies to 4k chars chunks. With large cookies, you may need to adjust your Nginx configuration to accept large client header buffers. E.g.: + +```nginx +large_client_header_buffers 4 16k; +``` + +#### Shared Dictionary Storage Adapter + +Shared dictionary uses OpenResty shared dictionary and works with multiple worker processes, but it isn't a good +choice if you want to run multiple separate frontends. It is relatively easy to configure and has some added +benefits on security side compared to `cookie`, although the normal cookie adapter is quite secure as well. +For locking the `shm` adapter uses `lua-resty-lock`. + +Shared dictionary adapter can be selected with configuration: + +```nginx +set $session_storage shm; +``` + +But for this to work, you will also need a storage configured for that: + +```nginx +http { + lua_shared_dict sessions 10m; +} +``` + +Additionally you can configure the locking and some other things as well: + +```nginx +set $session_shm_store sessions; +set $session_shm_uselocking on; +set $session_shm_lock_exptime 30; +set $session_shm_lock_timeout 5; +set $session_shm_lock_step 0.001; +set $session_shm_lock_ratio 2; +set $session_shm_lock_max_step 0.5; +``` + +The keys stored in shared dictionary are in form: + +`{session id}` and `{session id}.lock`. + + +#### Memcache Storage Adapter + +Memcache storage adapter stores the session data inside Memcached server. +It is scalable and works with web farms. + +Memcache adapter can be selected with configuration: + +```nginx +set $session_storage memcache; +``` + +Additionally you can configure Memcache adapter with these settings: + +```nginx +set $session_memcache_prefix sessions; +set $session_memcache_socket unix:///var/run/memcached/memcached.sock; +set $session_memcache_host 127.0.0.1; +set $session_memcache_port 11211; +set $session_memcache_uselocking on; +set $session_memcache_spinlockwait 10000; +set $session_memcache_maxlockwait 30; +set $session_memcache_pool_timeout 45; +set $session_memcache_pool_size 10; +``` + +The keys stored in Memcached are in form: + +`{prefix}:{session id}` and `{prefix}:{session id}.lock`. + +#### Redis Storage Adapter + +Redis storage adapter stores the session data inside Redis server. +It is scalable and works with web farms. + +Redis adapter can be selected with configuration: + +```nginx +set $session_storage redis; +``` + +Additionally you can configure Redis adapter with these settings: + +```nginx +set $session_redis_prefix sessions; +set $session_redis_socket unix:///var/run/redis/redis.sock; +set $session_redis_host 127.0.0.1; +set $session_redis_port 6379; +set $session_redis_auth password; +set $session_redis_uselocking on; +set $session_redis_spinlockwait 10000; +set $session_redis_maxlockwait 30; +set $session_redis_pool_timeout 45; +set $session_redis_pool_size 10; +``` + +The keys stored in Redis are in form: + +`{prefix}:{session id}` and `{prefix}:{session id}.lock`. + +#### Implementing a Storage Adapter + +It is possible to implement additional storage adapters using the plugin architecture in `lua-resty-session`. + +You need to implement at least these APIs: + +* `table adapter.new(opts)` +* `id, expires, data, hmac adapter:open(cookie, lifetime)` +* `cookie adapter:save(id, expires, data, hmac)` + +There are a few additional hooks that you may want to attach: + +* `ok, error adapter:start(id)` +* `ok, error adapter:close(id)` +* `ok, error adapter:destroy(id)` +* `ok, error adapter:ttl(id, ttl)` + +You have to place your adapter inside `resty.session.storage` for auto-loader to work. + +To configure session to use your adapter, you can do so with Nginx configuration (or in Lua code): + +```nginx +# Just an example. Pull request for MySQL support are greatly welcomed. +set $session_storage mysql; +``` + +## Pluggable Ciphers + +With version 2.1 we started to support pluggable ciphers. We currently have support for these ciphers: + +* `aes` aka AES encryption / decryption using `lua-resty-string`'s AES library (the default). +* `none` aka no encryption or decryption is done. + +The cipher adapter can be selected from Nginx config like this: + +```nginx +set $session_cipher aes; +``` + +Or with Lua code like this: + +```lua +local session = require "resty.session".start{ cipher = "aes" } +``` + +#### AES Cipher + +AES Cipher uses `lua-resty-string`'s (an OpenResty core library) AES implementation +(bindings to OpenSSL) for encryption. + +AES adapter can be selected with configuration: + +```nginx +set $session_cipher aes; +``` + +Additionally you can configure Memcache adapter with these settings: + +```nginx +set $session_aes_size 256; +set $session_aes_mode "cbc"; +set $session_aes_hash "sha512"; +set $session_aes_rounds 1; +``` + +Here follows the description of each setting: + +**size** + +`session.aes.size` holds the size of the cipher (`lua-resty-string` supports AES in `128`, `192`, +and `256` bits key sizes). See `aes.cipher` function in `lua-resty-string` for more information. +By default this will use `256` bits key size. This can be configured with Nginx +`set $session_aes_size 256;`. + +**mode** + +`session.aes.mode` holds the mode of the cipher. `lua-resty-string` supports AES in `ecb`, `cbc`, +`cfb1`, `cfb8`, `cfb128`, `ofb`, and `ctr` modes (ctr mode is not available with 256 bit keys). +See `aes.cipher` function in `lua-resty-string` for more information. By default `cbc` mode is +used. This can be configured with Nginx `set $session_aes_mode cbc;`. + +**hash** + +`session.aes.hash` is used in ecryption key, and iv derivation (see: OpenSSL +[EVP_BytesToKey](https://www.openssl.org/docs/crypto/EVP_BytesToKey.html)). By default `sha512` is +used but `md5`, `sha1`, `sha224`, `sha256`, and `sha384` are supported as well in `lua-resty-string`. +This can be configured with Nginx `set $session_aes_hash sha512;`. + +**rounds** + +`session.aes.rounds` can be used to slow-down the encryption key, and iv derivation. By default +this is set to `1` (the fastest). This can be configured with Nginx `set $session_aes_rounds 1;`. + +#### None Cipher + +None cipher disables encryption of the session data. This can be handy if you want to +debug things or want you session management as light as possible, or perhaps share the +session data with some other process without having to deal with encryption key management. +In general it is better to have encryption enabled in a production. + +None adapter can be selected with configuration: + +```nginx +set $session_cipher none; +``` + +There isn't any settings for None adapter as it is basically a no-op adapter. + +#### Implementing a Cipher Adapter + +If you want to write your own cipher adapter, you need to implement these three methods: + +* `table adapter.new(opts)` +* `string adapter:encrypt(data, key, iv or salt, associated data)` +* `string adapter:decrypt(ciphertext, key, iv or salt, associated data)` + +If you do not use say iv or associated data in your cipher, you can ignore them. + +You have to place your adapter inside `resty.session.ciphers` for auto-loader to work. + +## Pluggable Serializers + +Currently we only support JSON serializer, but there is a plugin architecture that you can use to +plugin your own serializer. The serializer is used to serialize session data in a form that can be +later deserialized and stored in some of our supported storages. + +The supported serializer names are: + +* `json` + +You need only to implement two functions to write an adapter: + +* `string adapter.serialize(table)` +* `table adapter.deserialize(string)` + +You have to place your adapter inside `resty.session.serializers` for auto-loader to work. + +To configure session to use your adapter, you can do so with Nginx configuration (or in Lua code): + +```nginx +set $session_serializer json; +``` + +## Pluggable Encoders + +Cookie data needs to be encoded in cookie form before it is send to client. We support +two encoding methods by default: modified cookie friendly base-64, and base-16 (or hexadecimal encoding). + +The supported encoder names are: + +* `base64` +* `base16` or `hex` + +If you want to write your own encoder, you need to implement these two methods: + +* `string adapter.encode(string)` +* `string adapter.decode(string)` + +You have to place your adapter inside `resty.session.encoders` for auto-loader to work. + +To configure session to use your adapter, you can do so with Nginx configuration (or in Lua code): + +```nginx +set $session_encoder base64; +``` + +## Pluggable Session Identifier Generators + +With version 2.12 we started to support pluggable session identifier generators in `lua-resty-session`. +Right now we support only one type of generator, and that is: + +* `random` + +If you want to write your own session identifier generator, you need to implement one function: + +* `string function(config)` + +(the `config` is actually a `session` instance) + +You have to place your generator inside `resty.session.identifiers` for auto-loader to work. + +To configure session to use your generator, you can do so with Nginx configuration (or in Lua code): + +```nginx +set $session_identifier_generator random; +``` + +#### Random Sesssion Identifier Generator + +Random generator uses `lua-resty-string`'s (an OpenResty core library) OpenSSL based cryptographically +safe random generator. + +Random generator can be selected with configuration: + +```nginx +set $session_identifier random; +``` + +Additionally you can configure Random generator with these settings: + +```nginx +set $session_random_length 16; +``` + +Here follows the description of each setting: + +**length** + +`session.random.length` holds the length of the `session.id`. By default it is 16 bytes. +This can be configured with Nginx `set $session_random_length 16;`. + +## Lua API + +### Functions and Methods + +#### table session.new(opts or nil) + +With this function you can create a new session table (i.e. the actual session instance). This allows +you to generate session table first, and set invidual configuration before calling `session:open()` or +`session:start()`. You can also pass in `opts` Lua `table` with the configurations. + +```lua +local session = require "resty.session".new() +-- set the configuration parameters before calling start +session.cookie.domain = ".mydomain.com" +-- call start before setting session.data parameters +session:start() +session.data.uid = 1 +-- save session and update the cookie to be sent to the client +session:save() +``` + +This is equivalent to this: + +```lua +local session = require "resty.session".new{ cookie = { domain = ".mydomain.com" } } +session:start() +session.data.uid = 1 +session:save() +``` + +As well as with this: + +```lua +local session = require "resty.session".start{ cookie = { domain = ".mydomain.com" } } +session.data.uid = 1 +session:save() +``` + +#### table, boolean session.open(opts or nil) + +With this function you can open a new session. It will create a new session Lua `table` on each call (unless called with +colon `:` as in examples above with `session.new`). Calling this function repeatedly will be a no-op when using colon `:`. +This function will return a (new) session `table` as a result. If the session cookie is supplied with user's HTTP(S) +client then this function validates the supplied session cookie. If validation is successful, the user supplied session +data will be used (if not, a new session is generated with empty data). You may supply optional session configuration +variables with `opts` argument, but be aware that many of these will only have effect if the session is a fresh session +(i.e. not loaded from user supplied cookie). The second `boolean` return argument will be `true` if the user +client send a valid cookie (meaning that session was already started on some earlier request), and `false` if the +new session was created (either because user client didn't send a cookie or that the cookie was not a valid one). This +function will not set a client cookie. You need to call `session:start()` to really start the session. This open function +is mainly used if you only want to read data and avoid automatically sending a cookie (see also issue +[#12](https://github.com/bungle/lua-resty-session/issues/12)). But be aware that this doesn't update cookie +expiration time stored in a cookie. + +```lua +local session = require "resty.session".open() +-- Set some options (overwriting the defaults or nginx configuration variables) +local session = require "resty.session".open{ random = { length = 32 }} +-- Read some data +if session.present then + ngx.print(session.data.uid) +end +-- Now let's really start the session +-- (session.started will be always false in this example): +if not session.started then + session:start() +end +session.data.greeting = "Hello, World!" +session:save() +``` + +#### table, boolean session.start(opts or nil) + +With this function you can start a new session. It will create a new session Lua `table` on each call (unless called with +colon `:` as in examples above with `session.new`). Right now you should only start session once per request as calling +this function repeatedly will overwrite the previously started session cookie and session data. This function will return +a (new) session `table` as a result. If the session cookie is supplied with user's HTTP(S) client then this function +validates the supplied session cookie. If validation is successful, the user supplied session data will be used +(if not, a new session is generated with empty data). You may supply optional session configuration variables +with `opts` argument, but be aware that many of these will only have effect if the session is a fresh session +(i.e. not loaded from user supplied cookie). This function does also manage session cookie renewing configured +with `$session_cookie_renew`. E.g. it will send a new cookie with a new expiration time if the following is +met `session.expires - now < session.cookie.renew or session.expires > now + session.cookie.lifetime`. The second +`boolean` return argument will be `true` if the user client send a valid cookie (meaning that session was already +started on some earlier request), and `false` if the new session was created (either because user client didn't send +a cookie or that the cookie was not a valid one). On error this will return nil and error message. + +```lua +local session = require "resty.session".start() +-- Set some options (overwriting the defaults or nginx configuration variables) +local session = require "resty.session".start{ random = { length = 32 }} +``` + +#### boolean, string session:regenerate(flush or nil) + +This function regenerates a session. It will generate a new session identifier (`session.id`) and optionally +flush the session data if `flush` argument evaluates `true`. It will automatically call `session:save` which +means that a new expires flag is set on the cookie, and the data is encrypted with the new parameters. With +client side sessions (`cookie` storage adapter) this overwrites the current cookie with a new one (but it +doesn't invalidate the old one as there is no state held on server side - invalidation actually happens when +the cookie's expiration time is not valid anymore). This function returns a boolean value if everything went +as planned. If not it will return error string as a second return value. + +```lua +local session = require "resty.session".start() +session:regenerate() +-- Flush the current data +session:regenerate(true) +``` + +#### boolean, string session:save([close = true]) + +This function saves the session and sends (not immediate though, as actual sending is handled by Nginx/OpenResty) +a new cookie to client (with a new expiration time and encrypted data). You need to call this function whenever +you want to save the changes made to `session.data` table. It is advised that you call this function only once +per request (no need to encrypt and set cookie many times). This function returns a boolean value if everything +went as planned. If not it will return error string as a second return value. Optionally you may pass `false` +to this method, if you don't want to close the session just yet, but just to save the data. + +```lua +local session = require "resty.session".start() +session.data.uid = 1 +session:save() +``` + +#### boolean, string session:close() + +This function is mainly usable with storages that implement `locking` as calling this with e.g. `cookie` storage +does not do anything else than set `session.closed` to `true`. + + +#### boolean session:destroy() + +This function will immediately set session data to empty table `{}`. It will also send a new cookie to +client with empty data and Expires flag `Expires=Thu, 01 Jan 1970 00:00:01 GMT` (meaning that the client +should remove the cookie, and not send it back again). This function returns a boolean value if everything went +as planned. + +```lua +local session = require "resty.session".start() +session:destroy() +``` + +#### session:hide() + +Sometimes, when you are using `lua-resty-session` in reverse proxy, you may want to hide the session +cookies from the upstream server. To do that you can call `session:hide()`. + +```lua +local session = require "resty.session".start() +session:hide() +``` + +### Fields + +#### string session.id + +`session.id` holds the current session id. By default it is 16 bytes long (raw binary bytes). +It is automatically generated. + +#### boolean session.present + +`session.present` can be used to check if the session that was opened with `session.open` or `session.start` +was really a one the was received from a client. If the session is a new one, this will be false. + +#### boolean session.opened + +`session.opened` can be used to check if the `session:open()` was called for the current session +object. + +#### boolean session.started + +`session.started` can be used to check if the `session:start()` was called for the current session +object. + +#### boolean session.destroyed + +`session.destroyed` can be used to check if the `session:destroy()` was called for the current session +object. It will also set `session.opened`, `session.started`, and `session.present` to false. + +#### boolean session.closed + +`session.closed` can be used to check if the `session:close()` was called for the current session +object. + +#### string session.key + +`session.key` holds the HMAC key. It is automatically generated. Nginx configuration like +`set $session_check_ssi on;`, `set $session_check_ua on;`, `set $session_check_scheme on;` and `set $session_check_addr on;` + will have effect on the generated key. + +#### table session.data + +`session.data` holds the data part of the session cookie. This is a Lua `table`. `session.data` +is the place where you store or retrieve session variables. When you want to save the data table, +you need to call `session:save` method. + +**Setting session variable:** + +```lua +local session = require "resty.session".start() +session.data.uid = 1 +session:save() +``` + +**Retrieving session variable (in other request):** + +```lua +local session = require "resty.session".open() +local uid = session.data.uid +``` + +#### number session.expires + +`session.expires` holds the expiration time of the session (expiration time will be generated when +`session:save` method is called). + +#### string session.secret + +`session.secret` holds the secret that is used in keyed HMAC generation. + +#### boolean session.cookie.persistent + +`session.cookie.persistent` is by default `false`. This means that cookies are not persisted between browser sessions +(i.e. they are deleted when the browser is closed). You can enable persistent sessions if you want to by setting this +to `true`. This can be configured with Nginx `set $session_cookie_persistent on;`. + +#### number session.cookie.discard + +`session.cookie.discard` holds the time in seconds how of long you want to keep old cookies alive when +using `regenerate` session strategy. This can be configured with Nginx `set $session_cookie_discard 10;` +(10 seconds is the default value). This works only with server side session storage adapters and when +using `regenerate` strategy (perhaps your custom strategy could utilize this too). + +#### number session.cookie.renew + +`session.cookie.renew` holds the minimun seconds until the cookie expires, and renews cookie automatically +(i.e. sends a new cookie with a new expiration time according to `session.cookie.lifetime`). This can be configured +with Nginx `set $session_cookie_renew 600;` (600 seconds is the default value). + +#### number session.cookie.lifetime + +`session.cookie.lifetime` holds the cookie lifetime in seconds in the future. By default this is set +to 3,600 seconds. This can be configured with Nginx `set $session_cookie_lifetime 3600;`. This does not +set cookie's expiration time on session only (by default) cookies, but it is used if the cookies are +configured persistent with `session.cookie.persistent == true`. See also notes about +[ssl_session_timeout](#nginx-configuration-variables). + +#### string session.cookie.path + +`session.cookie.path` holds the value of the cookie path scope. This is by default permissive `/`. You +may want to have a more specific scope if your application resides in different path (e.g. `/forums/`). +This can be configured with Nginx `set $session_cookie_path /forums/;`. + +#### string session.cookie.domain + +`session.cookie.domain` holds the value of the cookie domain. By default this is automatically set using +Nginx variable `host`. This can be configured with Nginx `set $session_cookie_domain openresty.org;`. +For `localhost` this is omitted. + +#### string session.cookie.samesite + +`session.cookie.samesite` holds the value of the cookie SameSite flag. By default we do use value of `Lax`. +The possible values are `Lax`, `Strict`, and `off`. Actually, setting this parameter anything else than +`Lax` or `Strict` will turn this off (but in general, you shouldn't do it). If you want better protection +against Cross Site Request Forgery (CSRF), set this to `Strict`. Default value of `Lax` gives you quite a +good protection against CSRF, but `Strict` goes even further. + +#### boolean session.cookie.secure + +`session.cookie.secure` holds the value of the cookie `Secure` flag. meaning that when set the client will +only send the cookie with encrypted TLS/SSL connection. By default the `Secure` flag is set on all the +cookies where the request was made through TLS/SSL connection. This can be configured and forced with +Nginx `set $session_cookie_secure on;`. + +#### boolean session.cookie.httponly + +`session.cookie.httponly` holds the value of the cookie `HttpOnly` flag. By default this is enabled, +and I cannot think of an situation where one would want to turn this off. By keeping this on you can +prevent your session cookies access from Javascript and give some safety of XSS attacks. If you really +want to turn this off, this can be configured with Nginx `set $session_cookie_httponly off;`. + +#### string session.cookie.delimiter + +`session.cookie.delimiter` is used to configure how the different parts of the data stored in a cookie are +delimited. By default it is a pipe character, `|`. It is up to storage adapter to decide if this configuration +parameter is used. + +#### string session.cookie.maxsize + +`session.cookie.maxsize` is used to configure maximum size of a single cookie. This value is used to split a +large cookie into chunks. By default it is `4000` bytes of serialized and encoded data which does not count +the cookie name and cookie flags. If you expect your cookies + flags be more than e.g. `4096` bytes, you +should reduce the `session.cookie.maxsize` so that a single cookie fits into `4096` bytes because otherwise +the user-agent may ignore the cookie (being too big). + +#### number session.cookie.chunks + +`session.cookie.chunks` should be used as a read only property to determine how many separate cookies was +used for a session. Usually this is `1`, but if you are using a `cookie` storage backend and store a lot +of data in session, then the cookie is divided to `n` chunks where each stores data containing 4.000 bytes +(the last one 4000 or less). This was implemented in version 2.15. + +#### boolean session.check.ssi + +`session.check.ssi` is additional check to validate that the request was made with the same SSL +session as when the original cookie was delivered. This check is enabled by default on releases prior 2.12 +on non-persistent sessions and disabled by default on persistent sessions and on releases 2.12 and later. +Please note that on TLS with TLS Tickets enabled, this will be empty) and not used. This is discussed on issue #5 +(https://github.com/bungle/lua-resty-session/issues/5). You can disable TLS tickets with Nginx configuration: + +```nginx +ssl_session_tickets off; +``` + +#### boolean session.check.ua + +`session.check.ua` is additional check to validate that the request was made with the same user-agent browser string +as where the original cookie was delivered. This check is enabled by default. + +#### boolean session.check.addr + +`session.check.addr` is additional check to validate that the request was made from the same remote ip-address +as where the original cookie was delivered. This check is disabled by default. + +#### boolean session.check.scheme + +`session.check.scheme` is additional check to validate that the request was made using the same protocol +as the one used when the original cookie was delivered. This check is enabled by default. + +#### number session.cipher.size (deprecated in 2.1 and removed in 2.2, use session.aes.size) + +`session.cipher.size` holds the size of the cipher (`lua-resty-string` supports AES in `128`, `192`, +and `256` bits key sizes). See `aes.cipher` function in `lua-resty-string` for more information. +By default this will use `256` bits key size. This can be configured with Nginx +`set $session_cipher_size 256;`. + +#### string session.cipher.mode (deprecated in 2.1 and removed in 2.2, use session.aes.mode) + +`session.cipher.mode` holds the mode of the cipher. `lua-resty-string` supports AES in `ecb`, `cbc`, +`cfb1`, `cfb8`, `cfb128`, `ofb`, and `ctr` modes (ctr mode is not available with 256 bit keys). +See `aes.cipher` function in `lua-resty-string` for more information. By default `cbc` mode is +used. This can be configured with Nginx `set $session_cipher_mode cbc;`. + +#### function session.cipher.hash (deprecated in 2.1 and removed in 2.2, use session.aes.hash) + +`session.cipher.hash` is used in ecryption key, and iv derivation (see: OpenSSL +[EVP_BytesToKey](https://www.openssl.org/docs/crypto/EVP_BytesToKey.html)). By default `sha512` is +used but `md5`, `sha1`, `sha224`, `sha256`, and `sha384` are supported as well in `lua-resty-string`. +This can be configured with Nginx `set $session_cipher_hash sha512;`. + +#### number session.cipher.rounds (deprecated in 2.1 and removed in 2.2, use session.aes.rounds) + +`session.cipher.rounds` can be used to slow-down the encryption key, and iv derivation. By default +this is set to `1` (the fastest). This can be configured with Nginx `set $session_cipher_rounds 1;`. + + +## Nginx Configuration Variables + +You can set default configuration parameters directly from Nginx configuration. It's **IMPORTANT** to understand +that these are read only once (not on every request), for performance reasons. This is especially important if +you run multiple sites (with different configurations) on the same Nginx server. You can of course set the common +parameters on Nginx configuration even on that case. But if you are really supporting multiple site with different +configurations (e.g. different `session.secret` on each site), you should set these in code (see: `session.new` +and `session.start`). + +Please note that Nginx has also its own SSL/TLS caches and timeouts. Especially note `ssl_session_timeout` if you +are running services over SSL/TLS as this will end sessions regardless of `session.cookie.lifetime`. Please adjust +that accordingly or disable `ssl_session_id` check `session.check.ssi = false` (in code) or +`set $session_check_ssi off;` (in Nginx configuration). As of 2.12 checking SSL session identifier check +(`$session_check_ssi` / `session.check.ssi`) is disabled by default because it was not reliable (most servers use +session tickets now), and it usually needed extra configuration. + +You may want to add something like this to your Nginx SSL/TLS config (quite a huge cache in this example, 1 MB is +about 4.000 SSL sessions): + +```nginx +ssl_session_cache shared:SSL:100m; +ssl_session_timeout 60m; +``` + +Also note that the `ssl_session_id` may be `null` if the TLS tickets are enabled. You can disable tickets in Nginx +server with the configuration below: + +```nginx +ssl_session_tickets off; +``` + +Right now this is a workaround and may change in a future if we find alternative ways to have the added security +that we have with `ssl_session_id` with TLS tickets too. While TLS tickets are great, they also have effect on +(Perfect) Forward Secrecy, and it is adviced to disable tickets until the problems mentioned in +[The Sad State of Server-Side TLS Session Resumption Implementations](https://timtaubert.de/blog/2014/11/the-sad-state-of-server-side-tls-session-resumption-implementations/) +article are resolved. + +Here is a list of `lua-resty-session` related Nginx configuration variables that you can use to control +`lua-resty-session`: + +```nginx +set $session_name session; +set $session_secret 623q4hR325t36VsCD3g567922IC0073T; +set $session_strategy default; +set $session_storage cookie; +set $session_hmac sha1; +set $session_cipher aes; +set $session_encoder base64; +set $session_serializer json; +set $session_cookie_persistent off; +set $session_cookie_discard 10; +set $session_cookie_renew 600; +set $session_cookie_lifetime 3600; +set $session_cookie_path /; +set $session_cookie_domain openresty.org; +set $session_cookie_samesite Lax; +set $session_cookie_secure on; +set $session_cookie_httponly on; +set $session_cookie_delimiter |; +set $session_cookie_maxsize 4000; +set $session_check_ssi off; +set $session_check_ua on; +set $session_check_scheme on; +set $session_check_addr off; +set $session_random_length 16; +set $session_aes_mode cbc; +set $session_aes_size 256; +set $session_aes_hash sha512; +set $session_aes_rounds 1; +# this is removed in 2.12, use session_random_length instead: +set $session_identifier_length 16; +# these are deprecated in 2.1 and removed in 2.2, use session_aes_* instead: +set $session_cipher_mode cbc; +set $session_cipher_size 256; +set $session_cipher_hash sha512; +set $session_cipher_rounds 1; +``` + +## Changes + +The changes of every release of this module is recorded in [Changes.md](https://github.com/bungle/lua-resty-session/blob/master/Changes.md) file. + +## See Also + +* [lua-resty-route](https://github.com/bungle/lua-resty-route) — Routing library +* [lua-resty-reqargs](https://github.com/bungle/lua-resty-reqargs) — Request arguments parser +* [lua-resty-template](https://github.com/bungle/lua-resty-template) — Templating engine +* [lua-resty-validation](https://github.com/bungle/lua-resty-validation) — Validation and filtering library + +## License + +`lua-resty-session` uses two clause BSD license. + +``` +Copyright (c) 2014 – 2017 Aapo Talvensaari +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +``` diff --git a/deps/lib64/luarocks/rocks/lua-resty-session/2.24-1/lua-resty-session-2.24-1.rockspec b/deps/lib64/luarocks/rocks/lua-resty-session/2.24-1/lua-resty-session-2.24-1.rockspec new file mode 100644 index 0000000..c317a77 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-session/2.24-1/lua-resty-session-2.24-1.rockspec @@ -0,0 +1,37 @@ +package = "lua-resty-session" +version = "2.24-1" +source = { + url = "git://github.com/bungle/lua-resty-session.git", + branch = "v2.24" +} +description = { + summary = "Session Library for OpenResty – Flexible and Secure", + detailed = "lua-resty-session is a secure, and flexible session library for OpenResty.", + homepage = "https://github.com/bungle/lua-resty-session", + maintainer = "Aapo Talvensaari ", + license = "BSD" +} +dependencies = { + "lua >= 5.1" +} +build = { + type = "builtin", + modules = { + ["resty.session"] = "lib/resty/session.lua", + ["resty.session.identifiers.random"] = "lib/resty/session/identifiers/random.lua", + ["resty.session.storage.shm"] = "lib/resty/session/storage/shm.lua", + ["resty.session.storage.redis"] = "lib/resty/session/storage/redis.lua", + ["resty.session.storage.cookie"] = "lib/resty/session/storage/cookie.lua", + ["resty.session.storage.memcache"] = "lib/resty/session/storage/memcache.lua", + ["resty.session.storage.memcached"] = "lib/resty/session/storage/memcached.lua", + ["resty.session.strategies.default"] = "lib/resty/session/strategies/default.lua", + ["resty.session.strategies.regenerate"] = "lib/resty/session/strategies/regenerate.lua", + ["resty.session.hmac.sha1"] = "lib/resty/session/hmac/sha1.lua", + ["resty.session.ciphers.aes"] = "lib/resty/session/ciphers/aes.lua", + ["resty.session.ciphers.none"] = "lib/resty/session/ciphers/none.lua", + ["resty.session.encoders.hex"] = "lib/resty/session/encoders/hex.lua", + ["resty.session.encoders.base16"] = "lib/resty/session/encoders/base16.lua", + ["resty.session.encoders.base64"] = "lib/resty/session/encoders/base64.lua", + ["resty.session.serializers.json"] = "lib/resty/session/serializers/json.lua" + } +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-session/2.24-1/rock_manifest b/deps/lib64/luarocks/rocks/lua-resty-session/2.24-1/rock_manifest new file mode 100644 index 0000000..2096f3f --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-session/2.24-1/rock_manifest @@ -0,0 +1,44 @@ +rock_manifest = { + doc = { + ["Changes.md"] = "f1ad869564c4cec77781f01a4696304c", + LICENSE = "4f71bda345195e543728df9e0c0d250c", + ["README.md"] = "7502e5eefc791423b77d634df926d4ea" + }, + lua = { + resty = { + session = { + ciphers = { + ["aes.lua"] = "cbfb54972d4d1d184b5817da1efa7ccb", + ["none.lua"] = "eba726c88fe7b824ac1fe4f6106a202a" + }, + encoders = { + ["base16.lua"] = "f7d1b6ee813e1ebbc271305c44c1c5b1", + ["base64.lua"] = "a185fac1583c34db93e360674bf262a7", + ["hex.lua"] = "c2bd7f016fc20a18c653abcdc310a404" + }, + hmac = { + ["sha1.lua"] = "f7748bf92a057d46439ad60d5f5fb9f9" + }, + identifiers = { + ["random.lua"] = "b515920759395f9e0937cc6f0eb99997" + }, + serializers = { + ["json.lua"] = "f5abd0b1228f4c2b6be9c50e44559dda" + }, + storage = { + ["cookie.lua"] = "5ecb644a8118b4332b9b1ed8202b7be6", + ["memcache.lua"] = "c615a81ab92c2b8f39ce5b7623445789", + ["memcached.lua"] = "07c2fc41117dd550b15c6ef69e37815f", + ["redis.lua"] = "5009a548abe25a18bead2da96c4be962", + ["shm.lua"] = "1bd4a6277a767047c4a9c837bda653d9" + }, + strategies = { + ["default.lua"] = "457997ea43e0ef85eafac4b99f8125ea", + ["regenerate.lua"] = "407ccf954ef9be7db55b2860b9318ae4" + } + }, + ["session.lua"] = "169f5f1b63670e605522987339873343" + } + }, + ["lua-resty-session-2.24-1.rockspec"] = "40645ef75768e0a610cfbb8f07143d77" +} diff --git a/deps/lib64/luarocks/rocks/lua-resty-template/1.9-1/doc/Changes.md b/deps/lib64/luarocks/rocks/lua-resty-template/1.9-1/doc/Changes.md new file mode 100644 index 0000000..06f71ff --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-template/1.9-1/doc/Changes.md @@ -0,0 +1,72 @@ +# Change Log + +All notable changes to `lua-resty-validation` will be documented in this file. + +## [1.9] - 2016-09-29 +### Added +- Support for the official OpenResty package manager (opm). + +### Changed +- Changed the change log format to keep-a-changelog. + +## [1.8] - 2016-06-14 +### Added +- Allow pass layout as a template object to template.new. + +## [1.7] - 2016-05-11 +### Fixed +- The loadngx was not working properly on non-file input. + See also: https://github.com/bungle/lua-resty-template/pull/19 + Thanks @zhoukk + +## [1.6] - 2016-04-25 +### Added +- Added short escaping syntax. + +## [1.5] - 2015-02-10 +### Added +- Support for {-verbatim-}...{-verbatim-}, and {-raw-}...{-raw-} blocks + (contents is not processed by template). + Please note that this could break your templates if you have used + blocks with names "verbatim" or "raw". + +### Fixed +- Issue #8: not returning value when using template.new and its render + function. + +## [1.4] - 2014-12-03 +### Added +- Added support for {[expression include]} syntax. + +### Changed +- Rewrote template.parse (cleaned up, less repetition of code, and + better handling of new lines - i.e. doesn't eat newlines anymore. + Also some adjustments to preceding spaces (space, tab, NUL-byte, + and vertical tabs) on some tags ({% ... %}, {-block-} ... {-block-}, + and {# ... #}) for a cleaner output. + +## [1.3] - 2014-11-06 +### Added +- Small modification to html helper example to handle valueless tag + attributess in HTML5 style. + +### Fixed +- Fixed a bug when a view was missing from context when using layouts. + +## [1.2] - 2014-09-29 +### Fixed +- Fixes nasty recursion bug (reported in bug #5) where sub-templates + modify the context table. Thank you for reporting this @DDarko. + +## [1.1] - 2014-09-10 +### Added +- Added _VERSION information to the module. +- Added CHANGES file to the project (this file). + +### Changed +- Lua > 5.1 uses _ENV instead of _G (Lua 5.1 uses _G). Future Proofing + if Lua is deprecating _G in Lua 5.3. + +## [1.0] - 2014-08-28 +### Added +- LuaRocks Support via MoonRocks. diff --git a/deps/lib64/luarocks/rocks/lua-resty-template/1.9-1/doc/LICENSE b/deps/lib64/luarocks/rocks/lua-resty-template/1.9-1/doc/LICENSE new file mode 100644 index 0000000..b67bdac --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-template/1.9-1/doc/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2014 - 2016 Aapo Talvensaari +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + +* Neither the name of the {organization} nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. diff --git a/deps/lib64/luarocks/rocks/lua-resty-template/1.9-1/doc/README.md b/deps/lib64/luarocks/rocks/lua-resty-template/1.9-1/doc/README.md new file mode 100644 index 0000000..f4c2c20 --- /dev/null +++ b/deps/lib64/luarocks/rocks/lua-resty-template/1.9-1/doc/README.md @@ -0,0 +1,1453 @@ +# lua-resty-template + +**lua-resty-template** is a compiling (1) (HTML) templating engine for Lua and OpenResty. + +(1) with compilation we mean that templates are translated to Lua functions that you may call or `string.dump` as a binary bytecode blobs to disk that can be later utilized with `lua-resty-template` or basic `load` and `loadfile` standard Lua functions (see also [Template Precompilation](#template-precompilation)). Although, generally you don't need to do that as `lua-resty-template` handles this behind the scenes. + +## Hello World with lua-resty-template + +```lua +local template = require "resty.template" +-- Using template.new +local view = template.new "view.html" +view.message = "Hello, World!" +view:render() +-- Using template.render +template.render("view.html", { message = "Hello, World!" })G +``` + +##### view.html +```html + + + +

{{message}}

+ + +``` + +##### Output +```html + + + +

Hello, World!

+ + +``` + +The same can be done with inline template string: + +```lua +-- Using template string +template.render([[ + + + +

{{message}}

+ +]], { message = "Hello, World!" }) +``` + +## Contents + +* [Template Syntax](#template-syntax) + * [Reserved Context Keys and Remarks](#reserved-context-keys-and-remarks) +* [Installation](#installation) + * [Using LuaRocks or Moonrocks](#using-luarocks-or-moonrocks) +* [Nginx / OpenResty Configuration](#nginx--openresty-configuration) +* [Lua API](#lua-api) + * [template.caching](#boolean-templatecachingboolean-or-nil) + * [template.new](#table-templatenewview-layout) + * [template.compile](#function-boolean-templatecompileview-key) + * [template.render](#templaterenderview-context-key) + * [template.parse](#string-templateparseview) + * [template.precompile](#string-templateprecompileview-path-strip) + * [template.load](#templateload) + * [template.print](#templateprint) +* [Template Precompilation](#template-precompilation) +* [Template Helpers](#template-helpers) +* [Usage Examples](#usage-examples) + * [Template Including](#template-including) + * [Views with Layouts](#views-with-layouts) + * [Using Blocks](#using-blocks) + * [Grandfather-Father-Son Inheritance](#grandfather-father-son-inheritance) + * [Macros](#macros) + * [Calling Methods in Templates](#calling-methods-in-templates) + * [Embedding Angular or other tags / templating inside the Templates](#embedding-angular-or-other-tags--templating-inside-the-templates) + * [Embedding Markdown inside the Templates](#embedding-markdown-inside-the-templates) + * [Lua Server Pages (LSP) with OpenResty](#lua-server-pages-lsp-with-openresty) +* [FAQ](#faq) +* [Alternatives](#alternatives) +* [Benchmarks](#benchmarks) +* [Changes](#changes) +* [License](#license) + +## Template Syntax + +You may use the following tags in templates: + +* `{{expression}}`, writes result of expression - html escaped +* `{*expression*}`, writes result of expression +* `{% lua code %}`, executes Lua code +* `{(template)}`, includes `template` file, you may also supply context for include file `{(file.html, { message = "Hello, World" } )}` +* `{[expression]}`, includes `expression` file (the result of expression), you may also supply context for include file `{["file.html", { message = "Hello, World" } ]}` +* `{-block-}...{-block-}`, wraps inside of a `{-block-}` to a value stored in a `blocks` table with a key `block` (in this case), see [using blocks](https://github.com/bungle/lua-resty-template#using-blocks). Don't use predefined block names `verbatim` and `raw`. +* `{-verbatim-}...{-verbatim-}` and `{-raw-}...{-raw-}` are predefined blocks whose inside is not processed by the `lua-resty-template` but the content is outputted as is. +* `{# comments #}` everything between `{#` and `#}` is considered to be commented out (i.e. not outputted or executed) + +From templates you may access everything in `context` table, and everything in `template` table. In templates you can also access `context` and `template` by prefixing keys. + +```html +

{{message}}

==

{{context.message}}

+``` + +##### Short Escaping Syntax + +If you don't want a particular template tag to be processed you may escape the starting tag with backslash `\`: + +```html +

\{{message}}

+``` + +This will output (instead of evaluating the message): + +```html +

{{message}}

+``` + +If you want to add backslash char just before template tag, you need to escape that as well: + +```html +

\\{{message}}

+``` + +This will output: + +```html +

\[message-variables-content-here]

+``` + +##### A Word About Complex Keys in Context Table + +Say you have this kind of a context table: + +```lua +local ctx = {["foo:bar"] = "foobar"} +``` + +And you want to render the `ctx["foo:bar"]`'s value `foobar` in your template. You have to specify it explicitly by referencing the `context` in your template: + +```html +{# {*["foo:bar"]*} won't work, you need to use: #} +{*context["foo:bar"]*} +``` + +Or altogether: + +```lua +template.render([[ +{*context["foo:bar"]*} +]], {["foo:bar"] = "foobar"}) +``` + +##### A Word About HTML Escaping + +Only strings are escaped, functions are called without arguments (recursively) and results are returned as is, other types are `tostring`ified. `nil`s and `ngx.null`s are converted to empty strings `""`. + +Escaped HTML characters: + +* `&` becomes `&` +* `<` becomes `<` +* `>` becomes `>` +* `"` becomes `"` +* `'` becomes `'` +* `/` becomes `/` + +#### Example +##### Lua +```lua +local template = require "resty.template" +template.render("view.html", { + title = "Testing lua-resty-template", + message = "Hello, World!", + names = { "James", "Jack", "Anne" }, + jquery = '' +}) +``` + +##### view.html +```html +{(header.html)} +

{{message}}

+
    +{% for _, name in ipairs(names) do %} +
  • {{name}}
  • +{% end %} +
+{(footer.html)} +``` + +##### header.html +```html + + + + {{title}} + {*jquery*} + + +``` + +##### footer.html +```html + + +``` + +#### Reserved Context Keys and Remarks + +It is adviced that you do not use these keys in your context tables: + +* `___`, holds the compiled template, if set you need to use `{{context.___}}` +* `context`, holds the current context, if set you need to use `{{context.context}}` +* `include`, holds the include helper function, if set you need to use `{{context.include}}` +* `layout`, holds the layout by which the view will be decorated, if set you need to use `{{context.layout}}` +* `blocks`, holds the blocks, if set you need to use `{{context.blocks}}` (see: [using blocks](#using-blocks)) +* `template`, holds the template table, if set you need to use `{{context.template}}` + +In addition to that with `template.new` you should not overwrite: + +* `render`, the function that renders a view, obviously ;-) + +You should also not `{(view.html)}` recursively: + +##### Lua +```lua +template.render "view.html" +``` + +##### view.html +```html +{(view.html)} +``` + +You can load templates from "sub-directories" as well with `{(syntax)}`: + +##### view.html +```html +{(users/list.html)} +``` + +**Also note that you can provide template either as a file path or as a string. If the file exists, it will be used, otherwise the string is used. See also [`template.load`](#templateload).** + +## Installation + +Just place [`template.lua`](https://github.com/bungle/lua-resty-template/blob/master/lib/resty/template.lua) somewhere in your `package.path`, preferably under `resty` directory. If you are using OpenResty, the default location would be `/usr/local/openresty/lualib/resty`. + +### Using LuaRocks or MoonRocks + +If you are using LuaRocks >= 2.2: + +```Shell +$ luarocks install lua-resty-template +``` + +If you are using LuaRocks < 2.2: + +```Shell +$ luarocks install --server=http://rocks.moonscript.org moonrocks +$ moonrocks install lua-resty-template +``` + +MoonRocks repository for `lua-resty-template` is located here: https://rocks.moonscript.org/modules/bungle/lua-resty-template. + +## Nginx / OpenResty Configuration + +When `lua-resty-template` is used in context of Nginx / OpenResty there are a few configuration directives that you need to be aware: + +* `template_root` (`set $template_root /var/www/site/templates`) +* `template_location` (`set $template_location /templates`) + +If none of these are set in Nginx configuration, `ngx.var.document_root` (aka root-directive) value is used. If `template_location` is set, it will be used first, and if the location returns anything but `200` as a status code, we do fallback to either `template_root` (if defined) or `document_root`. + +##### Using `document_root` + +This one tries to load file content with Lua code from `html` directory (relative to Nginx prefix). + +```nginx +http { + server { + location / { + root html; + content_by_lua ' + local template = require "resty.template" + template.render("view.html", { message = "Hello, World!" }) + '; + } + } +} +``` + +##### Using `template_root` + +This one tries to load file content with Lua code from `/usr/local/openresty/nginx/html/templates` directory. + +```nginx +http { + server { + set $template_root /usr/local/openresty/nginx/html/templates; + location / { + root html; + content_by_lua ' + local template = require "resty.template" + template.render("view.html", { message = "Hello, World!" }) + '; + } + } +} +``` + +##### Using `template_location` + +This one tries to load content with `ngx.location.capture` from `/templates` location (in this case this is served with `ngx_static` module). + +```nginx +http { + server { + set $template_location /templates; + location / { + root html; + content_by_lua ' + local template = require "resty.template" + template.render("view.html", { message = "Hello, World!" }) + '; + } + location /templates { + internal; + alias html/templates/; + } + } +} +``` + +**See also [`template.load`](#templateload).** + +## Lua API + +#### boolean template.caching(boolean or nil) + +This function enables or disables template caching, or if no parameters are passed, returns current state of template caching. By default template caching is enabled, but you may want to disable it on development or low-memory situations. + +```lua +local template = require "resty.template" +-- Get current state of template caching +local enabled = template.caching() +-- Disable template caching +template.caching(false) +-- Enable template caching +template.caching(true) +``` + +Please note that if the template was already cached when compiling a template, the cached version will be returned. You may want to flush cache with `template.cache = {}` to ensure that your template really gets recompiled. + +#### table template.new(view, layout) + +Creates a new template instance that is used as a (default) context when `render`ed. A table that gets created has +only one method `render`, but the table also has metatable with `__tostring` defined. See the example below. Both +`view` and `layout` arguments can either be strings or file paths, but layout can also be a table created previously +with `template.new`. + +```lua +local view = template.new"template.html" -- or +local view = template.new("view.html", "layout.html") -- or +local view = template.new[[

{{message}}

]] -- or +local view = template.new([[

{{message}}

]], [[ + + + {*view*} + + +]]) +``` + +##### Example +```lua +local template = require "resty.template" +local view = template.new"view.html" +view.message = "Hello, World!" +view:render() +-- You may also replace context on render +view:render{ title = "Testing lua-resty-template" } +-- If you want to include view context in replacement context +view:render(setmetatable({ title = "Testing lua-resty-template" }, { __index = view })) +-- To get rendered template as a string, you can use tostring +local result = tostring(view) +``` + +#### function, boolean template.compile(view, key, plain) + +Parses, compiles and caches (if caching is enabled) a template and returns the compiled template as a function that takes context as a parameter and returns rendered template as a string. Optionally you may pass `key` that is used as a cache key. If cache key is not provided `view` wil be used as a cache key. If cache key is `no-cache` the template cache will not be checked and the resulting function will not be cached. You may also optionally pass `plain` with a value of `true` if the `view` is plain text string (this will skip `template.load` and binary chunk detection in `template.parse` phase). + +```lua +local func = template.compile("template.html") -- or +local func = template.compile([[

{{message}}

]]) +``` + +##### Example +```lua +local template = require "resty.template" +local func = template.compile("view.html") +local world = func{ message = "Hello, World!" } +local universe = func{ message = "Hello, Universe!" } +print(world, universe) +``` + +Also note the second return value which is a boolean. You may discard it, or use it to determine if the returned function was cached. + +#### template.render(view, context, key, plain) + +Parses, compiles, caches (if caching is enabled) and outputs template either with `ngx.print` if available, or `print`. You may optionally also pass `key` that is used as a cache key. If `plain` evaluates to `true`, the `view` is considered to be plain string template (`template.load` and binary chunk detection is skipped on `template.parse`). + +```lua +template.render("template.html", { message = "Hello, World!" }) -- or +template.render([[

{{message}}

]], { message = "Hello, World!" }) +``` + +##### Example +```lua +local template = require "resty.template" +template.render("view.html", { message = "Hello, World!" }) +template.render("view.html", { message = "Hello, Universe!" }) +``` + +#### string template.parse(view, plain) + +Parses template file or string, and generates a parsed template string. This may come useful when debugging templates. You should note that if you are trying to parse a binary chunk (e.g. one returned with `template.compile`), `template.parse` will return that binary chunk as is. If optional parameter `plain` evaluates to `true`, the `view` is considered to be plain string, and the `template.load` and binary chunk detection is skipped. + +```lua +local t1 = template.parse("template.html") +local t2 = template.parse([[

{{message}}

]]) +``` + +#### string template.precompile(view, path, strip) + +Precompiles template as a binary chunk. This binary chunk can be written out as a file (and you may use it directly with Lua's `load` and `loadfile`). For convenience you may optionally specify `path` argument to output binary chunk to file. You may also supply `strip` parameter with value of `false` to make precompiled templates to have debug information as well (defaults to `true`). + +```lua +local view = [[ +

{{title}}

+
    +{% for _, v in ipairs(context) do %} +
  • {{v}}
  • +{% end %} +
]] + +local compiled = template.precompile(view) + +local file = io.open("precompiled-bin.html", "wb") +file:write(compiled) +file:close() + +-- Alternatively you could just write (which does the same thing as above) +template.precompile(view, "precompiled-bin.html") + +template.render("precompiled-bin.html", { + title = "Names", + "Emma", "James", "Nicholas", "Mary" +}) +``` + +#### template.load + +This field is used to load templates. `template.parse` calls this function before it starts parsing the template (assuming that optional `plain` argument in `template.parse` evaluates false (the default). By default there are two loaders in `lua-resty-template`: one for Lua and the other for Nginx / OpenResty. Users can overwrite this field with their own function. For example you may want to write a template loader function that loads templates from a database. + +Default `template.load` for Lua (attached as template.load when used directly with Lua): + +```lua +local function load_lua(path) + -- read_file tries to open file from path, and return its content. + return read_file(path) or path +end +``` + +Default `template.load` for Nginx / OpenResty (attached as template.load when used in context of Nginx / OpenResty): + +```lua +local function load_ngx(path) + local file, location = path, ngx.var.template_location + if file:sub(1) == "/" then file = file:sub(2) end + if location and location ~= "" then + if location:sub(-1) == "/" then location = location:sub(1, -2) end + local res = ngx.location.capture(location .. '/' .. file) + if res.status == 200 then return res.body end + end + local root = ngx.var.template_root or ngx.var.document_root + if root:sub(-1) == "/" then root = root:sub(1, -2) end + -- read_file tries to open file from path, and return its content. + return read_file(root .. "/" .. file) or path +end +``` + +As you can see, `lua-resty-template` always tries (by default) to load a template from a file (or with `ngx.location.capture`) even if you provided template as a string. `lua-resty-template`. But if you know that your templates are always strings, and not file paths, you may use `plain` argument in `template.compile`, `template.render`, and `template.parse` OR replace `template.load` with the simplest possible template loader there is (but be aware that if your templates use `{(file.html)}` includes, those are considered as strings too, in this case `file.html` will be the template string that is parsed) - you could also setup a loader that finds templates in some database system, e.g. Redis: + +```lua +local template = require "resty.template" +template.load = function(s) return s end +``` + +#### template.print + +This field contains a function that is used on `template.render()` or `template.new("example.html"):render()` to output the results. By default this holds either `ngx.print` (if available) or `print`. You may want to (and are allowed to) overwrite this field, if you want to use your own output function instead. This is also useful if you are using some other framework, e.g. Turbo.lua (http://turbolua.org/). + +```lua +local template = require "resty.template" + +template.print = function(s) + print(s) + print("") +end +``` + +## Template Precompilation + +`lua-resty-template` supports template precompilation. This can be useful when you want to skip template parsing (and Lua interpretation) in production or if you do not want your templates distributed as plain text files on production servers. Also by precompiling, you can ensure that your templates do not contain something, that cannot be compiled (they are syntactically valid Lua). Although templates are cached (even without precompilation), there are some perfomance (and memory) gains. You could integrate template precompilation in your build (or deployment) scripts (maybe as Gulp, Grunt or Ant tasks). + +##### Precompiling template, and output it as a binary file + +```lua +local template = require "resty.template" +local compiled = template.precompile("example.html", "example-bin.html") +``` + +##### Load precompiled template file, and run it with context parameters + +```lua +local template = require "resty.template" +template.render("example-bin.html", { "Jack", "Mary" }) +``` + +## Template Helpers + +While `lua-resty-template` does not have much infrastucture or ways to extend it, you still have a few possibilities that you may try. + +* Adding methods to global `string`, and `table` types (not encouraged, though) +* Wrap your values with something before adding them in context (e.g. proxy-table) +* Create global functions +* Add local functions either to `template` table or `context` table +* Use metamethods in your tables + +While modifying global types seems convenient, it can have nasty side effects. That's why I suggest you to look at these libraries, and articles first: + +* Method Chaining Wrapper (http://lua-users.org/wiki/MethodChainingWrapper) +* Moses (https://github.com/Yonaba/Moses) +* underscore-lua (https://github.com/jtarchie/underscore-lua) + +You could for example add Moses' or Underscore's `_` to template table or context table. + +##### Example + +```lua +local _ = require "moses" +local template = require "resty.template" +template._ = _ +``` + +Then you can use `_` inside your templates. I created one example template helper that can be found from here: +https://github.com/bungle/lua-resty-template/blob/master/lib/resty/template/html.lua + +##### Lua + +```lua +local template = require "resty.template" +local html = require "resty.template.html" + +template.render([[ +
    +{% for _, person in ipairs(context) do %} + {*html.li(person.name)*} +{% end %} +
+ +{% for _, person in ipairs(context) do %} + + {*html.td{ id = person.id }(person.name)*} + +{% end %} +
]], { + { id = 1, name = "Emma"}, + { id = 2, name = "James" }, + { id = 3, name = "Nicholas" }, + { id = 4 } +}) +``` + +##### Output + +```html +
    +
  • Emma
  • +
  • James
  • +
  • Nicholas
  • +
  • +
+ + + + + + + + + + + + +
Emma
James
Nicholas
+
+``` + +## Usage Examples + +### Template Including + +You may include templates inside templates with `{(template)}` and `{(template, context)}` syntax. The first one uses the current context as a context for included template, and the second one replaces it with a new context. Here is example of using includes and passing a different context to include file: + +##### Lua + +```lua +local template = require "resty.template" +template.render("include.html", { users = { + { name = "Jane", age = 29 }, + { name = "John", age = 25 } +}}) +``` + +##### include.html + +```html + + +
    +{% for _, user in ipairs(users) do %} + {(user.html, user)} +{% end %} +
+ + +``` + +##### user.html + +```html +
  • User {{name}} is of age {{age}}
  • +``` + +##### Outut + +```html + + +
      +
    • User Jane is of age 29
    • +
    • User John is of age 25
    • +
    + + +``` + +### Views with Layouts + +Layouts (or Master Pages) can be used to wrap a view inside another view (aka layout). + +##### Lua +```lua +local template = require "resty.template" +local layout = template.new "layout.html" +layout.title = "Testing lua-resty-template" +layout.view = template.compile "view.html" { message = "Hello, World!" } +layout:render() +-- Or like this +template.render("layout.html", { + title = "Testing lua-resty-template", + view = template.compile "view.html" { message = "Hello, World!" } +}) +-- Or maybe you like this style more +-- (but please remember that context.view is overwritten on rendering the layout.html) +local view = template.new("view.html", "layout.html") +view.title = "Testing lua-resty-template" +view.message = "Hello, World!" +view:render() +-- Well, maybe like this then? +local layout = template.new "layout.html" +layout.title = "Testing lua-resty-template" +local view = template.new("view.html", layout) +view.message = "Hello, World!" +view:render() +``` + +##### view.html +```html +

    {{message}}

    +``` + +##### layout.html +```html + + + + {{title}} + + + {*view*} + + +``` + +##### Alternatively you can define the layout in a view as well: + +##### Lua +```lua +local view = template.new("view.html", "layout.html") +view.title = "Testing lua-resty-template" +view.message = "Hello, World!" +view:render() +``` + +##### view.html +```html +{% layout="section.html" %} +

    {{message}}

    +``` + +##### section.html +```html +
    + {*view*} +
    +``` + +##### layout.html +```html + + + + {{title}} + + + {*view*} + + +``` + +##### Output +```html + + + + Testing lua-resty-template + + +
    +

    Hello, World!

    +
    + + +``` + +### Using Blocks + +Blocks can be used to move different parts of the views to specific places in layouts. Layouts have placeholders for blocks. + +##### Lua +```lua +local view = template.new("view.html", "layout.html") +view.title = "Testing lua-resty-template blocks" +view.message = "Hello, World!" +view.keywords = { "test", "lua", "template", "blocks" } +view:render() +``` + +##### view.html +```html +

    {{message}}

    +{-aside-} +
      + {% for _, keyword in ipairs(keywords) do %} +
    • {{keyword}}
    • + {% end %} +
    +{-aside-} +``` + +##### layout.html +```html + + + +{*title*} + + +
    + {*view*} +
    +{% if blocks.aside then %} + +{% end %} + + +``` + +##### Output + +```html + + + +Testing lua-resty-template blocks + + +
    +

    Hello, World!

    +
    + + + +``` +### Grandfather-Father-Son Inheritance + +Say you have `base.html`, `layout1.html`, `layout2.html` and `page.html`. You want an inheritance like this: +`base.html ➡ layout1.html ➡ page.html` or `base.html ➡ layout2.html ➡ page.html` (actually this nesting is not limited to three levels). + +##### Lua + +```lua +local res = require"resty.template".compile("page.html"){} +``` + +##### base.html + +```html + + + + {* blocks.page_css *} + + + {* blocks.main *} + + + {* blocks.page_js *} + + +``` + +##### layout1.html + +```html +{% layout = "base.html" %} +{-main-} + +
    + {* blocks.content *} +
    +{-main-} +``` + +##### layout2.html + +```html +{% layout = "base.html" %} +{-main-} + +
    + {* blocks.content *} +
    +
    I am different from layout1
    +{-main-} +``` + +##### page.html + +```html +{% layout = "layout1.html" %} +{-sidebar-} + this is sidebar +{-sidebar-} + +{-content-} + this is content +{-content-} + +{-page_css-} + +{-page_css-} + +{-page_js-} + +{-page_js-} +``` + +Or: + +##### page.html + +```html +{% layout = "layout2.html" %} +{-sidebar-} + this is sidebar +{-sidebar-} + +{-content-} + this is content +{-content-} + +{-page_css-} + +{-page_css-} + +{-page_js-} + +{-page_js-} +``` + +### Macros + +[@DDarko](https://github.com/DDarko) mentioned in an [issue #5](https://github.com/bungle/lua-resty-template/issues/5) that he has a use case where he needs to have macros or parameterized views. That is a nice feature that you can use with `lua-resty-template`. + +To use macros, let's first define some Lua code: + +```lua +template.render("macro.html", { + item = "original", + items = { a = "original-a", b = "original-b" } +}) +``` + +And the `macro-example.html`: + +```lua +{% local string_macro = [[ +
    {{item}}
    +]] %} +{* template.compile(string_macro)(context) *} +{* template.compile(string_macro){ item = "string-macro-context" } *} +``` + +This will output: + +```html +
    original
    +
    string-macro-context
    +``` + +Now let's add function macro, in `macro-example.html` (you can omit `local` if you want): + +```lua +{% local function_macro = function(var, el) + el = el or "div" + return "<" .. el .. ">{{" .. var .. "}}\n" +end %} + +{* template.compile(function_macro("item"))(context) *} +{* template.compile(function_macro("a", "span"))(items) *} +``` + +This will output: + +```html +
    original
    +original-a +``` + +But this is even more flexible, let's try another function macro: + +```lua +{% local function function_macro2(var) + return template.compile("
    {{" .. var .. "}}
    \n") +end %} +{* function_macro2 "item" (context) *} +{* function_macro2 "b" (items) *} +``` + +This will output: + +```html +
    original
    +
    original-b
    +``` + +And here is another one: + +```lua +{% function function_macro3(var, ctx) + return template.compile("
    {{" .. var .. "}}
    \n")(ctx or context) +end %} +{* function_macro3("item") *} +{* function_macro3("a", items) *} +{* function_macro3("b", items) *} +{* function_macro3("b", { b = "b-from-new-context" }) *} +``` + +This will output: + +```html +
    original
    +
    original-a
    +
    original-b
    +
    b-from-new-context
    +``` + +Macros are really flexible. You may have form-renderers and other helper-macros to have a reusable and parameterized template output. One thing you should know is that inside code blocks (between `{%` and `%}`) you cannot have `%}`, but you can work around this using string concatenation `"%" .. "}"`. + +### Calling Methods in Templates + +You can call string methods (or other table functions) in templates too. + +##### Lua +```lua +local template = require "resty.template" +template.render([[ +

    {{header:upper()}}

    +]], { header = "hello, world!" }) +``` + +##### Output +```html +

    HELLO, WORLD!

    +``` +### Embedding Angular or other tags / templating inside the Templates + +Sometimes you need to mix and match other templates (say client side Javascript templates like Angular) with +server side lua-resty-templates. Say you have this kind of Angular template: + +```html + + + + +