From 242021eb6ec4149a96067967ad1821368babd0b0 Mon Sep 17 00:00:00 2001 From: ElvaLiu Date: Sun, 1 Dec 2024 18:23:11 -0800 Subject: [PATCH] fix: support tcp binding ip:port or ip of ipv4 or ipv6 --- src/ngx_http_lua_socket_tcp.c | 4 +-- src/ngx_http_lua_util.c | 55 +++++++++++++++++++++++++++++++++++ src/ngx_http_lua_util.h | 2 ++ 3 files changed, 59 insertions(+), 2 deletions(-) diff --git a/src/ngx_http_lua_socket_tcp.c b/src/ngx_http_lua_socket_tcp.c index 998881d1ca..6048db7eaf 100644 --- a/src/ngx_http_lua_socket_tcp.c +++ b/src/ngx_http_lua_socket_tcp.c @@ -867,7 +867,7 @@ ngx_http_lua_socket_tcp_bind(lua_State *L) text = (u_char *) luaL_checklstring(L, 2, &len); - local = ngx_http_lua_parse_addr(L, text, len); + local = ngx_http_lua_parse_addr_port(L, text, len); if (local == NULL) { lua_pushnil(L); lua_pushfstring(L, "bad address"); @@ -3430,7 +3430,7 @@ ngx_http_lua_socket_tcp_handler(ngx_event_t *ev) static ngx_int_t ngx_http_lua_socket_tcp_get_peer(ngx_peer_connection_t *pc, void *data) { - /* empty */ + pc->type = SOCK_STREAM; return NGX_OK; } diff --git a/src/ngx_http_lua_util.c b/src/ngx_http_lua_util.c index c73bddc609..c1d7f01750 100644 --- a/src/ngx_http_lua_util.c +++ b/src/ngx_http_lua_util.c @@ -4555,4 +4555,59 @@ ngx_http_lua_parse_addr(lua_State *L, u_char *text, size_t len) } +ngx_addr_t * +ngx_http_lua_parse_addr_port(lua_State *L, u_char *text, size_t len) +{ + u_char *p, *last; + ngx_int_t port; + ngx_addr_t *addr; + size_t plen; + + addr = ngx_http_lua_parse_addr(L, text, len); + if (addr != NULL) { + return addr; + } + + last = text + len; + +#if (NGX_HAVE_INET6) + if (len && text[0] == '[') { + p = ngx_strlchr(text, last, ']'); + if (p == NULL || p == last - 1 || *++p != ':') { + return NULL; + } + + text++; + len -= 2; + } else +#endif + + { + p = ngx_strlchr(text, last, ':'); + if (p == NULL) { + return NULL; + } + } + + p++; + plen = last - p; + + port = ngx_atoi(p, plen); + if (port < 1 || port > 65535) { + return NULL; + } + + len -= plen + 1; + + addr = ngx_http_lua_parse_addr(L, text, len); + if (addr == NULL) { + return NULL; + } + + ngx_inet_set_port(addr->sockaddr, (in_port_t) port); + + return addr; +} + + /* vi:set ft=c ts=4 sw=4 et fdm=marker: */ diff --git a/src/ngx_http_lua_util.h b/src/ngx_http_lua_util.h index 85c6e614d6..6463142e89 100644 --- a/src/ngx_http_lua_util.h +++ b/src/ngx_http_lua_util.h @@ -265,6 +265,8 @@ ngx_int_t ngx_http_lua_decode_base64mime(ngx_str_t *dst, ngx_str_t *src); ngx_addr_t *ngx_http_lua_parse_addr(lua_State *L, u_char *text, size_t len); +ngx_addr_t *ngx_http_lua_parse_addr_port(lua_State *L, u_char *text, size_t len); + size_t ngx_http_lua_escape_log(u_char *dst, u_char *src, size_t size);