From: Dave Hart Date: Tue, 5 Apr 2011 07:05:55 +0000 (+0000) Subject: String buffer safety cleanup, converting to strlcpy() and strlcat(). X-Git-Tag: NTP_4_2_7P146~2 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=223d66392a561fa247eefee07790a91298a20636;p=thirdparty%2Fntp.git String buffer safety cleanup, converting to strlcpy() and strlcat(). Use utmpname() before pututline() so repeated steps do not accidentally record into wtmp where utmp was intended. Use setutent() before each pututline() including first. bk: 4d9abf53UTx9b0xo43YQPPKApCX-yg --- diff --git a/include/ntp_stdlib.h b/include/ntp_stdlib.h index aaac4d57b..451c16f15 100644 --- a/include/ntp_stdlib.h +++ b/include/ntp_stdlib.h @@ -230,6 +230,27 @@ extern int keytype_from_text (const char *, size_t *); extern const char *keytype_name (int); extern char * getpass_keytype (int); +/* strl-obsd.c */ +#ifndef HAVE_STRLCPY /* + */ +/* + * Copy src to string dst of size siz. At most siz-1 characters + * will be copied. Always NUL terminates (unless siz == 0). + * Returns strlen(src); if retval >= siz, truncation occurred. + */ +extern size_t strlcpy(char *dst, const char *src, size_t siz); +#endif +#ifndef HAVE_STRLCAT /* + */ +/* + * Appends src to string dst of size siz (unlike strncat, siz is the + * full size of dst, not space left). At most siz-1 characters + * will be copied. Always NUL terminates (unless siz <= strlen(dst)). + * Returns strlen(src) + MIN(siz, strlen(initial dst)). + * If retval >= siz, truncation occurred. + */ +extern size_t strlcat(char *dst, const char *src, size_t siz); +#endif + + /* lib/isc/win32/strerror.c * diff --git a/libntp/Makefile.am b/libntp/Makefile.am index f3434cbb3..31a28995c 100644 --- a/libntp/Makefile.am +++ b/libntp/Makefile.am @@ -100,6 +100,7 @@ libntp_a_SRCS = \ ssl_init.c \ statestr.c \ strdup.c \ + strl_obsd.c \ syssignal.c \ timespecops.c \ timetoa.c \ diff --git a/libntp/audio.c b/libntp/audio.c index 9a3e9cf3e..5fbe23902 100644 --- a/libntp/audio.c +++ b/libntp/audio.c @@ -176,19 +176,19 @@ audio_config_read( if (!strncmp(cc, "IDEV", (size_t) 4)) { sscanf(ca, "%99s", ab); - strncpy(cf_i_dev, ab, sizeof(cf_i_dev)); + strlcpy(cf_i_dev, ab, sizeof(cf_i_dev)); printf("idev <%s>\n", ab); } else if (!strncmp(cc, "CDEV", (size_t) 4)) { sscanf(ca, "%99s", ab); - strncpy(cf_c_dev, ab, sizeof(cf_c_dev)); + strlcpy(cf_c_dev, ab, sizeof(cf_c_dev)); printf("cdev <%s>\n", ab); } else if (!strncmp(cc, "AGC", (size_t) 3)) { sscanf(ca, "%99s", ab); - strncpy(cf_agc, ab, sizeof(cf_agc)); + strlcpy(cf_agc, ab, sizeof(cf_agc)); printf("agc <%s> %d\n", ab, i); } else if (!strncmp(cc, "MONITOR", (size_t) 7)) { sscanf(ca, "%99s", ab); - strncpy(cf_monitor, ab, sizeof(cf_monitor)); + strlcpy(cf_monitor, ab, sizeof(cf_monitor)); printf("monitor <%s> %d\n", ab, mixer_name(ab, -1)); } } diff --git a/libntp/authkeys.c b/libntp/authkeys.c index 94bc87fcf..3b65b4184 100644 --- a/libntp/authkeys.c +++ b/libntp/authkeys.c @@ -354,7 +354,7 @@ MD5auth_setkey( #ifndef DISABLE_BUG1243_FIX memcpy(sk->k.MD5_key, key, sk->keylen); #else - strncpy((char *)sk->k.MD5_key, (const char *)key, + strlcpy((char *)sk->k.MD5_key, (const char *)key, sizeof(sk->k.MD5_key)); #endif if (cache_keyid == keyno) { @@ -384,7 +384,7 @@ MD5auth_setkey( #ifndef DISABLE_BUG1243_FIX memcpy(sk->k.MD5_key, key, sk->keylen); #else - strncpy((char *)sk->k.MD5_key, (const char *)key, + strlcpy((char *)sk->k.MD5_key, (const char *)key, sizeof(sk->k.MD5_key)); #endif sk->next = key_hash[KEYHASH(keyno)]; diff --git a/libntp/decodenetnum.c b/libntp/decodenetnum.c index 9d950c6f8..d88c6550e 100644 --- a/libntp/decodenetnum.c +++ b/libntp/decodenetnum.c @@ -51,7 +51,7 @@ decodenetnum( else if (NULL != strchr(pp + 1, ':')) cp = num; /* two or more colons */ else { /* one colon */ - strncpy(name, num, sizeof(name)); + strlcpy(name, num, sizeof(name)); cp = name; pp = strchr(cp, ':'); *pp = '\0'; diff --git a/libntp/findconfig.c b/libntp/findconfig.c index 44e6b07ed..1785ff700 100644 --- a/libntp/findconfig.c +++ b/libntp/findconfig.c @@ -22,7 +22,7 @@ FindConfig( struct utsname unamebuf; /* All keyed by initial target being a directory */ - strncpy(result, base, sizeof(result)); + strlcpy(result, base, sizeof(result)); if (stat(result, &sbuf) == 0) { if (S_ISDIR(sbuf.st_mode)) { @@ -49,7 +49,7 @@ FindConfig( if (stat(result, &sbuf) == 0) { goto outahere; } else { - strncpy(result, + strlcpy(result, "/not/found", sizeof(result)); } diff --git a/libntp/msyslog.c b/libntp/msyslog.c index 10cc3bc8c..7c9e904a5 100644 --- a/libntp/msyslog.c +++ b/libntp/msyslog.c @@ -68,7 +68,7 @@ errno_to_str( pstatic = strerror(err); # endif if (pstatic != buf) - strncpy(buf, pstatic, bufsiz); + strlcpy(buf, pstatic, bufsiz); # else int rc; diff --git a/libntp/ntp_rfc2553.c b/libntp/ntp_rfc2553.c index 9c37aafa2..fe4eb09d2 100644 --- a/libntp/ntp_rfc2553.c +++ b/libntp/ntp_rfc2553.c @@ -412,7 +412,6 @@ getnameinfo (const struct sockaddr *sa, u_int salen, char *host, size_t hostlen, char *serv, size_t servlen, int flags) { struct hostent *hp; - int namelen; if (sa->sa_family != AF_INET) return (EAI_FAMILY); @@ -426,15 +425,7 @@ getnameinfo (const struct sockaddr *sa, u_int salen, char *host, return (EAI_FAIL); } if (host != NULL && hostlen > 0) { - /* - * Don't exceed buffer - */ - namelen = min(strlen(hp->h_name), hostlen - 1); - if (namelen > 0) { - strncpy(host, hp->h_name, namelen); - host[namelen] = '\0'; - } - } + strlcpy(host, hp->h_name, hostlen); return (0); } diff --git a/libntp/numtoa.c b/libntp/numtoa.c index 0fbbab794..5efbe942e 100644 --- a/libntp/numtoa.c +++ b/libntp/numtoa.c @@ -48,7 +48,7 @@ refid_str( LIB_GETBUF(text); text[0] = '.'; - strncpy(&text[1], (void *)&refid, sizeof(refid)); + memcpy(&text[1], &refid, sizeof(refid)); text[1 + sizeof(refid)] = '\0'; tlen = strlen(text); text[tlen] = '.'; diff --git a/libntp/numtohost.c b/libntp/numtohost.c index b3d458ee0..6b250d602 100644 --- a/libntp/numtohost.c +++ b/libntp/numtohost.c @@ -37,8 +37,7 @@ numtohost( return numtoa(netnum); LIB_GETBUF(bp); - - bp[LIB_BUFLENGTH-1] = '\0'; - (void) strncpy(bp, hp->h_name, LIB_BUFLENGTH-1); + strlcpy(bp, hp->h_name, LIB_BUFLENGTH); + return bp; } diff --git a/libntp/socktoa.c b/libntp/socktoa.c index fcac7bcfa..2d002c842 100644 --- a/libntp/socktoa.c +++ b/libntp/socktoa.c @@ -42,7 +42,7 @@ socktoa( LIB_GETBUF(res); if (NULL == sock) - strncpy(res, "(null)", LIB_BUFLENGTH); + strlcpy(res, "(null)", LIB_BUFLENGTH); else { switch(AF(sock)) { diff --git a/libntp/ssl_init.c b/libntp/ssl_init.c index 0145f0dc6..7cb37594e 100644 --- a/libntp/ssl_init.c +++ b/libntp/ssl_init.c @@ -94,7 +94,7 @@ keytype_from_text( */ INIT_SSL(); LIB_GETBUF(upcased); - strncpy(upcased, text, LIB_BUFLENGTH); + strlcpy(upcased, text, LIB_BUFLENGTH); for (pch = upcased; '\0' != *pch; pch++) *pch = (char)toupper(*pch); key_type = OBJ_sn2nid(upcased); diff --git a/libntp/strl_obsd.c b/libntp/strl_obsd.c new file mode 100644 index 000000000..cb8d4f359 --- /dev/null +++ b/libntp/strl_obsd.c @@ -0,0 +1,123 @@ +/* + * Why use strlcpy()/strlcat() instead of standard strncpy()/strncat()? + * To reduce likelihood of bugs and avoid wasteful zero fills. See: + * http://www.gratisoft.us/todd/papers/strlcpy.html + */ + +/* $OpenBSD: strlcpy.c,v 1.11 2006/05/05 15:27:38 millert Exp $ */ + +/* + * Copyright (c) 1998 Todd C. Miller + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include /* + marks local changes */ +#ifdef HAVE_SYS_TYPES_H /* + */ +#include +#endif /* + */ +#include + +#include "ntp_stdlib.h" /* + strlcpy, strlcat prototypes */ + +#ifndef HAVE_STRLCPY /* + */ +/* + * Copy src to string dst of size siz. At most siz-1 characters + * will be copied. Always NUL terminates (unless siz == 0). + * Returns strlen(src); if retval >= siz, truncation occurred. + */ +size_t +strlcpy(char *dst, const char *src, size_t siz) +{ + char *d = dst; + const char *s = src; + size_t n = siz; + + /* Copy as many bytes as will fit */ + if (n != 0) { + while (--n != 0) { + if ((*d++ = *s++) == '\0') + break; + } + } + + /* Not enough room in dst, add NUL and traverse rest of src */ + if (n == 0) { + if (siz != 0) + *d = '\0'; /* NUL-terminate dst */ + while (*s++) + ; + } + + return(s - src - 1); /* count does not include NUL */ +} +#endif /* + */ + + +/* $OpenBSD: strlcat.c,v 1.13 2005/08/08 08:05:37 espie Exp $ */ + +/* + * Copyright (c) 1998 Todd C. Miller + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/* #include */ /* + */ +/* #include */ /* + */ + +#ifndef HAVE_STRLCAT /* + */ +/* + * Appends src to string dst of size siz (unlike strncat, siz is the + * full size of dst, not space left). At most siz-1 characters + * will be copied. Always NUL terminates (unless siz <= strlen(dst)). + * Returns strlen(src) + MIN(siz, strlen(initial dst)). + * If retval >= siz, truncation occurred. + */ +size_t +strlcat(char *dst, const char *src, size_t siz) +{ + char *d = dst; + const char *s = src; + size_t n = siz; + size_t dlen; + + /* Find the end of dst and adjust bytes left but don't go past end */ + while (n-- != 0 && *d != '\0') + d++; + dlen = d - dst; + n = siz - dlen; + + if (n == 0) + return(dlen + strlen(s)); + while (*s != '\0') { + if (n != 1) { + *d++ = *s; + n--; + } + s++; + } + *d = '\0'; + + return(dlen + (s - src)); /* count does not include NUL */ +} +#endif /* + */ diff --git a/libntp/systime.c b/libntp/systime.c index 4ff0c0e1f..50c9ddea7 100644 --- a/libntp/systime.c +++ b/libntp/systime.c @@ -291,14 +291,19 @@ step_systime( #ifdef UPDATE_UTMP # ifdef HAVE_PUTUTLINE +# ifndef _PATH_UTMP +# define _PATH_UTMP UTMP_FILE +# endif + utmpname(_PATH_UTMP); ut.ut_type = OLD_TIME; - strncpy(ut.ut_line, OTIME_MSG, sizeof(ut.ut_line)); + strlcpy(ut.ut_line, OTIME_MSG, sizeof(ut.ut_line)); ut.ut_time = oldtimetv.tv_sec; - pututline(&ut); setutent(); + pututline(&ut); ut.ut_type = NEW_TIME; - strncpy(ut.ut_line, NTIME_MSG, sizeof(ut.ut_line)); + strlcpy(ut.ut_line, NTIME_MSG, sizeof(ut.ut_line)); ut.ut_time = timetv.tv_sec; + setutent(); pututline(&ut); endutent(); # else /* not HAVE_PUTUTLINE */ @@ -310,13 +315,14 @@ step_systime( #ifdef UPDATE_UTMPX # ifdef HAVE_PUTUTXLINE utx.ut_type = OLD_TIME; - strncpy(utx.ut_line, OTIME_MSG, sizeof(utx.ut_line)); + strlcpy(utx.ut_line, OTIME_MSG, sizeof(utx.ut_line)); utx.ut_tv = oldtimetv; - pututxline(&utx); setutxent(); + pututxline(&utx); utx.ut_type = NEW_TIME; - strncpy(utx.ut_line, NTIME_MSG, sizeof(utx.ut_line)); + strlcpy(utx.ut_line, NTIME_MSG, sizeof(utx.ut_line)); utx.ut_tv = timetv; + setutxent(); pututxline(&utx); endutxent(); # else /* not HAVE_PUTUTXLINE */ @@ -327,14 +333,19 @@ step_systime( #ifdef UPDATE_WTMP # ifdef HAVE_PUTUTLINE - utmpname(WTMP_FILE); +# ifndef _PATH_WTMP +# define _PATH_WTMP WTMP_FILE +# endif + utmpname(_PATH_WTMP); ut.ut_type = OLD_TIME; - strncpy(ut.ut_line, OTIME_MSG, sizeof(ut.ut_line)); + strlcpy(ut.ut_line, OTIME_MSG, sizeof(ut.ut_line)); ut.ut_time = oldtimetv.tv_sec; + setutent(); pututline(&ut); ut.ut_type = NEW_TIME; - strncpy(ut.ut_line, NTIME_MSG, sizeof(ut.ut_line)); + strlcpy(ut.ut_line, NTIME_MSG, sizeof(ut.ut_line)); ut.ut_time = timetv.tv_sec; + setutent(); pututline(&ut); endutent(); # else /* not HAVE_PUTUTLINE */ @@ -347,7 +358,7 @@ step_systime( # ifdef HAVE_PUTUTXLINE utx.ut_type = OLD_TIME; utx.ut_tv = oldtimetv; - strncpy(utx.ut_line, OTIME_MSG, sizeof(utx.ut_line)); + strlcpy(utx.ut_line, OTIME_MSG, sizeof(utx.ut_line)); # ifdef HAVE_UPDWTMPX updwtmpx(WTMPX_FILE, &utx); # else /* not HAVE_UPDWTMPX */ @@ -357,7 +368,7 @@ step_systime( # ifdef HAVE_PUTUTXLINE utx.ut_type = NEW_TIME; utx.ut_tv = timetv; - strncpy(utx.ut_line, NTIME_MSG, sizeof(utx.ut_line)); + strlcpy(utx.ut_line, NTIME_MSG, sizeof(utx.ut_line)); # ifdef HAVE_UPDWTMPX updwtmpx(WTMPX_FILE, &utx); # else /* not HAVE_UPDWTMPX */ diff --git a/libparse/data_mbg.c b/libparse/data_mbg.c index 65534b05c..97bef35c4 100644 --- a/libparse/data_mbg.c +++ b/libparse/data_mbg.c @@ -177,7 +177,7 @@ get_mbg_tzname( char *tznamep ) { - strncpy(tznamep, (char *)*buffpp, sizeof(TZ_NAME)); + strlcpy(tznamep, (char *)*buffpp, sizeof(TZ_NAME)); *buffpp += sizeof(TZ_NAME); } @@ -242,10 +242,10 @@ mbg_time_status_str( { if (p != *buffpp) { - strncpy(p, ", ", size - (p - start)); + strlcpy(p, ", ", size - (p - start)); p += 2; } - strncpy(p, s->string, size - (p - start)); + strlcpy(p, s->string, size - (p - start)); p += strlen(p); } } diff --git a/libparse/parsesolaris.c b/libparse/parsesolaris.c index ecd3fa2eb..d3756af88 100644 --- a/libparse/parsesolaris.c +++ b/libparse/parsesolaris.c @@ -143,7 +143,7 @@ _init( { if (strlen(t) >= (S - s)) { - (void) strncpy(t, s, (unsigned)(S - s)); + strlcpy(t, s, (unsigned)(S - s)); } } return (mod_install(&modlinkage)); diff --git a/ntpd/ntp_config.c b/ntpd/ntp_config.c index c633713a9..9dfb62357 100644 --- a/ntpd/ntp_config.c +++ b/ntpd/ntp_config.c @@ -1017,8 +1017,6 @@ concat_gen_fifos( else if (NULL == pf2) return pf1; - CHECK_FIFO_CONSISTENCY(*pf1); - CHECK_FIFO_CONSISTENCY(*pf2); CONCAT_FIFO(*pf1, *pf2, link); free(pf2); @@ -4266,7 +4264,7 @@ getconfig( * initialize it to "UNKNOWN". */ #ifndef SYS_WINNT - strncpy(line, "settimeofday=\"UNKNOWN\"", sizeof(line)); + strlcpy(line, "settimeofday=\"UNKNOWN\"", sizeof(line)); set_sys_var(line, strlen(line) + 1, RO); #endif getCmdOpts(argc, argv); @@ -4441,7 +4439,7 @@ normal_dtoa( pch_nz++; if (pch_nz == pch_e) return buf; - strncpy(pch_e, pch_nz, LIB_BUFLENGTH - (pch_e - buf)); + strlcpy(pch_e, pch_nz, LIB_BUFLENGTH - (pch_e - buf)); return buf; } diff --git a/ntpd/ntp_control.c b/ntpd/ntp_control.c index 82cbc8008..36f74a9dd 100644 --- a/ntpd/ntp_control.c +++ b/ntpd/ntp_control.c @@ -886,9 +886,7 @@ save_config( if (0 == reqend - reqpt) return; - strncpy(filespec, reqpt, sizeof(filespec)); - filespec[sizeof(filespec) - 1] = '\0'; - + strlcpy(filespec, reqpt, sizeof(filespec)); time(&now); /* @@ -898,10 +896,16 @@ save_config( */ if (0 == strftime(filename, sizeof(filename), filespec, localtime(&now))) - strncpy(filename, filespec, sizeof(filename)); - - filename[sizeof(filename) - 1] = '\0'; + strlcpy(filename, filespec, sizeof(filename)); + /* + * Conceptually we should be searching for DIRSEP in filename, + * however Windows actually recognizes both forward and + * backslashes as equivalent directory separators at the API + * level. On POSIX systems we could allow '\\' but such + * filenames are tricky to manipulate from a shell, so just + * reject both types of slashes on all platforms. + */ if (strchr(filename, '\\') || strchr(filename, '/')) { snprintf(reply, sizeof(reply), "saveconfig does not allow directory in filename"); @@ -2191,9 +2195,8 @@ ctl_putsys( case CS_DIGEST: if (crypto_flags) { - strncpy(str, OBJ_nid2ln(crypto_nid), + strlcpy(str, OBJ_nid2ln(crypto_nid), COUNTOF(str)); - str[COUNTOF(str) - 1] = '\0'; ctl_putstr(sys_var[CS_DIGEST].text, str, strlen(str)); } @@ -2204,9 +2207,8 @@ ctl_putsys( const EVP_MD *dp; dp = EVP_get_digestbynid(crypto_flags >> 16); - strncpy(str, OBJ_nid2ln(EVP_MD_pkey_type(dp)), + strlcpy(str, OBJ_nid2ln(EVP_MD_pkey_type(dp)), COUNTOF(str)); - str[COUNTOF(str) - 1] = '\0'; ctl_putstr(sys_var[CS_SIGNATURE].text, str, strlen(str)); } diff --git a/ntpd/ntp_filegen.c b/ntpd/ntp_filegen.c index fb2690a6c..ac9c09e8a 100644 --- a/ntpd/ntp_filegen.c +++ b/ntpd/ntp_filegen.c @@ -112,14 +112,15 @@ filegen_open( fullname = emalloc(len); savename = NULL; snprintf(filename, len, "%s%s", gen->prefix, gen->basename); - strncpy(fullname, filename, len); - fullname[len-1] = '\0'; /* prepare overflow detection */ /* where to place suffix */ - suflen = strlen(fullname); + suflen = strlcpy(fullname, filename, len); suffix = fullname + suflen; suflen = len - suflen; + /* last octet of fullname set to '\0' for truncation check */ + fullname[len - 1] = '\0'; + switch (gen->type) { default: @@ -128,10 +129,10 @@ filegen_open( "\"%s\" - reverting to FILEGEN_NONE", gen->type, filename); gen->type = FILEGEN_NONE; - /* fall through to FILEGEN_NONE */ + break; case FILEGEN_NONE: - strncpy(fullname, filename, len); + /* no suffix, all set */ break; case FILEGEN_PID: @@ -195,10 +196,8 @@ filegen_open( } /* check possible truncation */ - if (fullname[len-1]) { - fullname[len-1] = '\0'; - DPRINTF(1, ("logfile name truncated: \"%s\"", - fullname)); + if ('\0' != fullname[len - 1]) { + fullname[len - 1] = '\0'; msyslog(LOG_ERR, "logfile name truncated: \"%s\"", fullname); } diff --git a/ntpd/ntp_io.c b/ntpd/ntp_io.c index d89e98587..c89d6177c 100644 --- a/ntpd/ntp_io.c +++ b/ntpd/ntp_io.c @@ -707,12 +707,13 @@ is_ip_address( if (AF_UNSPEC == af || AF_INET6 == af) if (sizeof(tmpbuf) > strlen(host)) { if ('[' == host[0]) { - strncpy(tmpbuf, &host[1], sizeof(tmpbuf)); + strlcpy(tmpbuf, &host[1], sizeof(tmpbuf)); pch = strchr(tmpbuf, ']'); if (pch != NULL) *pch = '\0'; - } else - strncpy(tmpbuf, host, sizeof(tmpbuf)); + } else { + strlcpy(tmpbuf, host, sizeof(tmpbuf)); + } pch = strchr(tmpbuf, '%'); if (pch != NULL) *pch = '\0'; @@ -1086,7 +1087,7 @@ create_wildcards( if (v4wild) { wildif = new_interface(NULL); - strncpy(wildif->name, "v4wildcard", sizeof(wildif->name)); + strlcpy(wildif->name, "v4wildcard", sizeof(wildif->name)); memcpy(&wildif->sin, &wildaddr, sizeof(wildif->sin)); wildif->family = AF_INET; AF(&wildif->mask) = AF_INET; @@ -1140,7 +1141,7 @@ create_wildcards( if (v6wild) { wildif = new_interface(NULL); - strncpy(wildif->name, "v6wildcard", sizeof(wildif->name)); + strlcpy(wildif->name, "v6wildcard", sizeof(wildif->name)); memcpy(&wildif->sin, &wildaddr, sizeof(wildif->sin)); wildif->family = AF_INET6; AF(&wildif->mask) = AF_INET6; @@ -1387,8 +1388,7 @@ convert_isc_if( const u_char v6loop[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}; - strncpy(itf->name, isc_if->name, sizeof(itf->name)); - itf->name[sizeof(itf->name) - 1] = 0; /* strncpy may not */ + strlcpy(itf->name, isc_if->name, sizeof(itf->name)); itf->ifindex = isc_if->ifindex; itf->family = (u_short)isc_if->af; AF(&itf->sin) = itf->family; @@ -1603,7 +1603,7 @@ is_anycast( return ISC_FALSE; ZERO(ifr6); memcpy(&ifr6.ifr_addr, &psau->sa6, sizeof(ifr6.ifr_addr)); - strncpy(ifr6.ifr_name, name, sizeof(ifr6.ifr_name)); + strlcpy(ifr6.ifr_name, name, sizeof(ifr6.ifr_name)); if (ioctl(fd, SIOCGIFAFLAG_IN6, &ifr6) < 0) { close(fd); return ISC_FALSE; @@ -1766,7 +1766,7 @@ update_interfaces( * new prototype to respect any runtime * changes to the nic rules. */ - strncpy(ep->name, enumep.name, + strlcpy(ep->name, enumep.name, sizeof(ep->name)); if (ep->ignore_packets != enumep.ignore_packets) { @@ -1779,7 +1779,7 @@ update_interfaces( } } else { /* name collision - rename interface */ - strncpy(ep->name, "*multiple*", + strlcpy(ep->name, "*multiple*", sizeof(ep->name)); } @@ -2614,7 +2614,7 @@ io_multicast_add( ep->ignore_packets = ISC_FALSE; ep->flags |= INT_MCASTIF; - strncpy(ep->name, "multicast", sizeof(ep->name)); + strlcpy(ep->name, "multicast", sizeof(ep->name)); DPRINT_INTERFACE(2, (ep, "multicast add ", "\n")); add_interface(ep); log_listen_address(ep); diff --git a/ntpd/ntp_request.c b/ntpd/ntp_request.c index 2b9b68d2b..c9803c96c 100644 --- a/ntpd/ntp_request.c +++ b/ntpd/ntp_request.c @@ -2598,7 +2598,7 @@ fill_info_if_stats(void *data, interface_info_t *interface_info) ifs->unmask.addr = SOCK_ADDR4(&ep->mask); } ifs->v6_flag = htonl(ifs->v6_flag); - strncpy(ifs->name, ep->name, sizeof(ifs->name)); + strlcpy(ifs->name, ep->name, sizeof(ifs->name)); ifs->family = htons(ep->family); ifs->flags = htonl(ep->flags); ifs->last_ttl = htonl(ep->last_ttl); diff --git a/ntpd/ntp_resolver.c b/ntpd/ntp_resolver.c deleted file mode 100644 index 1f49a4bb1..000000000 --- a/ntpd/ntp_resolver.c +++ /dev/null @@ -1,974 +0,0 @@ - -/* Currently unused */ - -/* -** Ancestor was ripped off from ../ntpres/ntpres.c by Greg Troxel 4/2/92 -** -** The previous resolver only needed to do forward lookups, and all names -** were known before we started the resolver process. -** -** The new code must be able to handle reverse lookups, and the requests can -** show up at any time. -** -** Here's the drill for the new logic. -** -** We want to be able to do forward or reverse lookups. Forward lookups -** require one set of information to be sent back to the daemon, reverse -** lookups require a different set of information. The caller knows this. -** -** The daemon must not block. This includes communicating with the resolver -** process (if the resolver process is a separate task). -** -** Current resolver code blocks waiting for the response, so the -** alternatives are: -** -** - Find a nonblocking resolver library -** - Do each (initial) lookup in a separate process -** - - subsequent lookups *could* be handled by a different process that has -** a queue of pending requests -** -** We could use nonblocking lookups in a separate process (just to help out -** with timers). -** -** If we don't have nonblocking resolver calls we have more opportunities -** for denial-of-service problems. -** -** - too many fork()s -** - communications path -** -*/ - -#ifdef HAVE_CONFIG_H -# include -#endif - -#include -#include -#include - -#include -#include - -#include "ntp_machine.h" -#include "ntpd.h" -#include "ntp_io.h" -#include "ntp_request.h" -#include "ntp_stdlib.h" -#include "ntp_syslog.h" - -#define STREQ(a, b) (*(a) == *(b) && strcmp((a), (b)) == 0) - -/* - * Each item we are to resolve and configure gets one of these - * structures defined for it. - */ -struct dns_entry { - int de_done; -#define DE_NAME 001 -#define DE_ADDR 002 -#define DE_NA (DE_NAME | DE_ADDR) -#define DE_PENDING 000 -#define DE_GOT 010 -#define DE_FAIL 020 -#define DE_RESULT (DE_PENDING | DE_GOT | DE_FAIL) - struct dns_entry *de_next; - struct info_dns_assoc de_info; /* DNS info for peer */ -}; -#define de_associd de_info.associd -#define de_peeraddr de_info.peeraddr -#define de_hostname de_info.hostname - -/* - * dns_entries is a pointer to the list of configuration entries - * we have left to do. - */ -static struct dns_entry *dns_entries = NULL; - -/* - * We take an interrupt every thirty seconds, at which time we decrement - * config_timer and resolve_timer. The former is set to 2, so we retry - * unsucessful reconfigurations every minute. The latter is set to - * an exponentially increasing value which starts at 2 and increases to - * 32. When this expires we retry failed name resolutions. - * - * We sleep SLEEPTIME seconds before doing anything, to give the server - * time to arrange itself. - */ -#define MINRESOLVE 2 -#define MAXRESOLVE 32 -#define CONFIG_TIME 2 -#define ALARM_TIME 30 - -#define SLEEPTIME 2 - -static volatile int config_timer = 0; -static volatile int resolve_timer = 0; - -static int resolve_value; /* next value of resolve timer */ - -/* - * Big hack attack - */ -#define LOCALHOST 0x7f000001 /* 127.0.0.1, in hex, of course */ -#define SKEWTIME 0x08000000 /* 0.03125 seconds as a l_fp fraction */ - -/* - * Select time out. Set to 2 seconds. The server is on the local machine, - * after all. - */ -#define TIMEOUT_SEC 2 -#define TIMEOUT_USEC 0 - -/* - * File descriptor for ntp request code. - */ -static int sockfd = -1; - -/* - * Pipe descriptors - */ -int p_fd[2] = { -1, -1 }; - -/* stuff to be filled in by caller */ - -extern keyid_t req_keyid; /* request keyid */ - -/* end stuff to be filled in */ - -void ntp_res P((void)); -static RETSIGTYPE bong P((int)); -static void checkparent P((void)); -static void removeentry P((struct dns_entry *)); -static void addentry P((char *, struct sockaddr_storage, u_short)); -static void findhostaddr P((struct dns_entry *)); -static void openntp P((void)); -static int tell_ntpd P((struct info_dns_assoc *)); -static void doconfigure P((int)); - -struct ntp_res_t_pkt { /* Tagged packet: */ - void *tag; /* For the caller */ - u_int32 paddr; /* IP to look up, or 0 */ - char name[NTP_MAXHOSTNAME]; /* Name to look up (if 1st byte is not 0) */ -}; - -struct ntp_res_c_pkt { /* Control packet: */ - char name[NTP_MAXHOSTNAME]; - u_int32 paddr; - int mode; - int version; - int minpoll; - int maxpoll; - int flags; - int ttl; - keyid_t keyid; - u_char keystr[MAXFILENAME]; -}; - -/* - * ntp_res_name - */ - -void -ntp_res_name( - struct sockaddr_storage paddr, /* Address to resolve */ - u_short associd /* Association ID */ - ) -{ - pid_t pid; - - /* - * fork. - * - parent returns - * - child stuffs data and calls ntp_res() - */ - - for (pid = -1; pid == -1;) { -#ifdef RES_TEST - pid = 0; -#else - pid = fork(); -#endif - if (pid == -1) { - msyslog(LOG_ERR, "ntp_res_name: fork() failed: %m"); - sleep(2); - } - } - switch (pid) { - case -1: /* Error */ - msyslog(LOG_INFO, "ntp_res_name: error..."); - /* Can't happen */ - break; - - case 0: /* Child */ - closelog(); - kill_asyncio(); - (void) signal_no_reset(SIGCHLD, SIG_DFL); -#ifndef LOG_DAEMON - openlog("ntp_res", LOG_PID); -# else /* LOG_DAEMON */ -# ifndef LOG_NTP -# define LOG_NTP LOG_DAEMON -# endif - openlog("ntp_res_name", LOG_PID | LOG_NDELAY, LOG_NTP); -#endif - - addentry(NULL, paddr, associd); - ntp_res(); - break; - - default: /* Parent */ - /* Nothing to do. (In Real Life, this never happens.) */ - return; - } -} - -/* - * ntp_res needs; - * - * req_key(???), req_keyid valid - * syslog still open - */ - -void -ntp_res(void) -{ -#ifdef HAVE_SIGSUSPEND - sigset_t set; - - sigemptyset(&set); -#endif /* HAVE_SIGSUSPEND */ - -#ifdef DEBUG - if (debug) { - msyslog(LOG_INFO, "NTP_RESOLVER running"); - } -#endif - - /* check out auth stuff */ - if (sys_authenticate) { - if (!authistrusted(req_keyid)) { - msyslog(LOG_ERR, "invalid request keyid %08x", - req_keyid ); - exit(1); - } - } - - /* - * Make a first cut at resolving the bunch - */ - doconfigure(1); - if (dns_entries == NULL) { - if (debug) { - msyslog(LOG_INFO, "NTP_RESOLVER done!"); - } -#if defined SYS_WINNT - ExitThread(0); /* Don't want to kill whole NT process */ -#else - exit(0); /* done that quick */ -#endif - } - - /* - * Here we've got some problem children. Set up the timer - * and wait for it. - */ - resolve_value = resolve_timer = MINRESOLVE; - config_timer = CONFIG_TIME; -#ifndef SYS_WINNT - (void) signal_no_reset(SIGALRM, bong); - alarm(ALARM_TIME); -#endif /* SYS_WINNT */ - - for (;;) { - if (dns_entries == NULL) - exit(0); - - checkparent(); - - if (resolve_timer == 0) { - if (resolve_value < MAXRESOLVE) - resolve_value <<= 1; - resolve_timer = resolve_value; -#ifdef DEBUG - msyslog(LOG_INFO, "resolve_timer: 0->%d", resolve_timer); -#endif - config_timer = CONFIG_TIME; - doconfigure(1); - continue; - } else if (config_timer == 0) { - config_timer = CONFIG_TIME; -#ifdef DEBUG - msyslog(LOG_INFO, "config_timer: 0->%d", config_timer); -#endif - doconfigure(0); - continue; - } -#ifndef SYS_WINNT - /* - * There is a race in here. Is okay, though, since - * all it does is delay things by 30 seconds. - */ -# ifdef HAVE_SIGSUSPEND - sigsuspend(&set); -# else - sigpause(0); -# endif /* HAVE_SIGSUSPEND */ -#else - if (config_timer > 0) - config_timer--; - if (resolve_timer > 0) - resolve_timer--; - sleep(ALARM_TIME); -#endif /* SYS_WINNT */ - } -} - - -#ifndef SYS_WINNT -/* - * bong - service and reschedule an alarm() interrupt - */ -static RETSIGTYPE -bong( - int sig - ) -{ - if (config_timer > 0) - config_timer--; - if (resolve_timer > 0) - resolve_timer--; - alarm(ALARM_TIME); -} -#endif /* SYS_WINNT */ - -/* - * checkparent - see if our parent process is still running - * - * No need to worry in the Windows NT environment whether the - * main thread is still running, because if it goes - * down it takes the whole process down with it (in - * which case we won't be running this thread either) - * Turn function into NOP; - */ - -static void -checkparent(void) -{ -#if !defined (SYS_WINNT) && !defined (SYS_VXWORKS) - - /* - * If our parent (the server) has died we will have been - * inherited by init. If so, exit. - */ - if (getppid() == 1) { - msyslog(LOG_INFO, "parent died before we finished, exiting"); - exit(0); - } -#endif /* SYS_WINNT && SYS_VXWORKS*/ -} - - -/* - * removeentry - we are done with an entry, remove it from the list - */ -static void -removeentry( - struct dns_entry *entry - ) -{ - register struct dns_entry *de; - - de = dns_entries; - if (de == entry) { - dns_entries = de->de_next; - return; - } - - while (de != NULL) { - if (de->de_next == entry) { - de->de_next = entry->de_next; - return; - } - de = de->de_next; - } -} - - -/* - * addentry - add an entry to the configuration list - */ -static void -addentry( - char *name, - struct sockaddr_storage paddr, - u_short associd - ) -{ - register struct dns_entry *de; - -#ifdef DEBUG - if (debug > 1) { - msyslog(LOG_INFO, - "ntp_res_name: <%s> %s associd %d\n", - (name) ? name : "", stoa(&paddr), associd); - } -#endif - - de = (struct dns_entry *)emalloc(sizeof(struct dns_entry)); - if (name) { - strncpy(de->de_hostname, name, sizeof de->de_hostname); - de->de_done = DE_PENDING | DE_ADDR; - } else { - de->de_hostname[0] = 0; - de->de_done = DE_PENDING | DE_NAME; - } - de->de_peeraddr = paddr; - de->de_associd = associd; - de->de_next = NULL; - - if (dns_entries == NULL) { - dns_entries = de; - } else { - register struct dns_entry *dep; - - for (dep = dns_entries; dep->de_next != NULL; - dep = dep->de_next) - /* nothing */; - dep->de_next = de; - } -} - - -/* - * findhostaddr - resolve a host name into an address (Or vice-versa) - * - * sets entry->de_done appropriately when we're finished. We're finished if - * we either successfully look up the missing name or address, or if we get a - * "permanent" failure on the lookup. - * - */ -static void -findhostaddr( - struct dns_entry *entry - ) -{ - struct hostent *hp; - - checkparent(); /* make sure our guy is still running */ - - /* - * The following should never trip - this subroutine isn't - * called if hostname and peeraddr are "filled". - */ - if (entry->de_hostname[0] && !SOCKNUL(&entry->de_peeraddr)) { - - msyslog(LOG_ERR, "findhostaddr: both de_hostname and de_peeraddr are defined: <%s>/%s: state %#x", - &entry->de_hostname[0], stoa(&entry->de_peeraddr), entry->de_done); - return; - } - - /* - * The following should never trip. - */ - if (!entry->de_hostname[0] && SOCKNUL(&entry->de_peeraddr)) { - msyslog(LOG_ERR, "findhostaddr: both de_hostname and de_peeraddr are undefined!"); - entry->de_done |= DE_FAIL; - return; - } - - if (entry->de_hostname[0]) { -#ifdef DEBUG - if (debug > 2) - msyslog(LOG_INFO, "findhostaddr: Resolving <%s>", - &entry->de_hostname[0]); -#endif /* DEBUG */ - hp = gethostbyname(&entry->de_hostname[0]); - } else { -#ifdef DEBUG - if (debug > 2) { - msyslog(LOG_INFO, "findhostaddr: Resolving %s", - stoa(&entry->de_peeraddr)); - } -#endif - hp = gethostbyaddr((const char *)&entry->de_peeraddr, - sizeof entry->de_peeraddr, - AF_INET); - } - - if (hp == NULL) { - /* - * Bail if we should TRY_AGAIN. - * Otherwise, we have a permanent failure. - */ - if (h_errno == TRY_AGAIN) - return; - entry->de_done |= DE_FAIL; - } else { - entry->de_done |= DE_GOT; - } - - if (entry->de_done & DE_GOT) { - switch (entry->de_done & DE_NA) { - case DE_NAME: -#ifdef DEBUG - if (debug > 2) - msyslog(LOG_INFO, - "findhostaddr: name resolved."); -#endif - /* - * Use the first address. We don't have any way to - * tell preferences and older gethostbyname() - * implementations only return one. - */ - memmove((char *)&(entry->de_peeraddr), - (char *)hp->h_addr, - sizeof(struct in_addr)); - break; - case DE_ADDR: -#ifdef DEBUG - if (debug > 2) - msyslog(LOG_INFO, - "findhostaddr: address resolved."); -#endif - strncpy(&entry->de_hostname[0], hp->h_name, - sizeof entry->de_hostname); - break; - default: - msyslog(LOG_ERR, "findhostaddr: Bogus de_done: %#x", - entry->de_done); - break; - } - } else { -#ifdef DEBUG - if (debug > 2) { - const char *hes; -#ifndef HAVE_HSTRERROR - char hnum[20]; - - switch (h_errno) { - case HOST_NOT_FOUND: - hes = "Authoritive Answer Host not found"; - break; - case TRY_AGAIN: - hes = "Non-Authoritative Host not found, or SERVERFAIL"; - break; - case NO_RECOVERY: - hes = "Non recoverable errors, FORMERR, REFUSED, NOTIMP"; - break; - case NO_DATA: - hes = "Valid name, no data record of requested type"; - break; - default: - snprintf(hnum, sizeof hnum, "%d", h_errno); - hes = hnum; - break; - } -#else - hes = hstrerror(h_errno); -#endif - - msyslog(LOG_INFO, - "findhostaddr: Failed resolution on <%s>/%s: %s", - entry->de_hostname, stoa(&entry->de_peeraddr), hes); - } -#endif - /* Send a NAK message back to the daemon */ - } - return; -} - - -/* - * openntp - open a socket to the ntp server - */ -static void -openntp(void) -{ - struct sockaddr_in saddr; - - if (sockfd >= 0) - return; - - sockfd = socket(AF_INET, SOCK_DGRAM, 0); - if (sockfd == -1) { - msyslog(LOG_ERR, "socket() failed: %m"); - exit(1); - } - - memset((char *)&saddr, 0, sizeof(saddr)); - saddr.sin_family = AF_INET; - saddr.sin_port = htons(NTP_PORT); /* trash */ - saddr.sin_addr.s_addr = htonl(LOCALHOST); /* garbage */ - - /* - * Make the socket non-blocking. We'll wait with select() - */ -#ifndef SYS_WINNT -# if defined(O_NONBLOCK) - if (fcntl(sockfd, F_SETFL, O_NONBLOCK) == -1) { - msyslog(LOG_ERR, "fcntl(O_NONBLOCK) failed: %m"); - exit(1); - } -# else -# if defined(FNDELAY) - if (fcntl(sockfd, F_SETFL, FNDELAY) == -1) { - msyslog(LOG_ERR, "fcntl(FNDELAY) failed: %m"); - exit(1); - } -# else -# include "Bletch: NEED NON BLOCKING IO" -# endif /* FNDDELAY */ -# endif /* O_NONBLOCK */ -#else /* SYS_WINNT */ - { - int on = 1; - - if (ioctlsocket(sockfd,FIONBIO,(u_long *) &on) == SOCKET_ERROR) { - msyslog(LOG_ERR, "ioctlsocket(FIONBIO) fails: %m"); - exit(1); /* Windows NT - set socket in non-blocking mode */ - } - } -#endif /* SYS_WINNT */ - - if (connect(sockfd, (struct sockaddr *)&saddr, sizeof(saddr)) == -1) { - msyslog(LOG_ERR, "openntp: connect() failed: %m"); - exit(1); - } -} - - -/* - * tell_ntpd: Tell ntpd what we discovered. - */ -static int -tell_ntpd( - struct info_dns_assoc *conf - ) -{ - fd_set fdset; - struct timeval tvout; - struct req_pkt reqpkt; - l_fp ts; - int n; -#ifdef SYS_WINNT - HANDLE hReadWriteEvent = NULL; - BOOL ret; - DWORD NumberOfBytesWritten, NumberOfBytesRead, dwWait; - OVERLAPPED overlap; -#endif /* SYS_WINNT */ - - checkparent(); /* make sure our guy is still running */ - - if (sockfd < 0) - openntp(); - -#ifdef SYS_WINNT - hReadWriteEvent = CreateEvent(NULL, FALSE, FALSE, NULL); -#endif /* SYS_WINNT */ - - /* - * Try to clear out any previously received traffic so it - * doesn't fool us. Note the socket is nonblocking. - */ - tvout.tv_sec = 0; - tvout.tv_usec = 0; - FD_ZERO(&fdset); - FD_SET(sockfd, &fdset); - while (select(sockfd + 1, &fdset, (fd_set *)0, (fd_set *)0, &tvout) > - 0) { - recv(sockfd, (char *)&reqpkt, REQ_LEN_MAC, 0); - FD_ZERO(&fdset); - FD_SET(sockfd, &fdset); - } - - /* - * Make up a request packet with the configuration info - */ - memset((char *)&reqpkt, 0, sizeof(reqpkt)); - - reqpkt.rm_vn_mode = RM_VN_MODE(0, 0, 0); - reqpkt.auth_seq = AUTH_SEQ(1, 0); /* authenticated, no seq */ - reqpkt.implementation = IMPL_XNTPD; /* local implementation */ - reqpkt.request = REQ_HOSTNAME_ASSOCID; /* Hostname for associd */ - reqpkt.err_nitems = ERR_NITEMS(0, 1); /* one item */ - reqpkt.mbz_itemsize = MBZ_ITEMSIZE(sizeof(struct info_dns_assoc)); - memmove(reqpkt.data, (char *)conf, sizeof(struct info_dns_assoc)); - reqpkt.keyid = htonl(req_keyid); - - get_systime(&ts); - L_ADDUF(&ts, SKEWTIME); - HTONL_FP(&ts, &reqpkt.tstamp); - n = 0; - if (sys_authenticate) - n = authencrypt(req_keyid, (u_int32 *)&reqpkt, REQ_LEN_NOMAC); - - /* - * Done. Send it. - */ -#ifndef SYS_WINNT - n = send(sockfd, (char *)&reqpkt, (unsigned)(REQ_LEN_NOMAC + n), 0); - if (n < 0) { - msyslog(LOG_ERR, "send to NTP server failed: %m"); - return 0; /* maybe should exit */ - } -#else - /* In the NT world, documentation seems to indicate that there - * exist _write and _read routines that can be used to do blocking - * I/O on sockets. Problem is these routines require a socket - * handle obtained through the _open_osf_handle C run-time API - * of which there is no explanation in the documentation. We need - * nonblocking write's and read's anyway for our purpose here. - * We're therefore forced to deviate a little bit from the Unix - * model here and use the ReadFile and WriteFile Win32 I/O API's - * on the socket - */ - overlap.Offset = overlap.OffsetHigh = (DWORD)0; - overlap.hEvent = hReadWriteEvent; - ret = WriteFile((HANDLE)sockfd, (char *)&reqpkt, REQ_LEN_NOMAC + n, - (LPDWORD)&NumberOfBytesWritten, (LPOVERLAPPED)&overlap); - if ((ret == FALSE) && (GetLastError() != ERROR_IO_PENDING)) { - msyslog(LOG_ERR, "send to NTP server failed: %m"); - return 0; - } - dwWait = WaitForSingleObject(hReadWriteEvent, (DWORD) TIMEOUT_SEC * 1000); - if ((dwWait == WAIT_FAILED) || (dwWait == WAIT_TIMEOUT)) { - if (dwWait == WAIT_FAILED) - msyslog(LOG_ERR, "WaitForSingleObject failed: %m"); - return 0; - } -#endif /* SYS_WINNT */ - - - /* - * Wait for a response. A weakness of the mode 7 protocol used - * is that there is no way to associate a response with a - * particular request, i.e. the response to this configuration - * request is indistinguishable from that to any other. I should - * fix this some day. In any event, the time out is fairly - * pessimistic to make sure that if an answer is coming back - * at all, we get it. - */ - for (;;) { - FD_ZERO(&fdset); - FD_SET(sockfd, &fdset); - tvout.tv_sec = TIMEOUT_SEC; - tvout.tv_usec = TIMEOUT_USEC; - - n = select(sockfd + 1, &fdset, (fd_set *)0, - (fd_set *)0, &tvout); - - if (n < 0) - { - msyslog(LOG_ERR, "select() fails: %m"); - return 0; - } - else if (n == 0) - { - if(debug) - msyslog(LOG_INFO, "select() returned 0."); - return 0; - } - -#ifndef SYS_WINNT - n = recv(sockfd, (char *)&reqpkt, REQ_LEN_MAC, 0); - if (n <= 0) { - if (n < 0) { - msyslog(LOG_ERR, "recv() fails: %m"); - return 0; - } - continue; - } -#else /* Overlapped I/O used on non-blocking sockets on Windows NT */ - ret = ReadFile((HANDLE)sockfd, (char *)&reqpkt, (DWORD)REQ_LEN_MAC, - (LPDWORD)&NumberOfBytesRead, (LPOVERLAPPED)&overlap); - if ((ret == FALSE) && (GetLastError() != ERROR_IO_PENDING)) { - msyslog(LOG_ERR, "ReadFile() fails: %m"); - return 0; - } - dwWait = WaitForSingleObject(hReadWriteEvent, (DWORD) TIMEOUT_SEC * 1000); - if ((dwWait == WAIT_FAILED) || (dwWait == WAIT_TIMEOUT)) { - if (dwWait == WAIT_FAILED) { - msyslog(LOG_ERR, "WaitForSingleObject fails: %m"); - return 0; - } - continue; - } - n = NumberOfBytesRead; -#endif /* SYS_WINNT */ - - /* - * Got one. Check through to make sure it is what - * we expect. - */ - if (n < RESP_HEADER_SIZE) { - msyslog(LOG_ERR, "received runt response (%d octets)", - n); - continue; - } - - if (!ISRESPONSE(reqpkt.rm_vn_mode)) { -#ifdef DEBUG - if (debug > 1) - msyslog(LOG_INFO, "received non-response packet"); -#endif - continue; - } - - if (ISMORE(reqpkt.rm_vn_mode)) { -#ifdef DEBUG - if (debug > 1) - msyslog(LOG_INFO, "received fragmented packet"); -#endif - continue; - } - - if ( ( (INFO_VERSION(reqpkt.rm_vn_mode) < 2) - || (INFO_VERSION(reqpkt.rm_vn_mode) > NTP_VERSION)) - || INFO_MODE(reqpkt.rm_vn_mode) != MODE_PRIVATE) { -#ifdef DEBUG - if (debug > 1) - msyslog(LOG_INFO, - "version (%d/%d) or mode (%d/%d) incorrect", - INFO_VERSION(reqpkt.rm_vn_mode), - NTP_VERSION, - INFO_MODE(reqpkt.rm_vn_mode), - MODE_PRIVATE); -#endif - continue; - } - - if (INFO_SEQ(reqpkt.auth_seq) != 0) { -#ifdef DEBUG - if (debug > 1) - msyslog(LOG_INFO, - "nonzero sequence number (%d)", - INFO_SEQ(reqpkt.auth_seq)); -#endif - continue; - } - - if (reqpkt.implementation != IMPL_XNTPD || - reqpkt.request != REQ_HOSTNAME_ASSOCID) { -#ifdef DEBUG - if (debug > 1) - msyslog(LOG_INFO, - "implementation (%d/%d) or request (%d/%d) incorrect", - reqpkt.implementation, IMPL_XNTPD, - reqpkt.request, REQ_HOSTNAME_ASSOCID); -#endif - continue; - } - - if (INFO_NITEMS(reqpkt.err_nitems) != 0 || - INFO_MBZ(reqpkt.mbz_itemsize) != 0 || - INFO_ITEMSIZE(reqpkt.mbz_itemsize) != 0) { -#ifdef DEBUG - if (debug > 1) - msyslog(LOG_INFO, - "nitems (%d) mbz (%d) or itemsize (%d) nonzero", - INFO_NITEMS(reqpkt.err_nitems), - INFO_MBZ(reqpkt.mbz_itemsize), - INFO_ITEMSIZE(reqpkt.mbz_itemsize)); -#endif - continue; - } - - n = INFO_ERR(reqpkt.err_nitems); - switch (n) { - case INFO_OKAY: - /* success */ - return 1; - - case INFO_ERR_IMPL: - msyslog(LOG_ERR, - "server reports implementation mismatch!!"); - return 0; - - case INFO_ERR_REQ: - msyslog(LOG_ERR, - "server claims configuration request is unknown"); - return 0; - - case INFO_ERR_FMT: - msyslog(LOG_ERR, - "server indicates a format error occurred(!!)"); - return 0; - - case INFO_ERR_NODATA: - msyslog(LOG_ERR, - "server indicates no data available (shouldn't happen)"); - return 0; - - case INFO_ERR_AUTH: - msyslog(LOG_ERR, - "server returns a permission denied error"); - return 0; - - default: - msyslog(LOG_ERR, - "server returns unknown error code %d", n); - return 0; - } - } -} - - -/* - * doconfigure - attempt to resolve names/addresses - */ -static void -doconfigure( - int dores - ) -{ - register struct dns_entry *de; - register struct dns_entry *deremove; - char *done_msg = ""; - - de = dns_entries; - while (de != NULL) { -#ifdef DEBUG - if (debug > 1) { - msyslog(LOG_INFO, - "doconfigure: name: <%s> peeraddr: %s", - de->de_hostname, stoa(&de->de_peeraddr)); - } -#endif - if (dores && (de->de_hostname[0] == 0 || SOCKNUL(&de->de_peeraddr))) { - findhostaddr(de); - } - - switch (de->de_done & DE_RESULT) { - case DE_PENDING: - done_msg = ""; - break; - case DE_GOT: - done_msg = "succeeded"; - break; - case DE_FAIL: - done_msg = "failed"; - break; - default: - done_msg = "(error - shouldn't happen)"; - break; - } - if (done_msg[0]) { - /* Send the answer */ - if (tell_ntpd(&de->de_info)) { -#ifdef DEBUG - if (debug > 1) { - msyslog(LOG_INFO, - "DNS resolution on <%s>/%s %s", - de->de_hostname, stoa(&de->de_peeraddr), - done_msg); - } -#endif - deremove = de; - de = deremove->de_next; - removeentry(deremove); - } - } else { - de = de->de_next; - } - } -} diff --git a/ntpd/ntp_scanner.c b/ntpd/ntp_scanner.c index 8fcbb4e23..7a258ea0f 100644 --- a/ntpd/ntp_scanner.c +++ b/ntpd/ntp_scanner.c @@ -395,7 +395,7 @@ quote_if_needed(char *str) || strchr(str, ' ') != NULL)) { snprintf(ret, octets, "\"%s\"", str); } else - strncpy(ret, str, octets); + strlcpy(ret, str, octets); return ret; } diff --git a/ntpd/ntp_signd.c b/ntpd/ntp_signd.c index ec29863a5..2ba11d086 100644 --- a/ntpd/ntp_signd.c +++ b/ntpd/ntp_signd.c @@ -40,7 +40,7 @@ ux_socket_connect(const char *name) ZERO(addr); addr.sun_family = AF_UNIX; - strncpy(addr.sun_path, name, sizeof(addr.sun_path)); + strlcpy(addr.sun_path, name, sizeof(addr.sun_path)); fd = socket(AF_UNIX, SOCK_STREAM, 0); if (fd == -1) { diff --git a/ntpd/ntp_util.c b/ntpd/ntp_util.c index d5c65d512..f049582f1 100644 --- a/ntpd/ntp_util.c +++ b/ntpd/ntp_util.c @@ -359,27 +359,27 @@ stats_config( if (!ExpandEnvironmentStrings(invalue, newvalue, MAX_PATH)) { switch (item) { case STATS_FREQ_FILE: - strncpy(parameter, "STATS_FREQ_FILE", + strlcpy(parameter, "STATS_FREQ_FILE", sizeof(parameter)); break; case STATS_LEAP_FILE: - strncpy(parameter, "STATS_LEAP_FILE", + strlcpy(parameter, "STATS_LEAP_FILE", sizeof(parameter)); break; case STATS_STATSDIR: - strncpy(parameter, "STATS_STATSDIR", + strlcpy(parameter, "STATS_STATSDIR", sizeof(parameter)); break; case STATS_PID_FILE: - strncpy(parameter, "STATS_PID_FILE", + strlcpy(parameter, "STATS_PID_FILE", sizeof(parameter)); break; default: - strncpy(parameter, "UNKNOWN", + strlcpy(parameter, "UNKNOWN", sizeof(parameter)); break; } @@ -1018,7 +1018,7 @@ getauthkeys( _MAX_PATH)) { msyslog(LOG_ERR, "ExpandEnvironmentStrings(KEY_FILE) failed: %m"); - strncpy(key_file_name, keyfile, _MAX_PATH); + strlcpy(key_file_name, keyfile, _MAX_PATH); } key_file_name = erealloc(key_file_name, 1 + strlen(key_file_name)); @@ -1069,7 +1069,7 @@ char * fstostr( #ifdef WAIT_FOR_NTP_CRYPTO_C_CALLERS_ABLE_TO_HANDLE_MORE_THAN_20_CHARS msnprintf(buf, LIB_BUFLENGTH, "gmtime: %m"); #else - strncpy(buf, "gmtime() error", LIB_BUFLENGTH); + strlcpy(buf, "gmtime() error", LIB_BUFLENGTH); #endif else snprintf(buf, LIB_BUFLENGTH, "%04d%02d%02d%02d%02d", diff --git a/ntpd/refclock_acts.c b/ntpd/refclock_acts.c index 2d97f2d1a..ae14ccc48 100644 --- a/ntpd/refclock_acts.c +++ b/ntpd/refclock_acts.c @@ -381,7 +381,7 @@ acts_message( /* * Extract the first token in the line. */ - strncpy(tbuf, msg, sizeof(tbuf) - 1); + strlcpy(tbuf, msg, sizeof(tbuf)); strtok(tbuf, " "); switch (up->state) { @@ -895,7 +895,7 @@ acts_timecode( if (up->msgcnt == 0) return; - strncpy(pp->a_lastcode, str, sizeof(pp->a_lastcode) - 1); + strlcpy(pp->a_lastcode, str, sizeof(pp->a_lastcode)); pp->lencode = strlen(pp->a_lastcode); if (!refclock_process(pp)) { refclock_report(peer, CEVNT_BADTIME); diff --git a/ntpd/refclock_arbiter.c b/ntpd/refclock_arbiter.c index 34ca9b38f..738be508d 100644 --- a/ntpd/refclock_arbiter.c +++ b/ntpd/refclock_arbiter.c @@ -248,7 +248,7 @@ arb_receive( peer = rbufp->recv_peer; pp = peer->procptr; up = pp->unitptr; - temp = refclock_gtlin(rbufp, tbuf, BMAX, &trtmp); + temp = refclock_gtlin(rbufp, tbuf, sizeof(tbuf), &trtmp); /* * Note we get a buffer and timestamp for both a and , @@ -289,7 +289,7 @@ arb_receive( return; } else if (!strncmp(tbuf, "SR", 2)) { - strncpy(up->status, tbuf + 2, + strlcpy(up->status, tbuf + 2, sizeof(up->status)); if (pp->sloppyclockflag & CLK_FLAG4) write(pp->io.fd, "LA", 2); @@ -298,25 +298,25 @@ arb_receive( return; } else if (!strncmp(tbuf, "LA", 2)) { - strncpy(up->latlon, tbuf + 2, sizeof(up->latlon)); + strlcpy(up->latlon, tbuf + 2, sizeof(up->latlon)); write(pp->io.fd, "LO", 2); return; } else if (!strncmp(tbuf, "LO", 2)) { - strcat(up->latlon, " "); - strcat(up->latlon, tbuf + 2); + strlcat(up->latlon, " ", sizeof(up->latlon)); + strlcat(up->latlon, tbuf + 2, sizeof(up->latlon)); write(pp->io.fd, "LH", 2); return; } else if (!strncmp(tbuf, "LH", 2)) { - strcat(up->latlon, " "); - strcat(up->latlon, tbuf + 2); + strlcat(up->latlon, " ", sizeof(up->latlon)); + strlcat(up->latlon, tbuf + 2, sizeof(up->latlon)); write(pp->io.fd, "DB", 2); return; } else if (!strncmp(tbuf, "DB", 2)) { - strcat(up->latlon, " "); - strcat(up->latlon, tbuf + 2); + strlcat(up->latlon, " ", sizeof(up->latlon)); + strlcat(up->latlon, tbuf + 2, sizeof(up->latlon)); record_clock_stats(&peer->srcadr, up->latlon); #ifdef DEBUG if (debug) @@ -342,9 +342,9 @@ arb_receive( /* * Timecode format B5: "i yy ddd hh:mm:ss.000 " */ - strncpy(pp->a_lastcode, tbuf, BMAX); + strlcpy(pp->a_lastcode, tbuf, sizeof(pp->a_lastcode)); pp->a_lastcode[LENARB - 2] = up->qualchar; - strcat(pp->a_lastcode, up->status); + strlcat(pp->a_lastcode, up->status, sizeof(pp->a_lastcode)); pp->lencode = strlen(pp->a_lastcode); syncchar = ' '; if (sscanf(pp->a_lastcode, "%c%2d %3d %2d:%2d:%2d", diff --git a/ntpd/refclock_chu.c b/ntpd/refclock_chu.c index 88bb35b3e..e6a1a3c52 100644 --- a/ntpd/refclock_chu.c +++ b/ntpd/refclock_chu.c @@ -526,7 +526,7 @@ chu_start( */ peer->precision = PRECISION; pp->clockdesc = DESCRIPTION; - strncpy(up->ident, "CHU", sizeof(up->ident)); + strlcpy(up->ident, "CHU", sizeof(up->ident)); memcpy(&pp->refid, up->ident, 4); DTOLFP(CHAR, &up->charstamp); #ifdef HAVE_AUDIO diff --git a/ntpd/refclock_hpgps.c b/ntpd/refclock_hpgps.c index 4be8a7164..1d26d2552 100644 --- a/ntpd/refclock_hpgps.c +++ b/ntpd/refclock_hpgps.c @@ -331,7 +331,7 @@ hpgps_receive( * */ - strncpy(prompt, pp->a_lastcode, sizeof(prompt)); + strlcpy(prompt, pp->a_lastcode, sizeof(prompt)); tcp = strrchr(pp->a_lastcode,'>'); if (tcp == NULL) tcp = pp->a_lastcode; diff --git a/ntpd/refclock_jjy.c b/ntpd/refclock_jjy.c index d648587df..9514e6cf5 100644 --- a/ntpd/refclock_jjy.c +++ b/ntpd/refclock_jjy.c @@ -575,22 +575,19 @@ jjy_receive ( struct recvbuf *rbufp ) if ( up->lineerror != 0 ) { refclock_report ( peer, CEVNT_BADREPLY ) ; - strncpy ( sLogText, "BAD REPLY [", + strlcpy ( sLogText, "BAD REPLY [", sizeof( sLogText ) ) ; if ( up->linediscipline == LDISC_RAW ) { - strncat ( sLogText, up->rawbuf, - sizeof( sLogText ) - - strlen ( sLogText ) - 1 ) ; + strlcat ( sLogText, up->rawbuf, + sizeof( sLogText ) ) ; } else { - strncat ( sLogText, pp->a_lastcode, - sizeof( sLogText ) - - strlen ( sLogText ) - 1 ) ; + strlcat ( sLogText, pp->a_lastcode, + sizeof( sLogText ) ) ; } sLogText[MAX_LOGTEXT-1] = 0 ; if ( strlen ( sLogText ) < MAX_LOGTEXT - 2 ) - strncat ( sLogText, "]", - sizeof( sLogText ) - - strlen ( sLogText ) - 1 ) ; + strlcat ( sLogText, "]", + sizeof( sLogText ) ) ; record_clock_stats ( &peer->srcadr, sLogText ) ; return ; } @@ -1379,7 +1376,7 @@ printableString ( char *sOutput, int iOutputLen, char *sInput, int iInputLen ) n = strlen( printableControlChar[sInput[i] & 0xFF] ) ; if ( j + n + 1 >= OutputLen ) break ; - strncpy( sOutput + j, + strlcpy( sOutput + j, printableControlChar[sInput[i] & 0xFF], OutputLen - j ) ; } else { diff --git a/ntpd/refclock_neoclock4x.c b/ntpd/refclock_neoclock4x.c index 4660ea27a..1af174806 100644 --- a/ntpd/refclock_neoclock4x.c +++ b/ntpd/refclock_neoclock4x.c @@ -317,10 +317,10 @@ neoclock4x_start(int unit, up->leap_status = 0; up->unit = unit; - strncpy(up->firmware, "?", sizeof(up->firmware)); + strlcpy(up->firmware, "?", sizeof(up->firmware)); up->firmwaretag = '?'; - strncpy(up->serial, "?", sizeof(up->serial)); - strncpy(up->radiosignal, "?", sizeof(up->radiosignal)); + strlcpy(up->serial, "?", sizeof(up->serial)); + strlcpy(up->radiosignal, "?", sizeof(up->radiosignal)); up->timesource = '?'; up->dststatus = '?'; up->quarzstatus = '?'; @@ -336,7 +336,7 @@ neoclock4x_start(int unit, #if defined(NEOCLOCK4X_FIRMWARE) #if NEOCLOCK4X_FIRMWARE == NEOCLOCK4X_FIRMWARE_VERSION_A - strncpy(up->firmware, "(c) 2002 NEOL S.A. FRANCE / L0.01 NDF:A:* (compile time)", + strlcpy(up->firmware, "(c) 2002 NEOL S.A. FRANCE / L0.01 NDF:A:* (compile time)", sizeof(up->firmware)); up->firmwaretag = 'A'; #else @@ -932,13 +932,13 @@ neol_query_firmware(int fd, if(read_errors > 5) { msyslog(LOG_ERR, "NeoClock4X(%d): can't read firmware version (timeout)", unit); - strncpy(tmpbuf, "unknown due to timeout", sizeof(tmpbuf)); + strlcpy(tmpbuf, "unknown due to timeout", sizeof(tmpbuf)); break; } if(chars_read > 500) { msyslog(LOG_ERR, "NeoClock4X(%d): can't read firmware version (garbage)", unit); - strncpy(tmpbuf, "unknown due to garbage input", sizeof(tmpbuf)); + strlcpy(tmpbuf, "unknown due to garbage input", sizeof(tmpbuf)); break; } if(-1 == read(fd, &c, 1)) @@ -964,7 +964,7 @@ neol_query_firmware(int fd, if(0xA9 != c) /* wait for (c) char in input stream */ continue; - strncpy(tmpbuf, "(c)", sizeof(tmpbuf)); + strlcpy(tmpbuf, "(c)", sizeof(tmpbuf)); len = 3; init = 0; continue; @@ -1009,10 +1009,10 @@ neol_query_firmware(int fd, else { msyslog(LOG_ERR, "NeoClock4X(%d): can't query firmware version", unit); - strncpy(tmpbuf, "unknown error", sizeof(tmpbuf)); + strlcpy(tmpbuf, "unknown error", sizeof(tmpbuf)); } - strncpy(firmware, tmpbuf, maxlen); - firmware[maxlen] = '\0'; + if (strlcpy(firmware, tmpbuf, maxlen) >= maxlen) + strlcpy(firmware, "buffer too small", maxlen); if(flag) { diff --git a/ntpd/refclock_oncore.c b/ntpd/refclock_oncore.c index dd57f8cd3..77601d48c 100644 --- a/ntpd/refclock_oncore.c +++ b/ntpd/refclock_oncore.c @@ -1441,17 +1441,17 @@ oncore_receive( oncore_log_f(instance, LOG_DEBUG, ">>> %d bytes available", rbufp->recv_length); - strncpy(Msg, ">>>", sizeof(Msg)); + strlcpy(Msg, ">>>", sizeof(Msg)); for (i = 0; i < rbufp->recv_length; i++) { snprintf(Msg2, sizeof(Msg2), "%02x ", p[i]); - strncat(Msg, Msg2, sizeof(Msg)); + strlcat(Msg, Msg2, sizeof(Msg)); } oncore_log(instance, LOG_DEBUG, Msg); - strncpy(Msg, ">>>", sizeof(Msg)); + strlcpy(Msg, ">>>", sizeof(Msg)); for (i = 0; i < rbufp->recv_length; i++) { snprintf(Msg2, sizeof(Msg2), "%03o ", p[i]); - strncat(Msg, Msg2, sizeof(Msg)); + strlcat(Msg, Msg2, sizeof(Msg)); } oncore_log(instance, LOG_DEBUG, Msg); } @@ -1554,7 +1554,7 @@ oncore_consume( for (i = 4; i < l; i++) { snprintf(Msg2, sizeof(Msg2), "%03o ", rcvbuf[i]); - strncat(Msg, Msg2, sizeof(Msg)); + strlcat(Msg, Msg2, sizeof(Msg)); } oncore_log(instance, LOG_DEBUG, Msg); } @@ -1805,10 +1805,10 @@ oncore_get_timestamp( snprintf(f4, sizeof(f4), "%3d", (s_char)instance->BEHn[25]); } else { - strncpy(f1, "x", sizeof(f1)); - strncpy(f2, "x", sizeof(f2)); - strncpy(f3, "xx", sizeof(f3)); - strncpy(f4, "xxx", sizeof(f4)); + strlcpy(f1, "x", sizeof(f1)); + strlcpy(f2, "x", sizeof(f2)); + strlcpy(f3, "xx", sizeof(f3)); + strlcpy(f4, "xxx", sizeof(f4)); } snprintf(Msg, sizeof(Msg), /* MAX length 128, currently at 127 */ "%u.%09lu %d %d %2d %2d %2d %2ld rstat %02x dop %4.1f nsat %2d,%d traim %d,%s,%s sigma %s neg-sawtooth %s sat %d%d%d%d%d%d%d%d", @@ -1838,10 +1838,10 @@ oncore_get_timestamp( snprintf(f4, sizeof(f4), "%3d", (s_char)instance->BEHn[14]); } else { - strncpy(f1, "x", sizeof(f1)); - strncpy(f2, "x", sizeof(f2)); - strncpy(f3, "xx", sizeof(f3)); - strncpy(f4, "xxx", sizeof(f4)); + strlcpy(f1, "x", sizeof(f1)); + strlcpy(f2, "x", sizeof(f2)); + strlcpy(f3, "xx", sizeof(f3)); + strlcpy(f4, "xxx", sizeof(f4)); } snprintf(Msg, sizeof(Msg), "%u.%09lu %d %d %2d %2d %2d %2ld rstat %02x dop %4.1f nsat %2d,%d traim %d,%s,%s sigma %s neg-sawtooth %s sat %d%d%d%d%d%d%d%d%d%d%d%d", @@ -1925,13 +1925,12 @@ oncore_msg_any( for(i = 2; i < len && i < 2400 ; i++) { snprintf(Msg2, sizeof(Msg2), "%02x", buf[i]); - strncpy(Msg, Msg2, sizeof(Msg)); - + strlcat(Msg, Msg2, sizeof(Msg)); } oncore_log(instance, LOG_DEBUG, Msg); return; } else { - strncat(Msg, "##", sizeof(Msg)); + strlcpy(Msg, "##", sizeof(Msg)); qlim = Msg + sizeof(Msg) - 3; for (p = fmt, q = Msg + 2; q < qlim && *p; ) { *q++ = *p++; @@ -1944,7 +1943,7 @@ oncore_msg_any( i = 4; for (p = fmt; *p; p++) { snprintf(Msg2, "%02x", buf[i++]); - strncat(Msg, Msg2, sizeof(Msg)); + strlcat(Msg, Msg2, sizeof(Msg)); } oncore_log(instance, LOG_DEBUG, Msg); } @@ -3620,7 +3619,7 @@ oncore_print_Cb( *(cp+5)); for (ii = 0; ii < 33; ii++) { snprintf(Msg2, sizeof(Msg2), " %d", *(cp+ii)); - strncat(Msg, Msg2, sizeof(Msg)); + strlcat(Msg, Msg2, sizeof(Msg)); } oncore_log(instance, LOG_DEBUG, Msg); diff --git a/ntpd/refclock_parse.c b/ntpd/refclock_parse.c index a911a49c1..2bbdbd43c 100644 --- a/ntpd/refclock_parse.c +++ b/ntpd/refclock_parse.c @@ -2418,41 +2418,42 @@ parsestate( if (flagstrings[i].bit & lstate) { if (s != t) - strncpy(t, "; ", BUFFER_SIZES(buffer, t, size)); - strncat(t, flagstrings[i].name, BUFFER_SIZES(buffer, t, size)); - t += strlen(t); + strlcpy(t, "; ", BUFFER_SIZES(buffer, t, size)); + if (strlcat(t, flagstrings[i].name, BUFFER_SIZES(buffer, t, size)) < + BUFFER_SIZES(buffer, t, size)) + t += strlen(t); } i++; } if (lstate & (PARSEB_S_LEAP|PARSEB_S_ANTENNA|PARSEB_S_PPS|PARSEB_S_POSITION)) { - if (s != t) - strncpy(t, "; ", BUFFER_SIZES(buffer, t, size)); - - t += strlen(t); - - strncpy(t, "(", BUFFER_SIZES(buffer, t, size)); + if (s != t && + strlcpy(t, "; ", BUFFER_SIZES(buffer, t, size)) < + BUFFER_SIZES(buffer, t, size)) + t += strlen(t); - s = t = t + strlen(t); + if (strlcpy(t, "(", BUFFER_SIZES(buffer, t, size)) < + BUFFER_SIZES(buffer, t, size)) + s = t = t + strlen(t); i = 0; while (sflagstrings[i].bit) { if (sflagstrings[i].bit & lstate) { - if (t != s) - { - strncpy(t, "; ", BUFFER_SIZES(buffer, t, size)); + if (t != s && + strlcpy(t, "; ", BUFFER_SIZES(buffer, t, size)) < + BUFFER_SIZES(buffer, t, size)) t += 2; - } - strncpy(t, sflagstrings[i].name, BUFFER_SIZES(buffer, t, size)); - t += strlen(t); + if (strlcpy(t, sflagstrings[i].name, BUFFER_SIZES(buffer, t, size)) < + BUFFER_SIZES(buffer, t, size)) + t += strlen(t); } i++; } - strncpy(t, ")", BUFFER_SIZES(buffer, t, size)); + strlcpy(t, ")", BUFFER_SIZES(buffer, t, size)); } return buffer; } @@ -2492,8 +2493,8 @@ parsestatus( if (flagstrings[i].bit & lstate) { if (buffer[0]) - strncat(buffer, "; ", size); - strncat(buffer, flagstrings[i].name, size); + strlcat(buffer, "; ", size); + strlcat(buffer, flagstrings[i].name, size); } i++; } @@ -3111,7 +3112,7 @@ parse_start( msyslog(LOG_ERR, "PARSE receiver #%d: parse_start: io sub system initialisation failed.", CLK_UNIT(parse->peer)); parse_shutdown(CLK_UNIT(parse->peer), peer); /* let our cleaning staff do the work */ return 0; /* well, ok - special initialisation broke */ - } + } parse->generic->io.clock_recv = parse->binding->bd_receive; /* pick correct receive routine */ parse->generic->io.io_input = parse->binding->bd_io_input; /* pick correct input routine */ @@ -3149,9 +3150,12 @@ parse_start( parse_shutdown(CLK_UNIT(parse->peer), peer); /* let our cleaning staff do the work */ return 0; /* well, ok - special initialisation broke */ } - - strncpy(tmp_ctl.parseformat.parse_buffer, parse->parse_type->cl_format, sizeof(tmp_ctl.parseformat.parse_buffer)); - tmp_ctl.parseformat.parse_count = strlen(tmp_ctl.parseformat.parse_buffer); + + tmp_ctl.parseformat.parse_count = strlcpy(tmp_ctl.parseformat.parse_buffer, + parse->parse_type->cl_format, + sizeof(tmp_ctl.parseformat.parse_buffer)); + if (tmp_ctl.parseformat.parse_count >= sizeof(tmp_ctl.parseformat.parse_buffer)) + tmp_ctl.parseformat.parse_count = sizeof(tmp_ctl.parseformat.parse_buffer) - 1; if (!PARSE_SETFMT(parse, &tmp_ctl)) { @@ -3439,7 +3443,7 @@ parse_control( if (parse->timedata.parse_time.fp.l_ui == 0) { - strncpy(tt, "\"", BUFFER_SIZES(start, tt, 128)); + strlcpy(tt, "\"", BUFFER_SIZES(start, tt, 128)); } else { @@ -3465,7 +3469,7 @@ parse_control( (void) parsestate(tmpctl.parsegettc.parse_state, tt, BUFFER_SIZES(start, tt, 512)); - strncat(tt, "\"", BUFFER_SIZES(start, tt, 512)); + strlcat(tt, "\"", BUFFER_SIZES(start, tt, 512)); if (tmpctl.parsegettc.parse_count) mkascii(outstatus+strlen(outstatus), (int)(sizeof(outstatus)- strlen(outstatus) - 1), @@ -3485,8 +3489,8 @@ parse_control( tt = add_var(&out->kv_list, 80, RO|DEF); snprintf(tt, 80, "refclock_format=\""); - strncat(tt, tmpctl.parseformat.parse_buffer, tmpctl.parseformat.parse_count); - strncat(tt,"\"", 80); + strlcat(tt, tmpctl.parseformat.parse_buffer, 80); + strlcat(tt,"\"", 80); } /* @@ -3494,7 +3498,7 @@ parse_control( */ start = tt = add_var(&out->kv_list, LEN_STATES, RO|DEF); - strncpy(tt, "refclock_states=\"", LEN_STATES); + strlcpy(tt, "refclock_states=\"", LEN_STATES); tt += strlen(tt); for (i = 0; i <= CEVNT_MAX; i++) @@ -3529,7 +3533,7 @@ parse_control( (int)(percent / 100), (int)(percent % 100)); if ((count = strlen(item)) < (LEN_STATES - 40 - (tt - start))) { - strncpy(tt, item, BUFFER_SIZES(start, tt, LEN_STATES)); + strlcpy(tt, item, BUFFER_SIZES(start, tt, LEN_STATES)); tt += count; } sum += s_time; @@ -4218,7 +4222,7 @@ gps16x_message( *p++ = ' '; } - strncat(p, (const char *)s->string, sizeof(buffer)); + strlcat(p, (const char *)s->string, sizeof(buffer)); } s++; } @@ -4228,7 +4232,7 @@ gps16x_message( } else { - strncat(buffer, "\"", sizeof(buffer)); + strlcat(buffer, "\"", sizeof(buffer)); } set_var(&parse->kv, buffer, strlen(buffer)+1, RO|DEF); @@ -4288,12 +4292,12 @@ gps16x_message( switch (antinfo.status) { case ANT_INVALID: - strncat(p, "", BUFFER_SIZE(buffer, p)); + strlcat(p, "", BUFFER_SIZE(buffer, p)); p += strlen(p); break; case ANT_DISCONN: - strncat(p, "DISCONNECTED since ", BUFFER_SIZE(buffer, p)); + strlcat(p, "DISCONNECTED since ", BUFFER_SIZE(buffer, p)); NLOG(NLOG_CLOCKSTATUS) ERR(ERR_BADSTATUS) msyslog(LOG_ERR,"PARSE receiver #%d: ANTENNA FAILURE: %s", @@ -4305,7 +4309,7 @@ gps16x_message( break; case ANT_RECONN: - strncat(p, "RECONNECTED on ", BUFFER_SIZE(buffer, p)); + strlcat(p, "RECONNECTED on ", BUFFER_SIZE(buffer, p)); p += strlen(p); mbg_tm_str(&p, &antinfo.tm_reconn, BUFFER_SIZE(buffer, p)); snprintf(p, BUFFER_SIZE(buffer, p), ", reconnect clockoffset %c%ld.%07ld s, disconnect time ", @@ -4323,7 +4327,7 @@ gps16x_message( break; } - strncat(p, "\"", BUFFER_SIZE(buffer, p)); + strlcat(p, "\"", BUFFER_SIZE(buffer, p)); set_var(&parse->kv, buffer, strlen(buffer)+1, RO|DEF); } @@ -4344,24 +4348,24 @@ gps16x_message( int i; p = buffer; - strncpy(buffer, "gps_tot_51=\"", BUFFER_SIZE(buffer, p)); + strlcpy(buffer, "gps_tot_51=\"", BUFFER_SIZE(buffer, p)); p += strlen(p); mbg_tgps_str(&p, &cfgh.tot_51, BUFFER_SIZE(buffer, p)); - strncpy(p, "\"", BUFFER_SIZE(buffer, p)); + strlcpy(p, "\"", BUFFER_SIZE(buffer, p)); set_var(&parse->kv, buffer, strlen(buffer)+1, RO); p = buffer; - strncpy(buffer, "gps_tot_63=\"", BUFFER_SIZE(buffer, p)); + strlcpy(buffer, "gps_tot_63=\"", BUFFER_SIZE(buffer, p)); p += strlen(p); mbg_tgps_str(&p, &cfgh.tot_63, BUFFER_SIZE(buffer, p)); - strncpy(p, "\"", BUFFER_SIZE(buffer, p)); + strlcpy(p, "\"", BUFFER_SIZE(buffer, p)); set_var(&parse->kv, buffer, strlen(buffer)+1, RO); p = buffer; - strncpy(buffer, "gps_t0a=\"", BUFFER_SIZE(buffer, p)); + strlcpy(buffer, "gps_t0a=\"", BUFFER_SIZE(buffer, p)); p += strlen(p); mbg_tgps_str(&p, &cfgh.t0a, BUFFER_SIZE(buffer, p)); - strncpy(p, "\"", BUFFER_SIZE(buffer, p)); + strlcpy(p, "\"", BUFFER_SIZE(buffer, p)); set_var(&parse->kv, buffer, strlen(buffer)+1, RO); for (i = MIN_SVNO; i < MAX_SVNO; i++) @@ -4372,16 +4376,16 @@ gps16x_message( switch (cfgh.cfg[i] & 0x7) { case 0: - strncpy(p, "BLOCK I", BUFFER_SIZE(buffer, p)); + strlcpy(p, "BLOCK I", BUFFER_SIZE(buffer, p)); break; case 1: - strncpy(p, "BLOCK II", BUFFER_SIZE(buffer, p)); + strlcpy(p, "BLOCK II", BUFFER_SIZE(buffer, p)); break; default: - strncpy(p, "bad CFG", BUFFER_SIZE(buffer, p)); + strlcpy(p, "bad CFG", BUFFER_SIZE(buffer, p)); break; } - strncat(p, "\"", BUFFER_SIZE(buffer, p)); + strlcat(p, "\"", BUFFER_SIZE(buffer, p)); set_var(&parse->kv, buffer, strlen(buffer)+1, RO); p = buffer; @@ -4390,28 +4394,28 @@ gps16x_message( switch ((cfgh.health[i] >> 5) & 0x7 ) { case 0: - strncpy(p, "OK;", BUFFER_SIZE(buffer, p)); + strlcpy(p, "OK;", BUFFER_SIZE(buffer, p)); break; case 1: - strncpy(p, "PARITY;", BUFFER_SIZE(buffer, p)); + strlcpy(p, "PARITY;", BUFFER_SIZE(buffer, p)); break; case 2: - strncpy(p, "TLM/HOW;", BUFFER_SIZE(buffer, p)); + strlcpy(p, "TLM/HOW;", BUFFER_SIZE(buffer, p)); break; case 3: - strncpy(p, "Z-COUNT;", BUFFER_SIZE(buffer, p)); + strlcpy(p, "Z-COUNT;", BUFFER_SIZE(buffer, p)); break; case 4: - strncpy(p, "SUBFRAME 1,2,3;", BUFFER_SIZE(buffer, p)); + strlcpy(p, "SUBFRAME 1,2,3;", BUFFER_SIZE(buffer, p)); break; case 5: - strncpy(p, "SUBFRAME 4,5;", BUFFER_SIZE(buffer, p)); + strlcpy(p, "SUBFRAME 4,5;", BUFFER_SIZE(buffer, p)); break; case 6: - strncpy(p, "UPLOAD BAD;", BUFFER_SIZE(buffer, p)); + strlcpy(p, "UPLOAD BAD;", BUFFER_SIZE(buffer, p)); break; case 7: - strncpy(p, "DATA BAD;", BUFFER_SIZE(buffer, p)); + strlcpy(p, "DATA BAD;", BUFFER_SIZE(buffer, p)); break; } @@ -4420,25 +4424,25 @@ gps16x_message( switch (cfgh.health[i] & 0x1F) { case 0: - strncpy(p, "SIGNAL OK", BUFFER_SIZE(buffer, p)); + strlcpy(p, "SIGNAL OK", BUFFER_SIZE(buffer, p)); break; case 0x1C: - strncpy(p, "SV TEMP OUT", BUFFER_SIZE(buffer, p)); + strlcpy(p, "SV TEMP OUT", BUFFER_SIZE(buffer, p)); break; case 0x1D: - strncpy(p, "SV WILL BE TEMP OUT", BUFFER_SIZE(buffer, p)); + strlcpy(p, "SV WILL BE TEMP OUT", BUFFER_SIZE(buffer, p)); break; case 0x1E: break; case 0x1F: - strncpy(p, "MULTIPLE ERRS", BUFFER_SIZE(buffer, p)); + strlcpy(p, "MULTIPLE ERRS", BUFFER_SIZE(buffer, p)); break; default: - strncpy(p, "TRANSMISSION PROBLEMS", BUFFER_SIZE(buffer, p)); + strlcpy(p, "TRANSMISSION PROBLEMS", BUFFER_SIZE(buffer, p)); break; } - strncat(p, "\"", sizeof(buffer)); + strlcat(p, "\"", sizeof(buffer)); set_var(&parse->kv, buffer, strlen(buffer)+1, RO); } } @@ -4463,14 +4467,14 @@ gps16x_message( if (utc.valid) { - strncpy(p, "gps_utc_correction=\"", sizeof(buffer)); + strlcpy(p, "gps_utc_correction=\"", sizeof(buffer)); p += strlen(p); mk_utcinfo(p, utc.t0t.wn, utc.WNlsf, utc.DNt, utc.delta_tls, utc.delta_tlsf, BUFFER_SIZE(buffer, p)); - strncat(p, "\"", BUFFER_SIZE(buffer, p)); + strlcat(p, "\"", BUFFER_SIZE(buffer, p)); } else { - strncpy(p, "gps_utc_correction=\"\"", BUFFER_SIZE(buffer, p)); + strlcpy(p, "gps_utc_correction=\"\"", BUFFER_SIZE(buffer, p)); } set_var(&parse->kv, buffer, strlen(buffer)+1, RO|DEF); } @@ -4494,7 +4498,7 @@ gps16x_message( snprintf(buffer, sizeof(buffer), "gps_message=\"%s\"", buffer1); } else - strncpy(buffer, "gps_message=", sizeof(buffer)); + strlcpy(buffer, "gps_message=", sizeof(buffer)); set_var(&parse->kv, buffer, strlen(buffer)+1, RO|DEF); } @@ -5362,7 +5366,7 @@ trimbletsip_message( break; case CMD_RBEST4: - strncpy(t, "mode: ", BUFFER_SIZE(pbuffer, t)); + strlcpy(t, "mode: ", BUFFER_SIZE(pbuffer, t)); t += strlen(t); switch (mb(0) & 0xF) { @@ -5371,22 +5375,22 @@ trimbletsip_message( break; case 1: - strncpy(t, "0D", BUFFER_SIZE(pbuffer, t)); + strlcpy(t, "0D", BUFFER_SIZE(pbuffer, t)); break; case 3: - strncpy(t, "2D", BUFFER_SIZE(pbuffer, t)); + strlcpy(t, "2D", BUFFER_SIZE(pbuffer, t)); break; case 4: - strncpy(t, "3D", BUFFER_SIZE(pbuffer, t)); + strlcpy(t, "3D", BUFFER_SIZE(pbuffer, t)); break; } t += strlen(t); if (mb(0) & 0x10) - strncpy(t, "-MANUAL, ", BUFFER_SIZE(pbuffer, t)); + strlcpy(t, "-MANUAL, ", BUFFER_SIZE(pbuffer, t)); else - strncpy(t, "-AUTO, ", BUFFER_SIZE(pbuffer, t)); + strlcpy(t, "-AUTO, ", BUFFER_SIZE(pbuffer, t)); t += strlen(t); snprintf(t, BUFFER_SIZE(pbuffer, t), "satellites %02d %02d %02d %02d, PDOP %.2f, HDOP %.2f, VDOP %.2f, TDOP %.2f", @@ -5425,28 +5429,28 @@ trimbletsip_message( snprintf(t, BUFFER_SIZE(pbuffer, t), "illegal value 0x%02x", mb(0) & 0xFF); break; case 0x00: - strncpy(t, "doing position fixes", BUFFER_SIZE(pbuffer, t)); + strlcpy(t, "doing position fixes", BUFFER_SIZE(pbuffer, t)); break; case 0x01: - strncpy(t, "no GPS time yet", BUFFER_SIZE(pbuffer, t)); + strlcpy(t, "no GPS time yet", BUFFER_SIZE(pbuffer, t)); break; case 0x03: - strncpy(t, "PDOP too high", BUFFER_SIZE(pbuffer, t)); + strlcpy(t, "PDOP too high", BUFFER_SIZE(pbuffer, t)); break; case 0x08: - strncpy(t, "no usable satellites", BUFFER_SIZE(pbuffer, t)); + strlcpy(t, "no usable satellites", BUFFER_SIZE(pbuffer, t)); break; case 0x09: - strncpy(t, "only ONE usable satellite", BUFFER_SIZE(pbuffer, t)); + strlcpy(t, "only ONE usable satellite", BUFFER_SIZE(pbuffer, t)); break; case 0x0A: - strncpy(t, "only TWO usable satellites", BUFFER_SIZE(pbuffer, t)); + strlcpy(t, "only TWO usable satellites", BUFFER_SIZE(pbuffer, t)); break; case 0x0B: - strncpy(t, "only THREE usable satellites", BUFFER_SIZE(pbuffer, t)); + strlcpy(t, "only THREE usable satellites", BUFFER_SIZE(pbuffer, t)); break; case 0x0C: - strncpy(t, "the chosen satellite is unusable", BUFFER_SIZE(pbuffer, t)); + strlcpy(t, "the chosen satellite is unusable", BUFFER_SIZE(pbuffer, t)); break; } @@ -5515,13 +5519,13 @@ trimbletsip_message( short dtlsf = getshort((unsigned char *)&mb(24)); if ((int)t0t != 0) - { - mk_utcinfo(t, wnt, wnlsf, dn, dtls, dtlsf, BUFFER_SIZE(pbuffer, t)); - } + { + mk_utcinfo(t, wnt, wnlsf, dn, dtls, dtlsf, BUFFER_SIZE(pbuffer, t)); + } else - { - strncpy(t, "", BUFFER_SIZE(pbuffer, t)); - } + { + strlcpy(t, "", BUFFER_SIZE(pbuffer, t)); + } } break; @@ -5550,11 +5554,11 @@ trimbletsip_message( double f = getflt((unsigned char *)&mb(12)); if (f > 0.0) - snprintf(t, BUFFER_SIZE(pbuffer, t), "x= %.1fm, y= %.1fm, z= %.1fm, time_of_fix= %f sec", - x, y, z, - f); + snprintf(t, BUFFER_SIZE(pbuffer, t), "x= %.1fm, y= %.1fm, z= %.1fm, time_of_fix= %f sec", + x, y, z, + f); else - return; + return; } break; @@ -5565,12 +5569,12 @@ trimbletsip_message( double f = getflt((unsigned char *)&mb(12)); if (f > 0.0) - snprintf(t, BUFFER_SIZE(pbuffer, t), "lat %f %c, long %f %c, alt %.2fm", - ((lat < 0.0) ? (-lat) : (lat))*RTOD, (lat < 0.0 ? 'S' : 'N'), - ((lng < 0.0) ? (-lng) : (lng))*RTOD, (lng < 0.0 ? 'W' : 'E'), - getflt((unsigned char *)&mb(8))); + snprintf(t, BUFFER_SIZE(pbuffer, t), "lat %f %c, long %f %c, alt %.2fm", + ((lat < 0.0) ? (-lat) : (lat))*RTOD, (lat < 0.0 ? 'S' : 'N'), + ((lng < 0.0) ? (-lng) : (lng))*RTOD, (lng < 0.0 ? 'W' : 'E'), + getflt((unsigned char *)&mb(8))); else - return; + return; } break; @@ -5580,7 +5584,7 @@ trimbletsip_message( double y = getdbl((unsigned char *)&mb(8)); double z = getdbl((unsigned char *)&mb(16)); snprintf(t, BUFFER_SIZE(pbuffer, t), "x= %.1fm, y= %.1fm, z= %.1fm", - x, y, z); + x, y, z); } break; @@ -5599,7 +5603,7 @@ trimbletsip_message( { int i, sats; - strncpy(t, "mode: ", BUFFER_SIZE(pbuffer, t)); + strlcpy(t, "mode: ", BUFFER_SIZE(pbuffer, t)); t += strlen(t); switch (mb(0) & 0x7) { @@ -5608,18 +5612,18 @@ trimbletsip_message( break; case 3: - strncpy(t, "2D", BUFFER_SIZE(pbuffer, t)); + strlcpy(t, "2D", BUFFER_SIZE(pbuffer, t)); break; case 4: - strncpy(t, "3D", BUFFER_SIZE(pbuffer, t)); + strlcpy(t, "3D", BUFFER_SIZE(pbuffer, t)); break; } t += strlen(t); if (mb(0) & 0x8) - strncpy(t, "-MANUAL, ", BUFFER_SIZE(pbuffer, t)); + strlcpy(t, "-MANUAL, ", BUFFER_SIZE(pbuffer, t)); else - strncpy(t, "-AUTO, ", BUFFER_SIZE(pbuffer, t)); + strlcpy(t, "-AUTO, ", BUFFER_SIZE(pbuffer, t)); t += strlen(t); sats = (mb(0)>>4) & 0xF; @@ -5641,7 +5645,7 @@ trimbletsip_message( } if (tr) - { /* mark for tracking status query */ + { /* mark for tracking status query */ tr->qtracking = 1; } } @@ -5654,7 +5658,7 @@ trimbletsip_message( if (getflt((unsigned char *)&mb(4)) < 0.0) { - strncpy(t, "", BUFFER_SIZE(pbuffer, t)); + strlcpy(t, "", BUFFER_SIZE(pbuffer, t)); var_flag &= ~DEF; } else @@ -5670,31 +5674,31 @@ trimbletsip_message( if (mb(20)) { var_flag &= ~DEF; - strncpy(t, ", OLD", BUFFER_SIZE(pbuffer, t)); + strlcpy(t, ", OLD", BUFFER_SIZE(pbuffer, t)); } t += strlen(t); if (mb(22)) { if (mb(22) == 1) - strncpy(t, ", BAD PARITY", BUFFER_SIZE(pbuffer, t)); + strlcpy(t, ", BAD PARITY", BUFFER_SIZE(pbuffer, t)); else if (mb(22) == 2) - strncpy(t, ", BAD EPH HEALTH", BUFFER_SIZE(pbuffer, t)); + strlcpy(t, ", BAD EPH HEALTH", BUFFER_SIZE(pbuffer, t)); } t += strlen(t); if (mb(23)) - strncpy(t, ", collecting data", BUFFER_SIZE(pbuffer, t)); + strlcpy(t, ", collecting data", BUFFER_SIZE(pbuffer, t)); } } break; default: - strncpy(t, "", BUFFER_SIZE(pbuffer, t)); + strlcpy(t, "", BUFFER_SIZE(pbuffer, t)); break; } t += strlen(t); - strncpy(t,"\"", BUFFER_SIZE(pbuffer, t)); + strlcpy(t,"\"", BUFFER_SIZE(pbuffer, t)); set_var(&parse->kv, pbuffer, sizeof(pbuffer), var_flag); } } diff --git a/ntpd/refclock_true.c b/ntpd/refclock_true.c index c2c297c58..dcbed76bd 100644 --- a/ntpd/refclock_true.c +++ b/ntpd/refclock_true.c @@ -77,9 +77,9 @@ extern int async_write(int, const void *, unsigned int); * ? >+/- 500 milliseconds # >+/- 50 milliseconds * * >+/- 5 milliseconds . >+/- 1 millisecond * A-H less than 1 millisecond. Character indicates which station - * is being received as follows: - * A = Norway, B = Liberia, C = Hawaii, D = North Dakota, - * E = La Reunion, F = Argentina, G = Australia, H = Japan. + * is being received as follows: + * A = Norway, B = Liberia, C = Hawaii, D = North Dakota, + * E = La Reunion, F = Argentina, G = Australia, H = Japan. * * The carriage return start bit begins on 0 seconds and extends to 1 bit time. * @@ -109,7 +109,7 @@ extern int async_write(int, const void *, unsigned int); * val1 - stratum to assign to this clock (default = 0) * val2 - refid assigned to this clock (default = "TRUE", see below) * flag1 - will silence the clock side of ntpd, just reading the clock - * without trying to write to it. (default = 0) + * without trying to write to it. (default = 0) * flag2 - generate a debug file /tmp/true%d. * flag3 - enable ppsclock streams module * flag4 - use the PCL-720 (BSD/OS only) @@ -218,23 +218,26 @@ true_debug(struct peer *peer, const char *fmt, ...) if (want_debugging != now_debugging) { if (want_debugging) { - char filename[40]; - int fd; - - snprintf(filename, sizeof(filename), "/tmp/true%d.debug", up->unit); - fd = open(filename, O_CREAT | O_WRONLY | O_EXCL, 0600); - if (fd >= 0 && (up->debug = fdopen(fd, "r+"))) { + char filename[40]; + int fd; + + snprintf(filename, sizeof(filename), + "/tmp/true%d.debug", up->unit); + fd = open(filename, O_CREAT | O_WRONLY | O_EXCL, + 0600); + if (fd >= 0 && (up->debug = fdopen(fd, "r+"))) { #ifdef HAVE_SETVBUF - static char buf[BUFSIZ]; - setvbuf(up->debug, buf, _IOLBF, BUFSIZ); + static char buf[BUFSIZ]; + + setvbuf(up->debug, buf, _IOLBF, BUFSIZ); #else - setlinebuf(up->debug); + setlinebuf(up->debug); #endif - } - } else { - fclose(up->debug); - up->debug = NULL; - } + } + } else { + fclose(up->debug); + up->debug = NULL; + } } if (up->debug) { @@ -262,7 +265,7 @@ true_start( /* * Open serial port */ - (void)snprintf(device, sizeof(device), DEVICE, unit); + snprintf(device, sizeof(device), DEVICE, unit); fd = refclock_open(device, SPEED232, LDISC_CLK); if (fd <= 0) return 0; @@ -289,7 +292,7 @@ true_start( */ peer->precision = PRECISION; pp->clockdesc = DESCRIPTION; - memcpy((char *)&pp->refid, REFID, 4); + memcpy(&pp->refid, REFID, 4); up->pollcnt = 2; up->type = t_unknown; up->state = s_Base; @@ -306,6 +309,7 @@ true_start( return (1); } + /* * true_shutdown - shut down the clock */ @@ -342,10 +346,10 @@ true_receive( char synced; int i; int lat, lon, off; /* GOES Satellite position */ - /* Use these variable to hold data until we decide its worth keeping */ - char rd_lastcode[BMAX]; - l_fp rd_tmp; - u_short rd_lencode; + /* These variables hold data until we decide to keep it */ + char rd_lastcode[BMAX]; + l_fp rd_tmp; + u_short rd_lencode; /* * Get the clock this applies to and pointers to the data. @@ -357,18 +361,19 @@ true_receive( /* * Read clock output. Automatically handles STREAMS, CLKLDISC. */ - rd_lencode = refclock_gtlin(rbufp, rd_lastcode, BMAX, &rd_tmp); - rd_lastcode[rd_lencode] = '\0'; + rd_lencode = refclock_gtlin(rbufp, rd_lastcode, BMAX, &rd_tmp); + rd_lastcode[rd_lencode] = '\0'; /* * There is a case where generates 2 timestamps. */ - if (rd_lencode == 0) - return; - pp->lencode = rd_lencode; - strncpy(pp->a_lastcode, rd_lastcode, sizeof(pp->a_lastcode)); - pp->lastrec = rd_tmp; - true_debug(peer, "receive(%s) [%d]\n", pp->a_lastcode, pp->lencode); + if (rd_lencode == 0) + return; + pp->lencode = rd_lencode; + strlcpy(pp->a_lastcode, rd_lastcode, sizeof(pp->a_lastcode)); + pp->lastrec = rd_tmp; + true_debug(peer, "receive(%s) [%d]\n", pp->a_lastcode, + pp->lencode); up->pollcnt = 2; record_clock_stats(&peer->srcadr, pp->a_lastcode); @@ -439,13 +444,13 @@ true_receive( */ if (sscanf(pp->a_lastcode, "F%2d", &i) == 1 && i > 0 && i < 80) { switch (i) { - case 50: + case 50: true_doevent(peer, e_F50); break; - case 51: + case 51: true_doevent(peer, e_F51); break; - default: + default: true_debug(peer, "got F%02d - ignoring\n", i); break; } @@ -467,8 +472,8 @@ true_receive( /* * Timecode: "N03726428W12209421+000033" - * 1 2 - * 0123456789012345678901234 + * 1 2 + * index 0123456789012345678901234 * (from a TCU during initialization) */ if ((pp->a_lastcode[0] == 'N' || pp->a_lastcode[0] == 'S') && @@ -482,6 +487,8 @@ true_receive( } /* * Timecode: "ddd:hh:mm:ssQ" + * 1 2 + * index 0123456789012345678901234 * (from all clocks supported by this driver.) */ if (pp->a_lastcode[3] == ':' && @@ -497,9 +504,9 @@ true_receive( */ if (synced == '>' || synced == '#' || synced == '?' || synced == 'X') - pp->leap = LEAP_NOTINSYNC; + pp->leap = LEAP_NOTINSYNC; else - pp->leap = LEAP_NOWARNING; + pp->leap = LEAP_NOWARNING; true_doevent(peer, e_TS); @@ -551,7 +558,7 @@ true_receive( * want one when polled. If we havn't been polled, bail out. */ if (!up->polled) - return; + return; true_doevent(peer, e_Poll); if (!refclock_process(pp)) { @@ -562,7 +569,7 @@ true_receive( * If clock is good we send a NOMINAL message so that * any previous BAD messages are nullified */ - pp->lastref = pp->lastrec; + pp->lastref = pp->lastrec; refclock_receive(peer); refclock_report(peer, CEVNT_NOMINAL); @@ -596,13 +603,13 @@ true_send( pp = peer->procptr; if (!(pp->sloppyclockflag & CLK_FLAG1)) { - register int len = strlen(cmd); + int len = strlen(cmd); true_debug(peer, "Send '%s'\n", cmd); if (write(pp->io.fd, cmd, (unsigned)len) != len) - refclock_report(peer, CEVNT_FAULT); + refclock_report(peer, CEVNT_FAULT); else - pp->polls++; + pp->polls++; } } @@ -632,158 +639,158 @@ true_doevent( true_debug(peer, "clock %s, state %s, event %s\n", typeStr(up->type), stateStr(up->state), eventStr(event)); switch (up->type) { - case t_goes: + case t_goes: switch (event) { - case e_Init: /* FALLTHROUGH */ - case e_Satellite: + case e_Init: /* FALLTHROUGH */ + case e_Satellite: /* * Switch back to on-second time codes and return. */ true_send(peer, "C"); up->state = s_Start; break; - case e_Poll: + case e_Poll: /* * After each poll, check the station (satellite). */ true_send(peer, "P"); /* No state change needed. */ break; - default: + default: break; } /* FALLTHROUGH */ - case t_omega: + case t_omega: switch (event) { - case e_Init: + case e_Init: true_send(peer, "C"); up->state = s_Start; break; - case e_TS: + case e_TS: if (up->state != s_Start && up->state != s_Auto) { true_send(peer, "\03\r"); break; } up->state = s_Auto; break; - default: + default: break; } break; - case t_tm: + case t_tm: switch (event) { - case e_Init: + case e_Init: true_send(peer, "F18\r"); up->state = s_Init; break; - case e_F18: + case e_F18: true_send(peer, "F50\r"); up->state = s_F18; break; - case e_F50: + case e_F50: true_send(peer, "F51\r"); up->state = s_F50; break; - case e_F51: + case e_F51: true_send(peer, "F08\r"); up->state = s_Start; break; - case e_TS: + case e_TS: if (up->state != s_Start && up->state != s_Auto) { true_send(peer, "\03\r"); break; } up->state = s_Auto; break; - default: + default: break; } break; - case t_tcu: + case t_tcu: switch (event) { - case e_Init: + case e_Init: true_send(peer, "MD3\r"); /* GPS Synch'd Gen. */ true_send(peer, "TSU\r"); /* UTC, not GPS. */ true_send(peer, "AU\r"); /* Auto Timestamps. */ up->state = s_Start; break; - case e_TS: + case e_TS: if (up->state != s_Start && up->state != s_Auto) { true_send(peer, "\03\r"); break; } up->state = s_Auto; break; - default: + default: break; } break; - case t_unknown: + case t_unknown: switch (up->state) { - case s_Base: + case s_Base: if (event != e_Init) abort(); true_send(peer, "P\r"); up->state = s_InqGOES; break; - case s_InqGOES: + case s_InqGOES: switch (event) { - case e_Satellite: + case e_Satellite: up->type = t_goes; true_doevent(peer, e_Init); break; - case e_Init: /*FALLTHROUGH*/ - case e_Huh: /*FALLTHROUGH*/ - case e_TS: + case e_Init: /*FALLTHROUGH*/ + case e_Huh: /*FALLTHROUGH*/ + case e_TS: up->state = s_InqOmega; true_send(peer, "C\r"); break; - default: + default: abort(); } break; - case s_InqOmega: + case s_InqOmega: switch (event) { - case e_TS: + case e_TS: up->type = t_omega; up->state = s_Auto; /* Inq side-effect. */ break; - case e_Init: /*FALLTHROUGH*/ - case e_Huh: + case e_Init: /*FALLTHROUGH*/ + case e_Huh: up->state = s_InqTM; true_send(peer, "F18\r"); break; - default: + default: abort(); } break; - case s_InqTM: + case s_InqTM: switch (event) { - case e_F18: + case e_F18: up->type = t_tm; true_doevent(peer, e_Init); break; - case e_Init: /*FALLTHROUGH*/ - case e_Huh: + case e_Init: /*FALLTHROUGH*/ + case e_Huh: true_send(peer, "PO\r"); up->state = s_InqTCU; break; - default: + default: abort(); } break; - case s_InqTCU: + case s_InqTCU: switch (event) { - case e_Location: + case e_Location: up->type = t_tcu; true_doevent(peer, e_Init); break; - case e_Init: /*FALLTHROUGH*/ - case e_Huh: + case e_Init: /*FALLTHROUGH*/ + case e_Huh: up->state = s_Base; sleep(1); /* XXX */ break; - default: + default: abort(); } break; @@ -791,16 +798,17 @@ true_doevent( * An expedient hack to prevent lint complaints, * these don't actually need to be used here... */ - case s_Init: - case s_F18: - case s_F50: - case s_Start: - case s_Auto: - case s_Max: - msyslog(LOG_INFO, "TRUE: state %s is unexpected!", stateStr(up->state)); + case s_Init: + case s_F18: + case s_F50: + case s_Start: + case s_Auto: + case s_Max: + msyslog(LOG_INFO, "TRUE: state %s is unexpected!", + stateStr(up->state)); } break; - default: + default: abort(); /* NOTREACHED */ } @@ -842,9 +850,9 @@ true_poll( */ pp = peer->procptr; up = pp->unitptr; - if (up->pollcnt > 0) - up->pollcnt--; - else { + if (up->pollcnt > 0) { + up->pollcnt--; + } else { true_doevent(peer, e_Init); refclock_report(peer, CEVNT_TIMEOUT); } diff --git a/ntpd/refclock_wwv.c b/ntpd/refclock_wwv.c index b6b745d6c..f58bad62a 100644 --- a/ntpd/refclock_wwv.c +++ b/ntpd/refclock_wwv.c @@ -63,7 +63,7 @@ * * Fudge factors * - * Fudge flag4 causes the dubugging output described above to be + * Fudge flag4 causes the debugging output described above to be * recorded in the clockstats file. Fudge flag2 selects the audio input * port, where 0 is the mike port (default) and 1 is the line-in port. * It does not seem useful to select the compact disc player port. Fudge @@ -596,7 +596,7 @@ static void wwv_corr4 (struct peer *, struct decvec *, double [], double [][4]); static void wwv_gain (struct peer *); static void wwv_tsec (struct peer *); -static int timecode (struct wwvunit *, char *); +static int timecode (struct wwvunit *, char *, size_t); static double wwv_snr (double, double); static int carry (struct decvec *); static int wwv_newchan (struct peer *); @@ -2091,7 +2091,8 @@ wwv_clock( refclock_receive(peer); } } - pp->lencode = timecode(up, pp->a_lastcode); + pp->lencode = timecode(up, pp->a_lastcode, + sizeof(pp->a_lastcode)); record_clock_stats(&peer->srcadr, pp->a_lastcode); #ifdef DEBUG if (debug) @@ -2610,7 +2611,8 @@ wwv_qsy( static int timecode( struct wwvunit *up, /* driver structure pointer */ - char *ptr /* target string */ + char * tc, /* target string */ + size_t tcsiz /* target max chars */ ) { struct sync *sp; @@ -2635,20 +2637,23 @@ timecode( dut = up->misc & 0x7; if (!(up->misc & DUTS)) dut = -dut; - sprintf(ptr, "%c%1X", synchar, up->alarm); - sprintf(cptr, " %4d %03d %02d:%02d:%02d %c%c %+d", - year, day, hour, minute, second, leapchar, dst, dut); - strcat(ptr, cptr); + snprintf(tc, tcsiz, "%c%1X", synchar, up->alarm); + snprintf(cptr, sizeof(cptr), + " %4d %03d %02d:%02d:%02d %c%c %+d", + year, day, hour, minute, second, leapchar, dst, dut); + strlcat(tc, cptr, tcsiz); /* * Specific variable-format fields */ sp = up->sptr; - sprintf(cptr, " %d %d %s %.0f %d %.1f %d", up->watch, - up->mitig[up->dchan].gain, sp->refid, sp->metric, - up->errcnt, up->freq / SECOND * 1e6, up->avgint); - strcat(ptr, cptr); - return (strlen(ptr)); + snprintf(cptr, sizeof(cptr), " %d %d %s %.0f %d %.1f %d", + up->watch, up->mitig[up->dchan].gain, sp->refid, + sp->metric, up->errcnt, up->freq / SECOND * 1e6, + up->avgint); + strlcat(tc, cptr, tcsiz); + + return strlen(tc); } diff --git a/ntpdate/ntpdate.c b/ntpdate/ntpdate.c index b8eb39c28..307c0ce06 100644 --- a/ntpdate/ntpdate.c +++ b/ntpdate/ntpdate.c @@ -1352,7 +1352,7 @@ addserver( char service[5]; sockaddr_u addr; - strncpy(service, "ntp", sizeof(service)); + strlcpy(service, "ntp", sizeof(service)); /* Get host address. Looking for UDP datagram connection. */ ZERO(hints); @@ -1689,7 +1689,7 @@ init_io(void) * Open the socket */ - strncpy(service, "ntp", sizeof(service)); + strlcpy(service, "ntp", sizeof(service)); /* * Init hints addrinfo structure diff --git a/ntpdate/ntptime_config.c b/ntpdate/ntptime_config.c index e784d2803..78fc461ae 100644 --- a/ntpdate/ntptime_config.c +++ b/ntpdate/ntptime_config.c @@ -367,10 +367,8 @@ M break; case CONFIG_KEYS: - if (ntokens >= 2) { - key_file = (char *) emalloc(strlen(tokens[1]) + 1); - strcpy(key_file, tokens[1]); - } + if (ntokens >= 2) + key_file = estrdup(tokens[1]); break; } } diff --git a/ntpdc/ntpdc.c b/ntpdc/ntpdc.c index 36e850f79..cfdda72d3 100644 --- a/ntpdc/ntpdc.c +++ b/ntpdc/ntpdc.c @@ -422,7 +422,7 @@ openhost( * will return an "IPv4-mapped IPv6 address" address if you * give it an IPv4 address to lookup. */ - strncpy(service, "ntp", sizeof(service)); + strlcpy(service, "ntp", sizeof(service)); ZERO(hints); hints.ai_family = ai_fam_templ; hints.ai_protocol = IPPROTO_UDP; @@ -463,10 +463,9 @@ openhost( memcpy(&addr, ai->ai_addr, octets); if (ai->ai_canonname == NULL) - strncpy(temphost, stoa(&addr), sizeof(temphost)); + strlcpy(temphost, stoa(&addr), sizeof(temphost)); else - strncpy(temphost, ai->ai_canonname, sizeof(temphost)); - temphost[sizeof(temphost) - 1] = '\0'; + strlcpy(temphost, ai->ai_canonname, sizeof(temphost)); if (debug > 2) printf("Opening host %s\n", temphost); @@ -477,7 +476,7 @@ openhost( closesocket(sockfd); havehost = 0; } - strncpy(currenthost, temphost, sizeof(currenthost)); + strlcpy(currenthost, temphost, sizeof(currenthost)); /* port maps to the same in both families */ s_port = NSRCPORT(&addr);; @@ -1442,7 +1441,7 @@ getnetnum( memcpy(num, ai->ai_addr, ai->ai_addrlen); if (fullhost != NULL) { if (ai->ai_canonname != NULL) - strncpy(fullhost, ai->ai_canonname, + strlcpy(fullhost, ai->ai_canonname, LENHOSTNAME); else getnameinfo(&num->sa, SOCKLEN(num), diff --git a/ntpdc/ntpdc_ops.c b/ntpdc/ntpdc_ops.c index 25aa2ee7e..7d453fb66 100644 --- a/ntpdc/ntpdc_ops.c +++ b/ntpdc/ntpdc_ops.c @@ -1699,19 +1699,19 @@ again: } if (res != 0) - return; + return; if (!checkitems(items, fp)) - return; + return; if (!checkitemsize(itemsize, sizeof(struct info_restrict)) && !checkitemsize(itemsize, v4sizeof(struct info_restrict))) - return; + return; - (void) fprintf(fp, - " address mask count flags\n"); - (void) fprintf(fp, - "=====================================================================\n"); + fprintf(fp, + " address mask count flags\n"); + fprintf(fp, + "=====================================================================\n"); while (items > 0) { SET_ADDRS(resaddr, maskaddr, rl, addr, mask); @@ -1739,29 +1739,33 @@ again: while (rf->bit != 0) { if (mflags & rf->bit) { if (!res) - (void) strcat(flagstr, comma); + strlcat(flagstr, comma, + sizeof(flagstr)); res = 0; - (void) strcat(flagstr, rf->str); + strlcat(flagstr, rf->str, + sizeof(flagstr)); } rf++; } rf = (impl_ver == IMPL_XNTPD_OLD) - ? &resflagsV2[0] - : &resflagsV3[0] - ; + ? &resflagsV2[0] + : &resflagsV3[0]; + while (rf->bit != 0) { if (flags & rf->bit) { if (!res) - (void) strcat(flagstr, comma); + strlcat(flagstr, comma, + sizeof(flagstr)); res = 0; - (void) strcat(flagstr, rf->str); + strlcat(flagstr, rf->str, + sizeof(flagstr)); } rf++; } if (flagstr[0] == '\0') - strncpy(flagstr, "none", sizeof(flagstr)); + strlcpy(flagstr, "none", sizeof(flagstr)); if (!skip) fprintf(fp, "%-15.15s %-15.15s %9lu %s\n", diff --git a/ntpq/ntpq-subs.c b/ntpq/ntpq-subs.c index cf9b9ac28..446c9da9c 100644 --- a/ntpq/ntpq-subs.c +++ b/ntpq/ntpq-subs.c @@ -1616,11 +1616,12 @@ doprintpeers( decodeint(value, &hmode); } else if (!strcmp("refid", name)) { if (pvl == peervarlist) { - if (*value == '\0') { + drlen = strlen(value); + if (0 == drlen) { dstadr_refid = ""; - } else if (strlen(value) <= 4) { - strncpy((void *)&u32, value, - sizeof(u32)); + } else if (drlen <= 4) { + ZERO(u32); + memcpy(&u32, value, drlen); dstadr_refid = refid_str(u32, 1); } else if (decodenetnum(value, &dstadr)) { dstadr_refid = @@ -1706,7 +1707,7 @@ doprintpeers( fprintf(fp, "%-*s ", (int)maxhostlen, currenthost); if (AF_UNSPEC == af || AF(&srcadr) == af) { if (!have_srchost) - strncpy(clock_name, nntohost(&srcadr), + strlcpy(clock_name, nntohost(&srcadr), sizeof(clock_name)); fprintf(fp, "%c%-15.15s ", c, clock_name); drlen = strlen(dstadr_refid); @@ -2476,7 +2477,7 @@ collect_mru_list( case 'n': if (!strcmp(tag, "nonce")) { - strncpy(nonce, val, sizeof(nonce)); + strlcpy(nonce, val, sizeof(nonce)); nonce_uses = 0; break; /* case */ } else if (strcmp(tag, "now") || diff --git a/ntpq/ntpq.c b/ntpq/ntpq.c index 9bace34bb..81fa53358 100644 --- a/ntpq/ntpq.c +++ b/ntpq/ntpq.c @@ -583,10 +583,9 @@ openhost( memcpy(&addr, ai->ai_addr, octets); if (ai->ai_canonname == NULL) - strncpy(temphost, stoa(&addr), sizeof(temphost)); + strlcpy(temphost, stoa(&addr), sizeof(temphost)); else - strncpy(temphost, ai->ai_canonname, sizeof(temphost)); - temphost[sizeof(temphost) - 1] = '\0'; + strlcpy(temphost, ai->ai_canonname, sizeof(temphost)); if (debug > 2) printf("Opening host %s\n", temphost); @@ -597,7 +596,7 @@ openhost( closesocket(sockfd); havehost = 0; } - strncpy(currenthost, temphost, sizeof(currenthost)); + strlcpy(currenthost, temphost, sizeof(currenthost)); /* port maps to the same location in both families */ s_port = NSRCPORT(&addr); @@ -1710,7 +1709,7 @@ getnetnum( memcpy(num, ai->ai_addr, ai->ai_addrlen); if (fullhost != NULL) { if (ai->ai_canonname != NULL) - strncpy(fullhost, ai->ai_canonname, + strlcpy(fullhost, ai->ai_canonname, LENHOSTNAME); else getnameinfo(&num->sa, SOCKLEN(num), @@ -2999,7 +2998,7 @@ tstflags( cp += strlen(cp); cb -= strlen(cp); if (!val) { - strncat(cp, " ok", cb); + strlcat(cp, " ok", cb); cp += strlen(cp); cb -= strlen(cp); } else { diff --git a/ntpsnmpd/ntpSnmpSubagentObject.c b/ntpsnmpd/ntpSnmpSubagentObject.c index 57b10ba49..f65fedf60 100644 --- a/ntpsnmpd/ntpSnmpSubagentObject.c +++ b/ntpsnmpd/ntpSnmpSubagentObject.c @@ -121,7 +121,7 @@ ntpsnmpd_parse_string( if (value[0] == '"') { val_cnt--; - strncpy(value, &value[1], valuesize); + strlcpy(value, &value[1], valuesize); if (val_cnt > 0 && value[val_cnt - 1] == '"') { val_cnt--; value[val_cnt] = '\0'; diff --git a/ports/winnt/libntp/syslog.c b/ports/winnt/libntp/syslog.c index b0a84ac92..2a2915a20 100644 --- a/ports/winnt/libntp/syslog.c +++ b/ports/winnt/libntp/syslog.c @@ -134,8 +134,7 @@ void openlog(const char *name, int flags, ...) { /* Get a handle to the Application event log */ hAppLog = RegisterEventSource(NULL, progname); - strncpy(progname, name, sizeof(progname)); - progname[sizeof(progname) - 1] = 0; + strlcpy(progname, name, sizeof(progname)); } /* diff --git a/ports/winnt/vc6/libntp.dsp b/ports/winnt/vc6/libntp.dsp index a76a2f523..0814a9fe8 100644 --- a/ports/winnt/vc6/libntp.dsp +++ b/ports/winnt/vc6/libntp.dsp @@ -414,6 +414,10 @@ SOURCE=..\..\..\libntp\statestr.c # End Source File # Begin Source File +SOURCE=..\..\..\libntp\strl_obsd.c +# End Source File +# Begin Source File + SOURCE=..\libntp\syslog.c # End Source File # Begin Source File diff --git a/ports/winnt/vs2003/libntp.vcproj b/ports/winnt/vs2003/libntp.vcproj index 793a0b6ea..827064fdb 100644 --- a/ports/winnt/vs2003/libntp.vcproj +++ b/ports/winnt/vs2003/libntp.vcproj @@ -1536,26 +1536,11 @@ PreprocessorDefinitions=""/> + + - - - - - - diff --git a/ports/winnt/vs2005/libntp.vcproj b/ports/winnt/vs2005/libntp.vcproj index ea1330a78..16ef10dba 100644 --- a/ports/winnt/vs2005/libntp.vcproj +++ b/ports/winnt/vs2005/libntp.vcproj @@ -500,6 +500,10 @@ RelativePath="..\..\..\lib\isc\win32\strerror.c" > + + diff --git a/ports/winnt/vs2008/libntp/libntp.vcproj b/ports/winnt/vs2008/libntp/libntp.vcproj index f689558b7..ed7a76e1f 100644 --- a/ports/winnt/vs2008/libntp/libntp.vcproj +++ b/ports/winnt/vs2008/libntp/libntp.vcproj @@ -519,6 +519,10 @@ RelativePath="..\..\..\..\lib\isc\win32\strerror.c" > + + @@ -897,11 +901,11 @@ > timestamp = time(NULL); memcpy(pke->type, type, 4); pke->type[sizeof(pke->type) - 1] = '\0'; - strncpy(pke->hostname, hostname, - sizeof(pke->hostname)); - pke->hostname[sizeof(pke->hostname) - 1] = '\0'; + strlcpy(pke->hostname, hostname, sizeof(pke->hostname)); /* * insert in address ("hostname") order to find duplicates diff --git a/sntp/m4/ntp_libntp.m4 b/sntp/m4/ntp_libntp.m4 index 7271b94bf..1516d02b8 100644 --- a/sntp/m4/ntp_libntp.m4 +++ b/sntp/m4/ntp_libntp.m4 @@ -80,7 +80,7 @@ case "$host" in ;; esac -AC_CHECK_FUNCS([getclock stime timegm]) +AC_CHECK_FUNCS([getclock stime timegm strlcpy strlcat]) dnl HP-UX 11.31 on HPPA has a net/if.h that can't be compiled with gcc4 dnl due to an incomplete type (a union) mpinfou used in an array. gcc3 diff --git a/sntp/utilities.c b/sntp/utilities.c index a65af2913..84e5b84d1 100644 --- a/sntp/utilities.c +++ b/sntp/utilities.c @@ -121,16 +121,11 @@ addrinfo_to_str ( * in that case. */ char * -ss_to_str ( +ss_to_str( sockaddr_u *saddr ) { - char * buf; - - buf = emalloc(INET6_ADDRSTRLEN); - strncpy(buf, stoa(saddr), INET6_ADDRSTRLEN); - - return buf; + return estrdup(stoa(saddr)); } diff --git a/util/ntp-keygen.c b/util/ntp-keygen.c index 0b78728b6..17edb646e 100644 --- a/util/ntp-keygen.c +++ b/util/ntp-keygen.c @@ -135,6 +135,7 @@ */ FILE *fheader (const char *, const char *, const char *); int gen_md5 (char *); +void followlink (char *, size_t); #ifdef AUTOKEY EVP_PKEY *gen_rsa (char *); EVP_PKEY *gen_dsa (char *); @@ -176,12 +177,12 @@ long d0, d1, d2, d3; /* callback counters */ BOOL init_randfile(); /* - * Don't try to follow symbolic links + * Don't try to follow symbolic links. Assumes link == file. */ int readlink(char *link, char *file, int len) { - return (-1); + return strlen(file); } /* @@ -194,6 +195,7 @@ symlink(char *filename, char *linkname) { MoveFile(filename, linkname); return (0); } + void InitWin32Sockets() { WORD wVersionRequested; @@ -207,6 +209,29 @@ InitWin32Sockets() { } #endif /* SYS_WINNT */ + +/* + * followlink() - replace filename with its target if symlink. + * + * Some readlink() implementations do not null-terminate the result. + */ +void +followlink( + char * fname, + size_t bufsiz + ) +{ + int len; + + len = readlink(fname, fname, (int)bufsiz); + if (len < 0 || bufsiz < 1) + return; + if (len > (int)bufsiz - 1) + len = (int)bufsiz - 1; + fname[len] = '\0'; +} + + /* * Main program */ @@ -293,16 +318,16 @@ main( #ifdef AUTOKEY if (HAVE_OPT( PVT_PASSWD )) - passwd1 = strdup(OPT_ARG( PVT_PASSWD )); + passwd1 = estrdup(OPT_ARG( PVT_PASSWD )); if (HAVE_OPT( GET_PVT_PASSWD )) - passwd2 = strdup(OPT_ARG( GET_PVT_PASSWD )); + passwd2 = estrdup(OPT_ARG( GET_PVT_PASSWD )); if (HAVE_OPT( HOST_KEY )) hostkey++; if (HAVE_OPT( SIGN_KEY )) - sign = strdup(OPT_ARG( SIGN_KEY )); + sign = estrdup(OPT_ARG( SIGN_KEY )); if (HAVE_OPT( GQ_PARAMS )) gqkey++; @@ -326,16 +351,16 @@ main( if (HAVE_OPT( SUBJECT_NAME )) { if (*OPT_ARG(SUBJECT_NAME) != '@') { - certname = strdup(OPT_ARG(SUBJECT_NAME)); + certname = estrdup(OPT_ARG(SUBJECT_NAME)); } else { - strcpy(str, certname); - strcat(str, OPT_ARG(SUBJECT_NAME)); - certname = strdup(str); + strlcpy(str, certname, sizeof(str)); + strlcat(str, OPT_ARG(SUBJECT_NAME), sizeof(str)); + certname = estrdup(str); } } if (HAVE_OPT( ISSUER_NAME )) - groupname = strdup(OPT_ARG( ISSUER_NAME )); + groupname = estrdup(OPT_ARG( ISSUER_NAME )); if (HAVE_OPT( LIFETIME )) lifetime = OPT_VALUE_LIFETIME; @@ -354,7 +379,7 @@ main( if (!RAND_status()) { u_int temp; - if (RAND_file_name(pathbuf, MAXFILENAME) == NULL) { + if (RAND_file_name(pathbuf, sizeof(pathbuf)) == NULL) { fprintf(stderr, "RAND_file_name %s\n", ERR_error_string(ERR_get_error(), NULL)); exit (-1); @@ -374,7 +399,7 @@ main( /* * Load previous certificate if available. */ - sprintf(filename, "ntpkey_cert_%s", hostname); + snprintf(filename, sizeof(filename), "ntpkey_cert_%s", hostname); if ((fstr = fopen(filename, "r")) != NULL) { cert = PEM_read_X509(fstr, NULL, NULL, NULL); fclose(fstr); @@ -453,10 +478,10 @@ main( if (hostkey) pkey_host = genkey("RSA", "host"); if (pkey_host == NULL) { - sprintf(filename, "ntpkey_host_%s", hostname); + snprintf(filename, sizeof(filename), "ntpkey_host_%s", hostname); pkey_host = readkey(filename, passwd1, &fstamp, NULL); if (pkey_host != NULL) { - readlink(filename, filename, sizeof(filename)); + followlink(filename, sizeof(filename)); fprintf(stderr, "Using host key %s\n", filename); } else { @@ -476,10 +501,11 @@ main( if (sign != NULL) pkey_sign = genkey(sign, "sign"); if (pkey_sign == NULL) { - sprintf(filename, "ntpkey_sign_%s", hostname); + snprintf(filename, sizeof(filename), "ntpkey_sign_%s", + hostname); pkey_sign = readkey(filename, passwd1, &fstamp, NULL); if (pkey_sign != NULL) { - readlink(filename, filename, sizeof(filename)); + followlink(filename, sizeof(filename)); fprintf(stderr, "Using sign key %s\n", filename); } else { @@ -499,7 +525,7 @@ main( sprintf(filename, "ntpkey_gqkey_%s", groupname); pkey_gqkey = readkey(filename, passwd1, &fstamp, NULL); if (pkey_gqkey != NULL) { - readlink(filename, filename, sizeof(filename)); + followlink(filename, sizeof(filename)); fprintf(stderr, "Using GQ parameters %s\n", filename); } @@ -565,7 +591,7 @@ main( sprintf(filename, "ntpkey_iffkey_%s", groupname); pkey_iffkey = readkey(filename, passwd1, &fstamp, NULL); if (pkey_iffkey != NULL) { - readlink(filename, filename, sizeof(filename)); + followlink(filename, sizeof(filename)); fprintf(stderr, "Using IFF keys %s\n", filename); } @@ -629,7 +655,7 @@ main( pkey_mvkey = readkey(filename, passwd1, &fstamp, pkey_mvpar); if (pkey_mvkey != NULL) { - readlink(filename, filename, sizeof(filename)); + followlink(filename, sizeof(filename)); fprintf(stderr, "Using MV keys %s\n", filename); } diff --git a/util/tg.c b/util/tg.c index aa3950d88..0d0fce688 100644 --- a/util/tg.c +++ b/util/tg.c @@ -266,13 +266,13 @@ main( /* * Parse options */ - strcpy(device, DEVICE); + strlcpy(device, DEVICE, sizeof(device)); year = 0; while ((temp = getopt(argc, argv, "a:dhilsu:v:y:")) != -1) { switch (temp) { case 'a': /* specify audio device (/dev/audio) */ - strcpy(device, optarg); + strlcpy(device, optarg, sizeof(device)); break; case 'd': /* set DST for summer (WWV/H only) */ diff --git a/util/tg2.c b/util/tg2.c index 1293aff33..db8de0656 100644 --- a/util/tg2.c +++ b/util/tg2.c @@ -689,7 +689,7 @@ main( /* * Parse options */ - strcpy(device, DEVICE); + strlcpy(device, DEVICE, sizeof(device)); Year = 0; SetSampleRate = SECOND; @@ -701,7 +701,7 @@ main( switch (temp) { case 'a': /* specify audio device (/dev/audio) */ - strcpy(device, optarg); + strlcpy(device, optarg, sizeof(device)); break; case 'b': /* Remove (delete) a leap second at the end of the specified minute. */ @@ -1521,7 +1521,7 @@ main( /* * Generate data for the second */ - switch(encode) { + switch (encode) { /* * The IRIG second consists of 20 BCD digits of width- @@ -1529,7 +1529,8 @@ main( * percent on the 1000-Hz carrier. */ case IRIG: - strcpy (OutputDataString, ""); /* Initialize the output string */ + /* Initialize the output string */ + OutputDataString[0] = '\0'; for (BitNumber = 0; BitNumber < 100; BitNumber++) { FrameNumber = (BitNumber/10) + 1; @@ -1618,8 +1619,7 @@ main( TotalCyclesRemoved += 1; } - /* OutputDataString OUTPUT_DATA_STRING_LENGTH */ - strncat(OutputDataString, "x", OUTPUT_DATA_STRING_LENGTH); + strlcat(OutputDataString, "x", OUTPUT_DATA_STRING_LENGTH); } else { @@ -1637,7 +1637,7 @@ main( TotalCyclesRemoved += 1; } - strncat(OutputDataString, "o", OUTPUT_DATA_STRING_LENGTH); + strlcat(OutputDataString, "o", OUTPUT_DATA_STRING_LENGTH); } } // End of true clause for "if (RateCorrection < 0)" else @@ -1660,8 +1660,7 @@ main( TotalCyclesAdded += 1; } - /* OutputDataString OUTPUT_DATA_STRING_LENGTH */ - strncat(OutputDataString, "+", OUTPUT_DATA_STRING_LENGTH); + strlcat(OutputDataString, "+", OUTPUT_DATA_STRING_LENGTH); } else { @@ -1679,7 +1678,7 @@ main( TotalCyclesAdded += 1; } - strncat(OutputDataString, "*", OUTPUT_DATA_STRING_LENGTH); + strlcat(OutputDataString, "*", OUTPUT_DATA_STRING_LENGTH); } } // End of true clause for "if (RateCorrection > 0)" else @@ -1697,8 +1696,7 @@ main( peep(M5, 1000, HIGH); peep(M5, 1000, LOW); } - /* OutputDataString OUTPUT_DATA_STRING_LENGTH */ - strncat(OutputDataString, "1", OUTPUT_DATA_STRING_LENGTH); + strlcat(OutputDataString, "1", OUTPUT_DATA_STRING_LENGTH); } else { @@ -1712,7 +1710,7 @@ main( peep(M2, 1000, HIGH); peep(M8, 1000, LOW); } - strncat(OutputDataString, "0", OUTPUT_DATA_STRING_LENGTH); + strlcat(OutputDataString, "0", OUTPUT_DATA_STRING_LENGTH); } } // End of else clause for "if (RateCorrection > 0)" } // End of else claues for "if (RateCorrection < 0)" @@ -1731,8 +1729,7 @@ main( peep(M5, 1000, HIGH); peep(M5, 1000, LOW); } - /* OutputDataString OUTPUT_DATA_STRING_LENGTH */ - strncat(OutputDataString, "1", OUTPUT_DATA_STRING_LENGTH); + strlcat(OutputDataString, "1", OUTPUT_DATA_STRING_LENGTH); } else { @@ -1746,7 +1743,7 @@ main( peep(M2, 1000, HIGH); peep(M8, 1000, LOW); } - strncat(OutputDataString, "0", OUTPUT_DATA_STRING_LENGTH); + strlcat(OutputDataString, "0", OUTPUT_DATA_STRING_LENGTH); } } // end of else clause for "if ((FrameNumber == 5) && (BitNumber == 8))" break; @@ -1763,7 +1760,7 @@ main( peep(M2, 1000, HIGH); peep(M8, 1000, LOW); } - strncat(OutputDataString, "-", OUTPUT_DATA_STRING_LENGTH); + strlcat(OutputDataString, "-", OUTPUT_DATA_STRING_LENGTH); break; case DEC: /* send marker/position indicator IM/PI bit */ @@ -1780,7 +1777,7 @@ main( peep(arg, 1000, HIGH); peep(10 - arg, 1000, LOW); } - strncat(OutputDataString, ".", OUTPUT_DATA_STRING_LENGTH); + strlcat(OutputDataString, ".", OUTPUT_DATA_STRING_LENGTH); break; default: