apr-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Jeff Trawick <traw...@attglobal.net>
Subject tweaks to gethostname() for consistent error handling
Date Mon, 19 Nov 2001 15:44:13 GMT
Some systems will fail hostname() if buf too small, others won't, but
will truncate the name and not leave it '\0'-terminated.  Apps end up
adding their own logic to '\0'-terminate it, but rarely add logic to
determine whether or not it was truncated.  The app may or may not
work differently on systems where hostname() returns -1 if buf is too
small.

To move some of the gorpy logic out of the app, I changed
apr_gethostname() to zap any truncated buffer if hostname() failed
outright or if it returned a truncated name, and to return an error if
either of these occurred.  Thus, the sloppy app can't mistakenly use a
truncated hostname and the good app gets a failure on all APR
platforms if the buffer is too small.

Any further suggestions?

(same change needed in win32/sockopt.c and os2/sockopt.c)

Index: include/apr_network_io.h
===================================================================
RCS file: /cvs/apache/apr/include/apr_network_io.h,v
retrieving revision 1.112
diff -u -r1.112 apr_network_io.h
--- apr_network_io.h	2001/11/13 19:35:15	1.112
+++ apr_network_io.h	2001/11/19 15:18:06
@@ -407,8 +407,9 @@
  * Get name of the current machine
  * @param buf A buffer to store the hostname in.
  * @param len The maximum length of the hostname that can be stored in the
- *            buffer provided. 
+ *            buffer provided.  The suggested length is APRMAXHOSTLEN + 1.
  * @param cont The pool to use.
+ * @remark If the buffer was not large enough, an error will be returned.
  */
 APR_DECLARE(apr_status_t) apr_gethostname(char *buf, int len, apr_pool_t *cont);
 
Index: network_io/unix/sockopt.c
===================================================================
RCS file: /cvs/apache/apr/network_io/unix/sockopt.c,v
retrieving revision 1.48
diff -u -r1.48 sockopt.c
--- sockopt.c	2001/07/30 17:56:16	1.48
+++ sockopt.c	2001/11/19 15:18:09
@@ -293,10 +293,18 @@
 
 apr_status_t apr_gethostname(char *buf, apr_int32_t len, apr_pool_t *cont)
 {
-    if (gethostname(buf, len) == -1)
+    if (gethostname(buf, len) == -1) {
+        buf[0] = '\0';
         return errno;
-    else
-        return APR_SUCCESS;
+    }
+    else if (!memchr(buf, '\0', len)) { /* buffer too small */
+        /* note... most platforms just truncate in this condition
+         *         linux+glibc return an error
+         */
+        buf[0] = '\0';
+        return APR_ENAMETOOLONG;
+    }
+    return APR_SUCCESS;
 }
 
 #if APR_HAS_SO_ACCEPTFILTER

-- 
Jeff Trawick | trawick@attglobal.net | PGP public key at web site:
       http://www.geocities.com/SiliconValley/Park/9289/
             Born in Roswell... married an alien...

Mime
View raw message