[PATCH v4 RESEND 1/5] Optimize string copy in Unix sockets.

Alejandro Colomar alx.manpages at gmail.com
Tue Aug 23 23:02:34 UTC 2022


ngx_cpystrn() checks at every character if it is '\0' after
copying it.  We don't really need that check for copying the
sun_path, since it's unlikely that the path contains a null
character.  And even if that happened, the kernel will ignore any
trailing bytes after the first null character, so we can safely
copy things like "foo\0bar", and the kernel will interpret it as
if we had passed just "foo".

memcpy(3) will usually be the fastest copy method for the system,
so it optimizes a little bit.

But the main reason for this change is not really optimizing, but
instead it's for adding support for abstract Unix domain sockets,
which use null characters as the first character in the string,
and possibly also use it in the middle of the string.

Signed-off-by: Alejandro Colomar <alx.manpages at gmail.com>
Cc: Andrew Clayton <andrew at digital-domain.net>
Cc: Bjornar Ness <bjornar.ness at gmail.com>
---
 src/core/ngx_inet.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/src/core/ngx_inet.c b/src/core/ngx_inet.c
index 4228504a..2b062b88 100644
--- a/src/core/ngx_inet.c
+++ b/src/core/ngx_inet.c
@@ -744,7 +744,8 @@ ngx_parse_unix_domain_url(ngx_pool_t *pool, ngx_url_t *u)
     u->socklen = sizeof(struct sockaddr_un);
     saun = (struct sockaddr_un *) &u->sockaddr;
     saun->sun_family = AF_UNIX;
-    (void) ngx_cpystrn((u_char *) saun->sun_path, path, len);
+    memcpy(saun->sun_path, path, len - 1);
+    saun->sun_path[len] = '\0';
 
     u->addrs = ngx_pcalloc(pool, sizeof(ngx_addr_t));
     if (u->addrs == NULL) {
@@ -760,7 +761,8 @@ ngx_parse_unix_domain_url(ngx_pool_t *pool, ngx_url_t *u)
     u->naddrs = 1;
 
     saun->sun_family = AF_UNIX;
-    (void) ngx_cpystrn((u_char *) saun->sun_path, path, len);
+    memcpy(saun->sun_path, path, len - 1);
+    saun->sun_path[len] = '\0';
 
     u->addrs[0].sockaddr = (struct sockaddr *) saun;
     u->addrs[0].socklen = sizeof(struct sockaddr_un);
-- 
2.37.2



More information about the nginx-devel mailing list