4 * Home page of code is: http://www.smartmontools.org
6 * Copyright (C) 2002-12 Bruce Allen
7 * Copyright (C) 2008-17 Christian Franke
8 * Copyright (C) 2000 Michael Cornwell <cornwell@acm.org>
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2, or (at your option)
15 * You should have received a copy of the GNU General Public License
16 * (for example COPYING); If not, see <http://www.gnu.org/licenses/>.
18 * This code was originally developed as a Senior Thesis by Michael Cornwell
19 * at the Concurrent Systems Laboratory (now part of the Storage Systems
20 * Research Center), Jack Baskin School of Engineering, University of
21 * California, Santa Cruz. http://ssrc.soe.ucsc.edu/
25 // THIS FILE IS INTENDED FOR UTILITY ROUTINES THAT ARE APPLICABLE TO
26 // BOTH SCSI AND ATA DEVICES, AND THAT MAY BE USED IN SMARTD,
43 #include <mbstring.h> // _mbsinc()
48 #include "svnversion.h"
53 #include "dev_interface.h"
55 const char * utility_cpp_cvsid
= "$Id: utility.cpp 4583 2017-11-03 21:10:09Z chrfranke $"
56 UTILITY_H_CVSID INT64_H_CVSID
;
58 const char * packet_types
[] = {
59 "Direct-access (disk)",
60 "Sequential-access (tape)",
63 "Write-once (optical disk)",
66 "Optical memory (optical disk)",
69 "Graphic arts pre-press (10)",
70 "Graphic arts pre-press (11)",
73 "Reduced block command (simplified disk)",
74 "Optical card reader/writer"
77 // BUILD_INFO can be provided by package maintainers
79 #define BUILD_INFO "(local build)"
82 // Make version information string
83 std::string
format_version_info(const char * prog_name
, bool full
/*= false*/)
85 std::string info
= strprintf(
86 "%s " PACKAGE_VERSION
" "
87 #ifdef SMARTMONTOOLS_SVN_REV
88 SMARTMONTOOLS_SVN_DATE
" r" SMARTMONTOOLS_SVN_REV
90 "(build date " __DATE__
")" // checkout without expansion of Id keywords
92 " [%s] " BUILD_INFO
"\n"
93 "Copyright (C) 2002-17, Bruce Allen, Christian Franke, www.smartmontools.org\n",
94 prog_name
, smi()->get_os_version_str().c_str()
101 info
+= " comes with ABSOLUTELY NO WARRANTY. This is free\n"
102 "software, and you are welcome to redistribute it under\n"
103 "the terms of the GNU General Public License; either\n"
104 "version 2, or (at your option) any later version.\n"
105 "See http://www.gnu.org for further details.\n"
107 "smartmontools release " PACKAGE_VERSION
108 " dated " SMARTMONTOOLS_RELEASE_DATE
" at " SMARTMONTOOLS_RELEASE_TIME
"\n"
109 #ifdef SMARTMONTOOLS_SVN_REV
110 "smartmontools SVN rev " SMARTMONTOOLS_SVN_REV
111 " dated " SMARTMONTOOLS_SVN_DATE
" at " SMARTMONTOOLS_SVN_TIME
"\n"
113 "smartmontools SVN rev is unknown\n"
115 "smartmontools build host: " SMARTMONTOOLS_BUILD_HOST
"\n"
116 "smartmontools build with: "
117 #if __cplusplus > 201402
119 #elif __cplusplus > 201103
121 #elif __cplusplus > 199711
126 #if defined(__GNUC__) && defined(__VERSION__) // works also with CLang
130 "smartmontools configure arguments:"
132 info
+= (sizeof(SMARTMONTOOLS_CONFIGURE_ARGS
) > 1 ?
133 SMARTMONTOOLS_CONFIGURE_ARGS
: " [no arguments given]");
139 // Solaris only: Get site-default timezone. This is called from
140 // UpdateTimezone() when TZ environment variable is unset at startup.
141 #if defined (__SVR4) && defined (__sun)
142 static const char *TIMEZONE_FILE
= "/etc/TIMEZONE";
144 static char *ReadSiteDefaultTimezone(){
150 fp
= fopen(TIMEZONE_FILE
, "r");
151 if(fp
== NULL
) return NULL
;
152 while(fgets(buf
, sizeof(buf
), fp
)) {
153 if (strncmp(buf
, "TZ=", 3)) // searches last "TZ=" line
156 if (buf
[n
] == '\n') buf
[n
] = 0;
165 // Make sure that this executable is aware if the user has changed the
166 // time-zone since the last time we polled devices. The cannonical
167 // example is a user who starts smartd on a laptop, then flies across
168 // time-zones with a laptop, and then changes the timezone, WITHOUT
169 // restarting smartd. This is a work-around for a bug in
170 // GLIBC. Yuk. See bug number 48184 at http://bugs.debian.org and
171 // thanks to Ian Redfern for posting a workaround.
173 // Please refer to the smartd manual page, in the section labeled LOG
174 // TIMESTAMP TIMEZONE.
175 void FixGlibcTimeZoneBug(){
178 putenv((char *)"TZ=GMT"); // POSIX prototype is 'int putenv(char *)'
180 putenv((char *)"TZ");
187 putenv("TZ="); // empty value removes TZ, putenv("TZ") does nothing
190 #elif defined (__SVR4) && defined (__sun)
191 // In Solaris, putenv("TZ=") sets null string and invalid timezone.
192 // putenv("TZ") does nothing. With invalid TZ, tzset() do as if
193 // TZ=GMT. With TZ unset, /etc/TIMEZONE will be read only _once_ at
194 // first tzset() call. Conclusion: Unlike glibc, dynamic
195 // configuration of timezone can be done only by changing actual
196 // value of TZ environment value.
197 enum tzstate
{ NOT_CALLED_YET
, USER_TIMEZONE
, TRACK_TIMEZONE
};
198 static enum tzstate state
= NOT_CALLED_YET
;
200 static struct stat prev_stat
;
201 static char *prev_tz
;
202 struct stat curr_stat
;
205 if(state
== NOT_CALLED_YET
) {
207 state
= USER_TIMEZONE
; // use supplied timezone
209 state
= TRACK_TIMEZONE
;
210 if(stat(TIMEZONE_FILE
, &prev_stat
)) {
211 state
= USER_TIMEZONE
; // no TZ, no timezone file; use GMT forever
213 prev_tz
= ReadSiteDefaultTimezone(); // track timezone file change
214 if(prev_tz
) putenv(prev_tz
);
218 } else if(state
== TRACK_TIMEZONE
) {
219 if(stat(TIMEZONE_FILE
, &curr_stat
) == 0
220 && (curr_stat
.st_ctime
!= prev_stat
.st_ctime
221 || curr_stat
.st_mtime
!= prev_stat
.st_mtime
)) {
222 // timezone file changed
223 curr_tz
= ReadSiteDefaultTimezone();
226 if(prev_tz
) free(prev_tz
);
227 prev_tz
= curr_tz
; prev_stat
= curr_stat
;
233 // OTHER OS/LIBRARY FIXES SHOULD GO HERE, IF DESIRED. PLEASE TRY TO
234 // KEEP THEM INDEPENDENT.
239 // Fix strings in tzname[] to avoid long names with non-ascii characters.
240 // If TZ is not set, tzset() in the MSVC runtime sets tzname[] to the
241 // national language timezone names returned by GetTimezoneInformation().
242 static char * fixtzname(char * dest
, int destsize
, const char * src
)
245 while (src
[i
] && j
< destsize
-1) {
246 int i2
= (const char *)_mbsinc((const unsigned char *)src
+i
) - src
;
248 i
= i2
; // Ignore multibyte chars
250 if ('A' <= src
[i
] && src
[i
] <= 'Z')
251 dest
[j
++] = src
[i
]; // "Pacific Standard Time" => "PST"
262 // This value follows the peripheral device type value as defined in
263 // SCSI Primary Commands, ANSI INCITS 301:1997. It is also used in
264 // the ATA standard for packet devices to define the device type.
265 const char *packetdevicetype(int type
){
267 return packet_types
[type
];
275 // Runtime check of byte ordering, throws if different from isbigendian().
276 static void check_endianness()
279 // Force compile error if int type is not 32bit.
280 unsigned char c
[sizeof(unsigned) == 4 ? 4 : -1];
286 case 0x01020304: big
= 1; break;
287 case 0x04030201: big
= 0; break;
290 if (big
!= (isbigendian() ? 1 : 0))
291 throw std::logic_error("CPU endianness does not match compile time test");
294 // Utility function prints date and time and timezone into a character
295 // buffer of length>=64. All the fuss is needed to get the right
296 // timezone info (sigh).
297 void dateandtimezoneepoch(char *buffer
, time_t tval
){
299 const char *timezonename
;
300 char datebuffer
[DATEANDEPOCHLEN
];
303 FixGlibcTimeZoneBug();
305 // Get the time structure. We need this to determine if we are in
306 // daylight savings time or not.
307 tmval
=localtime(&tval
);
309 // Convert to an ASCII string, put in datebuffer
310 // same as: asctime_r(tmval, datebuffer);
311 strncpy(datebuffer
, asctime(tmval
), DATEANDEPOCHLEN
);
312 datebuffer
[DATEANDEPOCHLEN
-1]='\0';
315 lenm1
=strlen(datebuffer
)-1;
316 datebuffer
[lenm1
>=0?lenm1
:0]='\0';
318 #if defined(_WIN32) && defined(_MSC_VER)
319 // tzname is missing in MSVC14
320 #define tzname _tzname
323 // correct timezone name
324 if (tmval
->tm_isdst
==0)
325 // standard time zone
326 timezonename
=tzname
[0];
327 else if (tmval
->tm_isdst
>0)
328 // daylight savings in effect
329 timezonename
=tzname
[1];
331 // unable to determine if daylight savings in effect
335 // Fix long non-ascii timezone names
336 // cppcheck-suppress variableScope
337 char tzfixbuf
[6+1] = "";
339 timezonename
=fixtzname(tzfixbuf
, sizeof(tzfixbuf
), timezonename
);
342 // Finally put the information into the buffer as needed.
343 snprintf(buffer
, DATEANDEPOCHLEN
, "%s %s", datebuffer
, timezonename
);
348 // Date and timezone gets printed into string pointed to by buffer
349 void dateandtimezone(char *buffer
){
351 // Get the epoch (time in seconds since Jan 1 1970)
352 time_t tval
=time(NULL
);
354 dateandtimezoneepoch(buffer
, tval
);
358 // A replacement for perror() that sends output to our choice of
359 // printing. If errno not set then just print message.
360 void syserror(const char *message
){
363 // Get the correct system error message:
364 const char *errormessage
=strerror(errno
);
366 // Check that caller has handed a sensible string, and provide
367 // appropriate output. See perrror(3) man page to understand better.
368 if (message
&& *message
)
369 pout("%s: %s\n",message
, errormessage
);
371 pout("%s\n",errormessage
);
373 else if (message
&& *message
)
374 pout("%s\n",message
);
379 // Check regular expression for non-portable features.
381 // POSIX extended regular expressions interpret unmatched ')' ordinary:
382 // "The close-parenthesis shall be considered special in this context
383 // only if matched with a preceding open-parenthesis."
385 // GNU libc and BSD libc support unmatched ')', Cygwin reports an error.
387 // POSIX extended regular expressions do not define empty subexpressions:
388 // "A vertical-line appearing first or last in an ERE, or immediately following
389 // a vertical-line or a left-parenthesis, or immediately preceding a
390 // right-parenthesis, produces undefined results."
392 // GNU libc and Cygwin support empty subexpressions, BSD libc reports an error.
394 static const char * check_regex(const char * pattern
)
399 for (int i
= 0; (c
= pattern
[i
]); i
++) {
409 if (pattern
[++i
] == '^')
413 while ((c
= pattern
[i
]) && c
!= ']')
420 // Check "(...)" nesting
423 else if (c
== ')' && --level
< 0)
424 return "Unmatched ')'";
426 // Check for leading/trailing '|' or "||", "|)", "|$", "(|", "^|"
428 if ( (c
== '|' && ( i
== 0 || !(c1
= pattern
[i
+1])
429 || c1
== '|' || c1
== ')' || c1
== '$'))
430 || ((c
== '(' || c
== '^') && pattern
[i
+1] == '|') )
431 return "Empty '|' subexpression";
434 return (const char *)0;
437 // Wrapper class for regex(3)
439 regular_expression::regular_expression()
442 memset(&m_regex_buf
, 0, sizeof(m_regex_buf
));
445 regular_expression::regular_expression(const char * pattern
, int flags
,
446 bool throw_on_error
/*= true*/)
448 memset(&m_regex_buf
, 0, sizeof(m_regex_buf
));
449 if (!compile(pattern
, flags
) && throw_on_error
)
450 throw std::runtime_error(strprintf(
451 "error in regular expression \"%s\": %s",
452 m_pattern
.c_str(), m_errmsg
.c_str()));
455 regular_expression::~regular_expression()
460 regular_expression::regular_expression(const regular_expression
& x
)
462 memset(&m_regex_buf
, 0, sizeof(m_regex_buf
));
466 regular_expression
& regular_expression::operator=(const regular_expression
& x
)
473 void regular_expression::free_buf()
475 if (nonempty(&m_regex_buf
, sizeof(m_regex_buf
))) {
476 regfree(&m_regex_buf
);
477 memset(&m_regex_buf
, 0, sizeof(m_regex_buf
));
481 void regular_expression::copy(const regular_expression
& x
)
483 m_pattern
= x
.m_pattern
;
485 m_errmsg
= x
.m_errmsg
;
487 if (!m_pattern
.empty() && m_errmsg
.empty()) {
488 // There is no POSIX compiled-regex-copy command.
490 throw std::runtime_error(strprintf(
491 "Unable to recompile regular expression \"%s\": %s",
492 m_pattern
.c_str(), m_errmsg
.c_str()));
496 bool regular_expression::compile(const char * pattern
, int flags
)
504 bool regular_expression::compile()
506 int errcode
= regcomp(&m_regex_buf
, m_pattern
.c_str(), m_flags
);
509 regerror(errcode
, &m_regex_buf
, errmsg
, sizeof(errmsg
));
515 const char * errmsg
= check_regex(m_pattern
.c_str());
526 #ifndef HAVE_STRTOULL
527 // Replacement for missing strtoull() (Linux with libc < 6, MSVC)
528 // Functionality reduced to requirements of smartd and split_selective_arg().
530 uint64_t strtoull(const char * p
, char * * endp
, int base
)
532 uint64_t result
, maxres
;
538 if (p
[i
] == 'x' || p
[i
] == 'X') {
550 maxres
= ~(uint64_t)0 / (unsigned)base
;
553 if ('0' <= c
&& c
<= '9')
555 else if ('A' <= c
&& c
<= 'Z')
556 digit
= c
- 'A' + 10;
557 else if ('a' <= c
&& c
<= 'z')
558 digit
= c
- 'a' + 10;
561 if (digit
>= (unsigned)base
)
563 if (!( result
< maxres
564 || (result
== maxres
&& digit
<= ~(uint64_t)0 % (unsigned)base
))) {
565 result
= ~(uint64_t)0; errno
= ERANGE
; // return on overflow
568 result
= result
* (unsigned)base
+ digit
;
572 *endp
= (char *)p
+ i
- 1;
575 #endif // HAVE_STRTOLL
577 // Splits an argument to the -t option that is assumed to be of the form
578 // "selective,%lld-%lld" (prefixes of "0" (for octal) and "0x"/"0X" (for hex)
579 // are allowed). The first long long int is assigned to *start and the second
580 // to *stop. Returns zero if successful and non-zero otherwise.
581 int split_selective_arg(char *s
, uint64_t *start
,
582 uint64_t *stop
, int *mode
)
585 if (!(s
= strchr(s
, ',')))
588 if (!isdigit((int)(*++s
))) {
590 if (!strncmp(s
, "redo", 4))
592 else if (!strncmp(s
, "next", 4))
594 else if (!strncmp(s
, "cont", 4))
607 // Last argument to strtoull (the base) is 0 meaning that decimal is assumed
608 // unless prefixes of "0" (for octal) or "0x"/"0X" (for hex) are used.
609 *start
= strtoull(s
, &tailptr
, 0);
612 if (!(!errno
&& (add
|| *s
== '-')))
614 if (!strcmp(s
, "-max")) {
615 *stop
= ~(uint64_t)0; // replaced by max LBA later
621 *stop
= strtoull(s
+1, &tailptr
, 0);
622 if (errno
|| *tailptr
!= '\0')
627 *stop
+= *start
; // -t select,N+M => -t select,N,(N+M-1)
632 // Returns true if region of memory contains non-zero entries
633 bool nonempty(const void * data
, int size
)
635 for (int i
= 0; i
< size
; i
++)
636 if (((const unsigned char *)data
)[i
])
641 // Copy not null terminated char array to null terminated string.
642 // Replace non-ascii characters. Remove leading and trailing blanks.
643 const char * format_char_array(char * str
, int strsize
, const char * chr
, int chrsize
)
646 while (b
< chrsize
&& chr
[b
] == ' ')
649 while (b
+n
< chrsize
&& chr
[b
+n
])
651 while (n
> 0 && chr
[b
+n
-1] == ' ')
657 for (int i
= 0; i
< n
; i
++) {
659 str
[i
] = (' ' <= c
&& c
<= '~' ? c
: '?');
666 // Format integer with thousands separator
667 const char * format_with_thousands_sep(char * str
, int strsize
, uint64_t val
,
668 const char * thousands_sep
/* = 0 */)
670 if (!thousands_sep
) {
673 setlocale(LC_ALL
, "");
674 const struct lconv
* currentlocale
= localeconv();
675 if (*(currentlocale
->thousands_sep
))
676 thousands_sep
= currentlocale
->thousands_sep
;
681 snprintf(num
, sizeof(num
), "%" PRIu64
, val
);
682 int numlen
= strlen(num
);
687 while (i
< numlen
&& (numlen
- i
) % 3 != 0 && j
< strsize
-1);
690 while (i
< numlen
&& j
< strsize
-1) {
691 j
+= snprintf(str
+j
, strsize
-j
, "%s%.3s", thousands_sep
, num
+i
);
698 // Format capacity with SI prefixes
699 const char * format_capacity(char * str
, int strsize
, uint64_t val
,
700 const char * decimal_point
/* = 0 */)
702 if (!decimal_point
) {
705 setlocale(LC_ALL
, "");
706 const struct lconv
* currentlocale
= localeconv();
707 if (*(currentlocale
->decimal_point
))
708 decimal_point
= currentlocale
->decimal_point
;
712 const unsigned factor
= 1000; // 1024 for KiB,MiB,...
713 static const char prefixes
[] = " KMGTP";
715 // Find d with val in [d, d*factor)
718 for (uint64_t d2
= d
* factor
; val
>= d2
; d2
*= factor
) {
720 if (++i
>= sizeof(prefixes
)-2)
725 uint64_t n
= val
/ d
;
727 snprintf(str
, strsize
, "%u B", (unsigned)n
);
728 else if (n
>= 100) // "123 xB"
729 snprintf(str
, strsize
, "%" PRIu64
" %cB", n
, prefixes
[i
]);
730 else if (n
>= 10) // "12.3 xB"
731 snprintf(str
, strsize
, "%" PRIu64
"%s%u %cB", n
, decimal_point
,
732 (unsigned)(((val
% d
) * 10) / d
), prefixes
[i
]);
734 snprintf(str
, strsize
, "%" PRIu64
"%s%02u %cB", n
, decimal_point
,
735 (unsigned)(((val
% d
) * 100) / d
), prefixes
[i
]);
740 // return (v)sprintf() formatted std::string
741 __attribute_format_printf(1, 0)
742 std::string
vstrprintf(const char * fmt
, va_list ap
)
745 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
746 buf
[sizeof(buf
)-1] = 0;
750 std::string
strprintf(const char * fmt
, ...)
752 va_list ap
; va_start(ap
, fmt
);
753 std::string str
= vstrprintf(fmt
, ap
);
759 #ifndef HAVE_WORKING_SNPRINTF
760 // Some versions of (v)snprintf() don't append null char (MSVCRT.DLL),
761 // and/or return -1 on output truncation (glibc <= 2.0.6).
762 // Below are sane replacements substituted by #define in utility.h.
765 #if defined(_WIN32) && defined(_MSC_VER)
766 #define vsnprintf _vsnprintf
769 int safe_vsnprintf(char *buf
, int size
, const char *fmt
, va_list ap
)
774 i
= vsnprintf(buf
, size
, fmt
, ap
);
775 if (0 <= i
&& i
< size
)
778 return strlen(buf
); // Note: cannot detect for overflow, not necessary here.
781 int safe_snprintf(char *buf
, int size
, const char *fmt
, ...)
785 i
= safe_vsnprintf(buf
, size
, fmt
, ap
);
790 static void check_snprintf() {}
792 #elif defined(__GNUC__) && (__GNUC__ >= 7)
794 // G++ 7+: Assume sane implementation and avoid -Wformat-truncation warning
795 static void check_snprintf() {}
799 static void check_snprintf()
801 char buf
[] = "ABCDEFGHI";
802 int n1
= snprintf(buf
, 8, "123456789");
803 int n2
= snprintf(buf
, 0, "X");
804 if (!(!strcmp(buf
, "1234567") && n1
== 9 && n2
== 1))
805 throw std::logic_error("Function snprintf() does not conform to C99");
808 #endif // HAVE_WORKING_SNPRINTF
810 // Runtime check of ./configure result, throws on error.