Line data Source code
1 : /*
2 : * Copyright (C) 2011 Andrea Mazzoleni
3 : *
4 : * This program is free software: you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation, either version 3 of the License, or
7 : * (at your option) any later version.
8 : *
9 : * This program is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * GNU General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU General Public License
15 : * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 : */
17 :
18 : #include "portable.h"
19 :
20 : #include "support.h"
21 :
22 : /****************************************************************************/
23 : /* lock */
24 :
25 : /**
26 : * Locks used externally.
27 : */
28 : #if HAVE_THREAD
29 : static thread_mutex_t msg_lock;
30 : static thread_mutex_t memory_lock;
31 : static thread_mutex_t random_lock;
32 : #endif
33 :
34 22554567 : void lock_msg(void)
35 : {
36 : #if HAVE_THREAD
37 22554567 : thread_mutex_lock(&msg_lock);
38 : #endif
39 22554567 : }
40 :
41 22554567 : void unlock_msg(void)
42 : {
43 : #if HAVE_THREAD
44 22554567 : thread_mutex_unlock(&msg_lock);
45 : #endif
46 22554567 : }
47 :
48 20941303 : void lock_memory(void)
49 : {
50 : #if HAVE_THREAD
51 20941303 : thread_mutex_lock(&memory_lock);
52 : #endif
53 20941303 : }
54 :
55 20941303 : void unlock_memory(void)
56 : {
57 : #if HAVE_THREAD
58 20941303 : thread_mutex_unlock(&memory_lock);
59 : #endif
60 20941303 : }
61 :
62 0 : void lock_random(void)
63 : {
64 : #if HAVE_THREAD
65 0 : thread_mutex_lock(&random_lock);
66 : #endif
67 0 : }
68 :
69 0 : void unlock_random(void)
70 : {
71 : #if HAVE_THREAD
72 0 : thread_mutex_unlock(&random_lock);
73 : #endif
74 0 : }
75 :
76 :
77 310 : void lock_init(void)
78 : {
79 : #if HAVE_THREAD
80 : /* initialize the locks as first operation as log_fatal depends on them */
81 310 : thread_mutex_init(&msg_lock);
82 310 : thread_mutex_init(&memory_lock);
83 310 : thread_mutex_init(&random_lock);
84 : #endif
85 310 : }
86 :
87 288 : void lock_done(void)
88 : {
89 : #if HAVE_THREAD
90 288 : thread_mutex_destroy(&msg_lock);
91 288 : thread_mutex_destroy(&memory_lock);
92 288 : thread_mutex_destroy(&random_lock);
93 : #endif
94 288 : }
95 :
96 : /****************************************************************************/
97 : /* random */
98 :
99 : static uint64_t random_state = 1;
100 :
101 283 : void random_reseed(void)
102 : {
103 283 : random_state = tick();
104 283 : }
105 :
106 0 : unsigned char random_u8(void)
107 : {
108 0 : return random_u64() & 0xFF;
109 : }
110 :
111 : /*
112 : * SplitMix64
113 : *
114 : * - Zero-safe: Any 64-bit seed is valid (even 0).
115 : * - Full period: Guaranteed to visit every 2^64 value.
116 : * - Logic: Uses a Weyl sequence + MurmurHash3-style finalizer.
117 : *
118 : * See: https://rosettacode.org/wiki/Pseudo-random_numbers/Splitmix64
119 : */
120 0 : uint64_t random_u64(void)
121 : {
122 : uint64_t z;
123 :
124 0 : lock_random();
125 :
126 0 : z = random_state += 0x9E3779B97F4A7C15ULL;
127 :
128 0 : unlock_random();
129 :
130 0 : z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL;
131 0 : z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL;
132 :
133 0 : return z ^ (z >> 31);
134 : }
135 :
136 : /****************************************************************************/
137 : /* error */
138 :
139 1830939 : int is_hw(int err)
140 : {
141 1830939 : if (err == EIO)
142 12 : return 1;
143 : #ifdef EFSCORRUPTED
144 : if (err == EFSCORRUPTED) /* used by XFS inside the kernel - never expected in user mode as converted to EUCLEAN */
145 : return 1;
146 : #endif
147 : #ifdef EUCLEAN
148 1830927 : if (err == EUCLEAN) /* used by XFS at user level instead of EFSCORRUPTED */
149 0 : return 1;
150 : #endif
151 : #ifdef EBADCRC
152 : if (err == EBADCRC) /* used by BTRFS - never expected in user mode as converted to EIO */
153 : return 1;
154 : #endif
155 : #ifdef EBADMSG
156 1830927 : if (err == EBADMSG) /* used by BTRFS - never expected in user mode as converted to EIO */
157 0 : return 1;
158 : #endif
159 : #ifdef ENOMEDIUM
160 1830927 : if (err == ENOMEDIUM) /* medium removed */
161 0 : return 1;
162 : #endif
163 : #ifdef EHWPOISON
164 1830927 : if (err == EHWPOISON) /* hardware memory error */
165 0 : return 1;
166 : #endif
167 1830927 : return 0;
168 : }
169 :
170 0 : void log_fatal_errno(int err, const char* name)
171 : {
172 0 : if (err == EIO) {
173 0 : log_fatal(err, "DANGER! Unexpected input/output error in disk %s. It isn't possible to continue.\n", name);
174 : #ifdef EFSCORRUPTED
175 : } else if (err == EFSCORRUPTED) {
176 : log_fatal(err, "DANGER! Unexpected corrupted error in disk %s. It isn't possible to continue.\n", name);
177 : #endif
178 : #ifdef EUCLEAN
179 0 : } else if (err == EUCLEAN) {
180 0 : log_fatal(err, "DANGER! Unexpected corrupted error in disk %s. It isn't possible to continue.\n", name);
181 : #endif
182 : #ifdef EBADCRC
183 : } else if (err == EBADCRC) {
184 : log_fatal(err, "DANGER! Unexpected bad crc error in disk %s. It isn't possible to continue.\n", name);
185 : #endif
186 : #ifdef EBADMSG
187 0 : } else if (err == EBADMSG) {
188 0 : log_fatal(err, "DANGER! Unexpected bad crc error in disk %s. It isn't possible to continue.\n", name);
189 : #endif
190 : #ifdef ENOMEDIUM
191 0 : } else if (err == ENOMEDIUM) {
192 0 : log_fatal(err, "DANGER! Unexpected medium removed in disk %s. It isn't possible to continue.\n", name);
193 : #endif
194 : #ifdef EHWPOISON
195 0 : } else if (err == EHWPOISON) {
196 0 : log_fatal(err, "DANGER! Unexpected memory error in disk %s. It isn't possible to continue.\n", name);
197 : #endif
198 0 : } else if (err == EACCES) {
199 0 : log_fatal(err, "WARNING! Grant permission in the disk %s. It isn't possible to continue.\n", name);
200 0 : } else if (err == ENOSPC) {
201 0 : log_fatal(err, "WARNING! Ensure there is free space on the disk %s. It isn't possible to continue.\n", name);
202 : } else {
203 0 : log_fatal(err, "WARNING! Without a working %s disk, it isn't possible to continue.\n", name);
204 : }
205 0 : }
206 :
207 27 : void log_error_errno(int err, const char* name)
208 : {
209 27 : if (err == EIO) {
210 0 : log_fatal(err, "DANGER! Unexpected input/output error in disk %s.\n", name);
211 : #ifdef EFSCORRUPTED
212 : } else if (err == EFSCORRUPTED) {
213 : log_fatal(err, "DANGER! Unexpected corrupted error in disk %s.\n", name);
214 : #endif
215 : #ifdef EUCLEAN
216 27 : } else if (err == EUCLEAN) {
217 0 : log_fatal(err, "DANGER! Unexpected corrupted error in disk %s.\n", name);
218 : #endif
219 : #ifdef EBADCRC
220 : } else if (err == EBADCRC) {
221 : log_fatal(err, "DANGER! Unexpected bad crc error in disk %s.\n", name);
222 : #endif
223 : #ifdef EBADMSG
224 27 : } else if (err == EBADMSG) {
225 0 : log_fatal(err, "DANGER! Unexpected bad crc error in disk %s.\n", name);
226 : #endif
227 : #ifdef ENOMEDIUM
228 27 : } else if (err == ENOMEDIUM) {
229 0 : log_fatal(err, "DANGER! Unexpected medium removed in disk %s.\n", name);
230 : #endif
231 : #ifdef EHWPOISON
232 27 : } else if (err == EHWPOISON) {
233 0 : log_fatal(err, "DANGER! Unexpected memory error in disk %s.\n", name);
234 : #endif
235 27 : } else if (err == EACCES) {
236 12 : log_error(err, "WARNING! Grant permission in the disk %s.\n", name);
237 15 : } else if (err == ENOSPC) {
238 0 : log_error(err, "WARNING! Ensure there is free space on the disk %s.\n", name);
239 15 : } else if (err == ENOENT) {
240 15 : log_error(err, "WARNING! You cannot modify files while running.\n");
241 : }
242 27 : }
243 :
244 : /****************************************************************************/
245 : /* print */
246 :
247 : int msg_level = 0;
248 : FILE* stdlog = 0;
249 : int msg_line_prev = 0; /**< Previous line width on stdout */
250 : int msg_line_curr = 0; /**< Current line width on stdout */
251 :
252 : /*
253 : * Note that in the following functions we always flush both
254 : * stdout and stderr, because we want to ensure that they mixes
255 : * well when redirected to files
256 : *
257 : * The buffering is similar at the "line buffered" one, that
258 : * is not available on Windows, so we emulate it in this way.
259 : *
260 : * For stdlog flushing is limited. To ensure flushing the
261 : * caller should use log_flush().
262 : */
263 :
264 41543 : static void vmsg(FILE* out, const char* format, va_list ap)
265 : {
266 41543 : char* dup = strdup_nofail(format);
267 41543 : int len = strlen(dup);
268 41543 : int written = 0;
269 41543 : char control = 0;
270 :
271 41543 : if (len > 0) {
272 41543 : if (dup[len - 1] == '\n') {
273 41533 : dup[len - 1] = 0;
274 41533 : control = '\n';
275 10 : } else if (dup[len - 1] == '\r') {
276 0 : dup[len - 1] = 0;
277 0 : control = '\r';
278 : }
279 : }
280 :
281 41543 : if (dup[0]) {
282 41440 : written = vfprintf(out, dup, ap);
283 : }
284 :
285 41543 : switch (control) {
286 10 : case 0 :
287 10 : msg_line_curr += written;
288 10 : break;
289 41533 : case '\n' :
290 41533 : msg_line_curr += written;
291 : /* writes spaces to overwrite any previous char */
292 41533 : while (msg_line_curr < msg_line_prev) {
293 0 : fprintf(out, " ");
294 0 : --msg_line_prev;
295 : }
296 41533 : msg_line_prev = 0;
297 41533 : msg_line_curr = 0;
298 41533 : fprintf(out, "\n");
299 41533 : break;
300 0 : case '\r' :
301 0 : msg_line_curr += written;
302 : /* writes spaces to overwrite any previous char */
303 0 : while (msg_line_curr < msg_line_prev) {
304 0 : fprintf(out, " ");
305 0 : --msg_line_prev;
306 : }
307 0 : msg_line_prev = msg_line_curr;
308 0 : msg_line_curr = 0;
309 0 : fprintf(out, "\r");
310 : }
311 :
312 41543 : free(dup);
313 41543 : }
314 :
315 803 : void log_fatal(int err, const char* format, ...)
316 : {
317 : va_list ap;
318 :
319 803 : lock_msg();
320 :
321 803 : if (stdlog) {
322 105 : if (is_hw(err))
323 12 : fprintf(stdlog, "msg:fatal_hardware: ");
324 : else
325 93 : fprintf(stdlog, "msg:fatal: ");
326 :
327 105 : va_start(ap, format);
328 105 : vfprintf(stdlog, format, ap);
329 105 : va_end(ap);
330 :
331 105 : fflush(stdlog);
332 : }
333 :
334 803 : va_start(ap, format);
335 803 : vmsg(stderr, format, ap);
336 803 : va_end(ap);
337 :
338 803 : fflush(stderr);
339 :
340 803 : unlock_msg();
341 803 : }
342 :
343 365227 : void log_error(int err, const char* format, ...)
344 : {
345 : va_list ap;
346 :
347 365227 : lock_msg();
348 :
349 365227 : if (stdlog) {
350 363389 : if (is_hw(err))
351 0 : fprintf(stdlog, "msg:error_hardware: ");
352 : else
353 363389 : fprintf(stdlog, "msg:error: ");
354 :
355 363389 : va_start(ap, format);
356 363389 : vfprintf(stdlog, format, ap);
357 363389 : va_end(ap);
358 :
359 363389 : fflush(stdlog);
360 : } else {
361 1838 : va_start(ap, format);
362 1838 : vmsg(stderr, format, ap);
363 1838 : va_end(ap);
364 :
365 1838 : fflush(stderr);
366 : }
367 :
368 365227 : unlock_msg();
369 365227 : }
370 :
371 4697 : void log_expected(int err, const char* format, ...)
372 : {
373 : va_list ap;
374 :
375 4697 : lock_msg();
376 :
377 4697 : if (stdlog) {
378 4697 : if (is_hw(err))
379 0 : fprintf(stdlog, "msg:error_hardware: "); /* we never expect an hardware error */
380 : else
381 4697 : fprintf(stdlog, "msg:expected: ");
382 :
383 4697 : va_start(ap, format);
384 4697 : vfprintf(stdlog, format, ap);
385 4697 : va_end(ap);
386 :
387 4697 : fflush(stdlog);
388 : }
389 :
390 4697 : unlock_msg();
391 4697 : }
392 :
393 21732148 : void log_tag(const char* format, ...)
394 : {
395 : va_list ap;
396 :
397 21732148 : lock_msg();
398 :
399 21732148 : if (stdlog) {
400 2567733 : va_start(ap, format);
401 2567733 : vfprintf(stdlog, format, ap);
402 2567733 : va_end(ap);
403 :
404 : /* here we intentionally don't flush to make the output faster */
405 : }
406 :
407 21732148 : unlock_msg();
408 21732148 : }
409 :
410 3649 : void log_flush(void)
411 : {
412 3649 : lock_msg();
413 :
414 3649 : if (stdlog)
415 334 : fflush(stdlog);
416 3649 : fflush(stdout);
417 3649 : fflush(stderr);
418 :
419 3649 : unlock_msg();
420 3649 : }
421 :
422 743 : void msg_status(const char* format, ...)
423 : {
424 : va_list ap;
425 :
426 743 : lock_msg();
427 :
428 743 : if (stdlog) {
429 407 : fprintf(stdlog, "msg:status: ");
430 :
431 407 : va_start(ap, format);
432 407 : vfprintf(stdlog, format, ap);
433 407 : va_end(ap);
434 :
435 407 : fflush(stdlog);
436 : }
437 :
438 743 : if (msg_level >= MSG_STATUS) {
439 743 : va_start(ap, format);
440 743 : vmsg(stdout, format, ap);
441 743 : va_end(ap);
442 : }
443 :
444 743 : unlock_msg();
445 743 : }
446 :
447 312495 : void msg_info(const char* format, ...)
448 : {
449 : va_list ap;
450 :
451 312495 : lock_msg();
452 :
453 : /* don't output in stdlog as these messages */
454 : /* are always paired with a msg_tag() call */
455 :
456 312495 : if (msg_level >= MSG_INFO) {
457 37886 : va_start(ap, format);
458 37886 : vmsg(stdout, format, ap);
459 37886 : va_end(ap);
460 :
461 37886 : fflush(stdout);
462 : }
463 :
464 312495 : unlock_msg();
465 312495 : }
466 :
467 5081 : void msg_progress(const char* format, ...)
468 : {
469 : va_list ap;
470 :
471 5081 : lock_msg();
472 :
473 5081 : if (stdlog) {
474 901 : fprintf(stdlog, "msg:progress: ");
475 :
476 901 : va_start(ap, format);
477 901 : vfprintf(stdlog, format, ap);
478 901 : va_end(ap);
479 :
480 901 : fflush(stdlog);
481 : }
482 :
483 5081 : if (msg_level >= MSG_PROGRESS) {
484 174 : va_start(ap, format);
485 174 : vmsg(stdout, format, ap);
486 174 : va_end(ap);
487 :
488 174 : fflush(stdout);
489 : }
490 :
491 5081 : unlock_msg();
492 5081 : }
493 :
494 2118 : void msg_bar(const char* format, ...)
495 : {
496 : va_list ap;
497 :
498 2118 : lock_msg();
499 :
500 : /* don't output in stdlog as these messages */
501 : /* are intended for screen only */
502 : /* also don't flush stdout as they are intended to be partial messages */
503 :
504 2118 : if (msg_level >= MSG_BAR) {
505 0 : va_start(ap, format);
506 0 : vmsg(stdout, format, ap);
507 0 : va_end(ap);
508 : }
509 :
510 2118 : unlock_msg();
511 2118 : }
512 :
513 127020 : void msg_verbose(const char* format, ...)
514 : {
515 : va_list ap;
516 :
517 127020 : lock_msg();
518 :
519 127020 : if (stdlog) {
520 125051 : fprintf(stdlog, "msg:verbose: ");
521 :
522 125051 : va_start(ap, format);
523 125051 : vfprintf(stdlog, format, ap);
524 125051 : va_end(ap);
525 :
526 125051 : fflush(stdlog);
527 : }
528 :
529 127020 : if (msg_level >= MSG_VERBOSE) {
530 99 : va_start(ap, format);
531 99 : vmsg(stdout, format, ap);
532 99 : va_end(ap);
533 :
534 99 : fflush(stdout);
535 : }
536 :
537 127020 : unlock_msg();
538 127020 : }
539 :
540 586 : void msg_flush(void)
541 : {
542 586 : lock_msg();
543 :
544 586 : fflush(stdout);
545 586 : fflush(stderr);
546 :
547 586 : unlock_msg();
548 586 : }
549 :
550 77 : void printc(char c, size_t pad)
551 : {
552 135 : while (pad) {
553 : /* group writes in long pieces */
554 : char buf[128];
555 58 : size_t len = pad;
556 :
557 58 : if (len >= sizeof(buf))
558 0 : len = sizeof(buf) - 1;
559 :
560 58 : memset(buf, c, len);
561 58 : buf[len] = 0;
562 :
563 58 : fputs(buf, stdout);
564 :
565 58 : pad -= len;
566 : }
567 77 : }
568 :
569 34 : void printr(const char* str, size_t pad)
570 : {
571 : size_t len;
572 :
573 34 : len = strlen(str);
574 :
575 34 : if (len < pad)
576 34 : printc(' ', pad - len);
577 :
578 34 : fputs(str, stdout);
579 34 : }
580 :
581 142 : void printl(const char* str, size_t pad)
582 : {
583 : size_t len;
584 :
585 142 : fputs(str, stdout);
586 :
587 142 : len = strlen(str);
588 :
589 142 : if (len < pad)
590 6 : printc(' ', pad - len);
591 142 : }
592 :
593 18 : void printp(double v, size_t pad)
594 : {
595 : char buf[64];
596 18 : const char* s = "%";
597 :
598 18 : if (v > 0.1)
599 0 : snprintf(buf, sizeof(buf), "%5.2f%s", v, s);
600 18 : else if (v > 0.01)
601 0 : snprintf(buf, sizeof(buf), "%6.3f%s", v, s);
602 18 : else if (v > 0.001)
603 0 : snprintf(buf, sizeof(buf), "%7.4f%s", v, s);
604 18 : else if (v > 0.0001)
605 0 : snprintf(buf, sizeof(buf), "%8.5f%s", v, s);
606 18 : else if (v > 0.00001)
607 0 : snprintf(buf, sizeof(buf), "%9.6f%s", v, s);
608 18 : else if (v > 0.000001)
609 0 : snprintf(buf, sizeof(buf), "%10.7f%s", v, s);
610 18 : else if (v > 0.0000001)
611 0 : snprintf(buf, sizeof(buf), "%11.8f%s", v, s);
612 18 : else if (v > 0.00000001)
613 0 : snprintf(buf, sizeof(buf), "%12.9f%s", v, s);
614 18 : else if (v > 0.000000001)
615 0 : snprintf(buf, sizeof(buf), "%13.10f%s", v, s);
616 18 : else if (v > 0.0000000001)
617 0 : snprintf(buf, sizeof(buf), "%14.11f%s", v, s);
618 18 : else if (v > 0.00000000001)
619 0 : snprintf(buf, sizeof(buf), "%15.12f%s", v, s);
620 18 : else if (v > 0.000000000001)
621 0 : snprintf(buf, sizeof(buf), "%16.13f%s", v, s);
622 : else
623 18 : snprintf(buf, sizeof(buf), "%17.14f%s", v, s);
624 18 : printl(buf, pad);
625 18 : }
626 :
627 : #define charcat(c) \
628 : do { \
629 : if (p == end) { \
630 : goto bail; \
631 : } \
632 : *p++ = (c); \
633 : } while (0)
634 :
635 2652388 : const char* esc_tag(const char* str, char* buffer)
636 : {
637 2652388 : char* begin = buffer;
638 2652388 : char* end = begin + ESC_MAX;
639 2652388 : char* p = begin;
640 :
641 : /* copy string with escaping */
642 34792293 : while (*str) {
643 32139905 : char c = *str++;
644 :
645 32139905 : switch (c) {
646 3 : case '\n' :
647 3 : charcat('\\');
648 3 : charcat('n');
649 3 : break;
650 3 : case '\r' :
651 3 : charcat('\\');
652 3 : charcat('r');
653 3 : break;
654 4 : case ':' :
655 4 : charcat('\\');
656 4 : charcat('d');
657 4 : break;
658 6 : case '\\' :
659 6 : charcat('\\');
660 6 : charcat('\\');
661 6 : break;
662 32139889 : default :
663 32139889 : charcat(c);
664 32139889 : break;
665 : }
666 : }
667 :
668 : /* put final 0 */
669 2652388 : if (p == end)
670 0 : goto bail;
671 2652388 : *p = 0;
672 :
673 2652388 : return begin;
674 :
675 0 : bail:
676 : /* LCOV_EXCL_START */
677 : log_fatal(EINTERNAL, "Escape for log is too long\n");
678 : exit(EXIT_FAILURE);
679 : /* LCOV_EXCL_STOP */
680 : }
681 :
682 : #ifdef _WIN32
683 : static int needs_quote(const char* arg)
684 : {
685 : while (*arg) {
686 : char c = *arg;
687 : if (c == ' ' || c == '\t' || c == '\n' || c == '\r' ||
688 : c == '&' || c == '|' || c == '(' || c == ')' ||
689 : c == '<' || c == '>' || c == '^' || c == '"' ||
690 : c == '%' || c == '!' || c == '=' || c == ';' ||
691 : (unsigned char)c < 32 || c == 127)
692 : return 1;
693 : ++arg;
694 : }
695 :
696 : return 0;
697 : }
698 : #endif
699 :
700 : struct stream {
701 : const char* str;
702 : unsigned idx;
703 : const char** map;
704 : unsigned max;
705 : };
706 :
707 5261663 : static inline char ssget(struct stream* ss)
708 : {
709 : /* get the next char */
710 5261663 : char c = *ss->str++;
711 :
712 : /* if one string is finished, go to the next */
713 5297758 : while (c == 0 && ss->idx + 1 < ss->max) {
714 36095 : ss->str = ss->map[++ss->idx];
715 36095 : c = *ss->str++;
716 : }
717 :
718 5261663 : return c;
719 : }
720 :
721 : #ifdef _WIN32
722 : const char* esc_shell_multi(const char** str_map, unsigned str_max, char* buffer)
723 : {
724 : char* begin = buffer;
725 : char* end = begin + ESC_MAX;
726 : char* p = begin;
727 : struct stream ss;
728 : char c;
729 : unsigned i;
730 : int has_quote;
731 :
732 : has_quote = 0;
733 : for (i = 0; i < str_max; ++i) {
734 : if (needs_quote(str_map[i]))
735 : has_quote = 1;
736 : }
737 :
738 : ss.idx = 0;
739 : ss.str = str_map[0];
740 : ss.map = str_map;
741 : ss.max = str_max;
742 :
743 : if (!has_quote) {
744 : c = ssget(&ss);
745 : while (c) {
746 : charcat(c);
747 : c = ssget(&ss);
748 : }
749 : } else {
750 : /* starting quote */
751 : charcat('"');
752 :
753 : c = ssget(&ss);
754 : while (c) {
755 : int bl = 0;
756 : while (c == '\\') {
757 : ++bl;
758 : c = ssget(&ss);
759 : }
760 :
761 : if (c == 0) {
762 : /* double backslashes before closing quote */
763 : bl = bl * 2;
764 : while (bl--)
765 : charcat('\\');
766 : break;
767 : } else if (c == '"') {
768 : /* double backslashes + escape the quote */
769 : bl = bl * 2 + 1;
770 : while (bl--)
771 : charcat('\\');
772 : charcat('"');
773 : } else {
774 : /* normal backslashes */
775 : while (bl--)
776 : charcat('\\');
777 : charcat(c);
778 : }
779 :
780 : c = ssget(&ss);
781 : }
782 :
783 : /* ending quote */
784 : charcat('"');
785 : }
786 :
787 : /* put final 0 */
788 : charcat(0);
789 :
790 : return begin;
791 :
792 : bail:
793 : /* LCOV_EXCL_START */
794 : log_fatal(EINTERNAL, "Escape for shell is too long\n");
795 : exit(EXIT_FAILURE);
796 : /* LCOV_EXCL_STOP */
797 : }
798 : #else
799 366218 : const char* esc_shell_multi(const char** str_map, unsigned str_max, char* buffer)
800 : {
801 366218 : char* begin = buffer;
802 366218 : char* end = begin + ESC_MAX;
803 366218 : char* p = begin;
804 : struct stream ss;
805 : char c;
806 :
807 366218 : ss.idx = 0;
808 366218 : ss.str = str_map[0];
809 366218 : ss.map = str_map;
810 366218 : ss.max = str_max;
811 :
812 366218 : c = ssget(&ss);
813 5261663 : while (c) {
814 4895445 : switch (c) {
815 : /* special chars that need to be quoted */
816 81442 : case ' ' : /* space */
817 : case '\t' : /* tab */
818 : case '\n' : /* newline */
819 : case '\r' : /* carriage return */
820 : case '~' : /* home */
821 : case '`' : /* command */
822 : case '#' : /* comment */
823 : case '$' : /* variable */
824 : case '&' : /* background job */
825 : case '*' : /* wildcard */
826 : case '(' : /* shell */
827 : case ')' : /* shell */
828 : case '\\' : /* quote */
829 : case '|' : /* pipe */
830 : case '[' : /* wildcard */
831 : case ']' : /* wildcard */
832 : case '{' : /* code */
833 : case '}' : /* code */
834 : case ';' : /* separator */
835 : case '\'' : /* quote */
836 : case '"' : /* quote */
837 : case '<' : /* redirect */
838 : case '>' : /* redirect */
839 : case '?' : /* wildcard */
840 : case '=' : /* assignment */
841 : case '!' : /* history expansion */
842 81442 : charcat('\\');
843 81442 : charcat(c);
844 81442 : break;
845 4814003 : default :
846 : /* check for control characters */
847 4814003 : if ((unsigned char)c < 32 || c == 127) {
848 6 : charcat('\\');
849 6 : charcat(c);
850 : } else {
851 4813997 : charcat(c);
852 : }
853 4814003 : break;
854 : }
855 :
856 4895445 : c = ssget(&ss);
857 : }
858 :
859 : /* put final 0 */
860 366218 : charcat(0);
861 :
862 366218 : return begin;
863 :
864 0 : bail:
865 : /* LCOV_EXCL_START */
866 : log_fatal(EINTERNAL, "Escape for shell is too long\n");
867 : exit(EXIT_FAILURE);
868 : /* LCOV_EXCL_STOP */
869 : }
870 : #endif
871 :
872 21 : char* strpolish(char* s)
873 : {
874 21 : char* i = s;
875 :
876 1030 : while (*i) {
877 1009 : if (isspace(*i) || !isprint(*i))
878 119 : *i = ' ';
879 1009 : ++i;
880 : }
881 :
882 21 : return s;
883 : }
884 :
885 1718 : unsigned strsplit(char** split_map, unsigned split_max, char* str, const char* delimiters)
886 : {
887 1718 : unsigned mac = 0;
888 :
889 : /* skip initial delimiters */
890 1718 : str += strspn(str, delimiters);
891 :
892 8782 : while (*str != 0 || mac == split_max) {
893 : /* start of the token */
894 7064 : split_map[mac] = str;
895 7064 : ++mac;
896 :
897 : /* find the first delimiter or the end of the string */
898 7064 : str += strcspn(str, delimiters);
899 :
900 : /* put the final terminator if missing */
901 7064 : if (*str != 0)
902 5538 : *str++ = 0;
903 :
904 : /* skip trailing delimiters */
905 7064 : str += strspn(str, delimiters);
906 : }
907 :
908 1718 : return mac;
909 : }
910 :
911 13 : char* strtrim(char* str)
912 : {
913 : char* begin;
914 : char* end;
915 :
916 13 : begin = str;
917 14 : while (begin[0] && isspace((unsigned char)begin[0]))
918 1 : ++begin;
919 :
920 13 : end = begin + strlen(begin);
921 28 : while (end > begin && isspace((unsigned char)end[-1]))
922 15 : --end;
923 :
924 13 : end[0] = 0;
925 :
926 13 : if (begin != end)
927 13 : memmove(str, begin, end - begin + 1);
928 :
929 13 : return str;
930 : }
931 :
932 2 : char* strlwr(char* str)
933 : {
934 2 : char* s = str;
935 :
936 24 : while (*s) {
937 22 : *s = tolower((unsigned char)*s);
938 22 : ++s;
939 : }
940 :
941 2 : return str;
942 : }
943 :
944 11 : char* worddigitstr(const char* haystack, const char* needle)
945 : {
946 11 : size_t len = strlen(needle);
947 : const char* s;
948 :
949 11 : if (len == 0)
950 1 : return NULL;
951 :
952 11 : for (s = haystack; (s = strstr(s, needle)) != NULL; ++s) {
953 :
954 : /* left boundary */
955 8 : if (s == haystack || isspace((unsigned char)s[-1]) || isdigit((unsigned char)s[-1])) {
956 : /* right boundary */
957 7 : if (s[len] == '\0' || isspace((unsigned char)s[len]) || isdigit((unsigned char)s[len])) {
958 7 : return (char*)s;
959 : }
960 : }
961 : }
962 :
963 3 : return NULL;
964 : }
965 :
966 : /****************************************************************************/
967 : /* path */
968 :
969 1902922 : void pathcpy(char* dst, size_t size, const char* src)
970 : {
971 1902922 : size_t len = strlen(src);
972 :
973 1902922 : if (len + 1 > size) {
974 : /* LCOV_EXCL_START */
975 : log_fatal(EINTERNAL, "Path too long '%s'\n", src);
976 : os_abort();
977 : /* LCOV_EXCL_STOP */
978 : }
979 :
980 1902922 : memcpy(dst, src, len + 1);
981 1902922 : }
982 :
983 279 : void pathcat(char* dst, size_t size, const char* src)
984 : {
985 279 : size_t dst_len = strlen(dst);
986 279 : size_t src_len = strlen(src);
987 :
988 279 : if (dst_len + src_len + 1 > size) {
989 : /* LCOV_EXCL_START */
990 : log_fatal(EINTERNAL, "Path too long '%s%s'\n", dst, src);
991 : os_abort();
992 : /* LCOV_EXCL_STOP */
993 : }
994 :
995 279 : memcpy(dst + dst_len, src, src_len + 1);
996 279 : }
997 :
998 3601926 : void pathcatl(char* dst, size_t dst_len, size_t size, const char* src)
999 : {
1000 3601926 : size_t src_len = strlen(src);
1001 :
1002 3601926 : if (dst_len + src_len + 1 > size) {
1003 : /* LCOV_EXCL_START */
1004 : log_fatal(EINTERNAL, "Path too long '%s%s'\n", dst, src);
1005 : os_abort();
1006 : /* LCOV_EXCL_STOP */
1007 : }
1008 :
1009 3601926 : memcpy(dst + dst_len, src, src_len + 1);
1010 3601926 : }
1011 :
1012 788 : void pathcatc(char* dst, size_t size, char c)
1013 : {
1014 788 : size_t dst_len = strlen(dst);
1015 :
1016 788 : if (dst_len + 2 > size) {
1017 : /* LCOV_EXCL_START */
1018 : log_fatal(EINTERNAL, "Path too long '%s%c'\n", dst, c);
1019 : os_abort();
1020 : /* LCOV_EXCL_STOP */
1021 : }
1022 :
1023 788 : dst[dst_len] = c;
1024 788 : dst[dst_len + 1] = 0;
1025 788 : }
1026 :
1027 17981 : void pathimport(char* dst, size_t size, const char* src)
1028 : {
1029 17981 : pathcpy(dst, size, src);
1030 :
1031 : #ifdef _WIN32
1032 : /* convert the Windows dir separator '\' to C '/', */
1033 : /* and the Windows escaping char '^' to the fnmatch '\' */
1034 : while (*dst) {
1035 : switch (*dst) {
1036 : case '\\' :
1037 : *dst = '/';
1038 : break;
1039 : case '^' :
1040 : *dst = '\\';
1041 : break;
1042 : }
1043 : ++dst;
1044 : }
1045 : #endif
1046 17981 : }
1047 :
1048 12234 : void pathexport(char* dst, size_t size, const char* src)
1049 : {
1050 12234 : pathcpy(dst, size, src);
1051 :
1052 : #ifdef _WIN32
1053 : /* invert the import */
1054 : while (*dst) {
1055 : switch (*dst) {
1056 : case '/' :
1057 : *dst = '\\';
1058 : break;
1059 : case '\\' :
1060 : *dst = '^';
1061 : break;
1062 : }
1063 : ++dst;
1064 : }
1065 : #endif
1066 12234 : }
1067 :
1068 42979947 : void pathprint(char* dst, size_t size, const char* format, ...)
1069 : {
1070 : size_t len;
1071 : va_list ap;
1072 :
1073 42979947 : va_start(ap, format);
1074 42979947 : len = vsnprintf(dst, size, format, ap);
1075 42979947 : va_end(ap);
1076 :
1077 42979947 : if (len >= size) {
1078 : /* LCOV_EXCL_START */
1079 : if (size > 0) {
1080 : dst[size - 1] = 0;
1081 : log_fatal(EINTERNAL, "Path too long '%s...'\n", dst);
1082 : } else {
1083 : log_fatal(EINTERNAL, "Path too long for empty size'\n");
1084 : }
1085 : os_abort();
1086 : /* LCOV_EXCL_STOP */
1087 : }
1088 42979947 : }
1089 :
1090 7949 : void pathslash(char* dst, size_t size)
1091 : {
1092 7949 : size_t len = strlen(dst);
1093 :
1094 7949 : if (len > 0 && dst[len - 1] != '/') {
1095 6286 : if (len + 2 >= size) {
1096 : /* LCOV_EXCL_START */
1097 : log_fatal(EINTERNAL, "Path too long '%s/'\n", dst);
1098 : os_abort();
1099 : /* LCOV_EXCL_STOP */
1100 : }
1101 :
1102 6286 : dst[len] = '/';
1103 6286 : dst[len + 1] = 0;
1104 : }
1105 7949 : }
1106 :
1107 58108 : void pathcut(char* dst)
1108 : {
1109 58108 : char* slash = strrchr(dst, '/');
1110 :
1111 58108 : if (slash)
1112 58108 : slash[1] = 0;
1113 : else
1114 0 : dst[0] = 0;
1115 58108 : }
1116 :
1117 53116131 : int pathcmp(const char* a, const char* b)
1118 : {
1119 : #ifdef _WIN32
1120 : char ai[PATH_MAX];
1121 : char bi[PATH_MAX];
1122 :
1123 : /* import to convert \ to / */
1124 : pathimport(ai, sizeof(ai), a);
1125 : pathimport(bi, sizeof(bi), b);
1126 :
1127 : /* case insensitive compare in Windows */
1128 : return stricmp(ai, bi);
1129 : #else
1130 53116131 : return strcmp(a, b);
1131 : #endif
1132 : }
1133 :
1134 0 : int path_is_root_of(const char* root, const char* path)
1135 : {
1136 0 : while (*root && *path) {
1137 : #ifdef _WIN32
1138 : /* case insensitive compare in Windows */
1139 : char r = tolower((unsigned char)*root);
1140 : char p = tolower((unsigned char)*path);
1141 : if (r == '\\')
1142 : r = '/';
1143 : if (p == '\\')
1144 : p = '/';
1145 : if (r != p)
1146 : return 0;
1147 : #else
1148 0 : if (*root != *path)
1149 0 : return 0;
1150 : #endif
1151 0 : ++root;
1152 0 : ++path;
1153 : }
1154 :
1155 0 : return *root == 0 && *path != 0;
1156 : }
1157 :
1158 : /****************************************************************************/
1159 : /* file-system */
1160 :
1161 787726 : int mkancestor(const char* file)
1162 : {
1163 : char dir[PATH_MAX];
1164 : struct stat st;
1165 : char* c;
1166 :
1167 787726 : pathcpy(dir, sizeof(dir), file);
1168 :
1169 787726 : c = strrchr(dir, '/');
1170 787726 : if (!c) {
1171 : /* no ancestor */
1172 0 : return 0;
1173 : }
1174 :
1175 : /* clear the file */
1176 787726 : *c = 0;
1177 :
1178 : /* if it's the root dir */
1179 787726 : if (*dir == 0) {
1180 : /* nothing more to do */
1181 0 : return 0;
1182 : }
1183 :
1184 : #ifdef _WIN32
1185 : /* if it's a drive specification like "C:" */
1186 : if (isalpha(dir[0]) && dir[1] == ':' && dir[2] == 0) {
1187 : /* nothing more to do */
1188 : return 0;
1189 : }
1190 : #endif
1191 :
1192 : /*
1193 : * Check if the dir already exists using lstat().
1194 : *
1195 : * Note that in Windows when dealing with read-only media
1196 : * you cannot try to create the directory, and expecting
1197 : * the EEXIST error because the call will fail with ERROR_WRITE_PROTECTED.
1198 : *
1199 : * Also in Windows it's better to use lstat() than stat() because it
1200 : * doesn't need to open the dir with CreateFile().
1201 : */
1202 787726 : if (lstat(dir, &st) == 0) {
1203 : /* it already exists */
1204 787648 : return 0;
1205 : }
1206 :
1207 : /* recursively create them all */
1208 78 : if (mkancestor(dir) != 0) {
1209 : /* LCOV_EXCL_START */
1210 : return -1;
1211 : /* LCOV_EXCL_STOP */
1212 : }
1213 :
1214 : /* create it */
1215 78 : if (mkdir(dir, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) != 0) {
1216 : /* LCOV_EXCL_START */
1217 : log_fatal(errno, "Error creating directory '%s'. %s.\n", dir, strerror(errno));
1218 : return -1;
1219 : /* LCOV_EXCL_STOP */
1220 : }
1221 :
1222 78 : return 0;
1223 : }
1224 :
1225 121348 : int fmtime(int f, int64_t mtime_sec, int mtime_nsec)
1226 : {
1227 : #if HAVE_FUTIMENS
1228 : struct timespec tv[2];
1229 : #else
1230 : struct timeval tv[2];
1231 : #endif
1232 : int ret;
1233 :
1234 : #if HAVE_FUTIMENS /* futimens() is preferred because it gives nanosecond precision */
1235 121348 : tv[0].tv_sec = mtime_sec;
1236 121348 : if (mtime_nsec != STAT_NSEC_INVALID)
1237 121348 : tv[0].tv_nsec = mtime_nsec;
1238 : else
1239 0 : tv[0].tv_nsec = 0;
1240 121348 : tv[1].tv_sec = tv[0].tv_sec;
1241 121348 : tv[1].tv_nsec = tv[0].tv_nsec;
1242 :
1243 121348 : ret = futimens(f, tv);
1244 : #elif HAVE_FUTIMES /* fallback to futimes() if nanosecond precision is not available */
1245 : tv[0].tv_sec = mtime_sec;
1246 : if (mtime_nsec != STAT_NSEC_INVALID)
1247 : tv[0].tv_usec = mtime_nsec / 1000;
1248 : else
1249 : tv[0].tv_usec = 0;
1250 : tv[1].tv_sec = tv[0].tv_sec;
1251 : tv[1].tv_usec = tv[0].tv_usec;
1252 :
1253 : ret = futimes(f, tv);
1254 : #elif HAVE_FUTIMESAT /* fallback to futimesat() for Solaris, it only has futimesat() */
1255 : tv[0].tv_sec = mtime_sec;
1256 : if (mtime_nsec != STAT_NSEC_INVALID)
1257 : tv[0].tv_usec = mtime_nsec / 1000;
1258 : else
1259 : tv[0].tv_usec = 0;
1260 : tv[1].tv_sec = tv[0].tv_sec;
1261 : tv[1].tv_usec = tv[0].tv_usec;
1262 :
1263 : ret = futimesat(f, 0, tv);
1264 : #else
1265 : #error No function available to set file timestamps with sub-second precision
1266 : #endif
1267 :
1268 121348 : return ret;
1269 : }
1270 :
1271 11645 : int lmtime(const char* path, int64_t mtime_sec, int mtime_nsec)
1272 : {
1273 : #if HAVE_UTIMENSAT
1274 : struct timespec tv[2];
1275 : #else
1276 : struct timeval tv[2];
1277 : #endif
1278 : int ret;
1279 :
1280 : #if HAVE_UTIMENSAT /* utimensat() is preferred because it gives nanosecond precision */
1281 11645 : tv[0].tv_sec = mtime_sec;
1282 11645 : if (mtime_nsec != STAT_NSEC_INVALID)
1283 11645 : tv[0].tv_nsec = mtime_nsec;
1284 : else
1285 0 : tv[0].tv_nsec = 0;
1286 11645 : tv[1].tv_sec = tv[0].tv_sec;
1287 11645 : tv[1].tv_nsec = tv[0].tv_nsec;
1288 :
1289 11645 : ret = utimensat(AT_FDCWD, path, tv, AT_SYMLINK_NOFOLLOW);
1290 : #elif HAVE_LUTIMES /* fallback to lutimes() if nanosecond precision is not available */
1291 : tv[0].tv_sec = mtime_sec;
1292 : if (mtime_nsec != STAT_NSEC_INVALID)
1293 : tv[0].tv_usec = mtime_nsec / 1000;
1294 : else
1295 : tv[0].tv_usec = 0;
1296 : tv[1].tv_sec = tv[0].tv_sec;
1297 : tv[1].tv_usec = tv[0].tv_usec;
1298 :
1299 : ret = lutimes(path, tv);
1300 : #elif HAVE_FUTIMESAT /* fallback to futimesat() for Solaris, it only has futimesat() */
1301 : tv[0].tv_sec = mtime_sec;
1302 : if (mtime_nsec != STAT_NSEC_INVALID)
1303 : tv[0].tv_usec = mtime_nsec / 1000;
1304 : else
1305 : tv[0].tv_usec = 0;
1306 : tv[1].tv_sec = tv[0].tv_sec;
1307 : tv[1].tv_usec = tv[0].tv_usec;
1308 :
1309 : ret = futimesat(AT_FDCWD, path, tv);
1310 : #else
1311 : #error No function available to set file timestamps with sub-second precision
1312 : #endif
1313 :
1314 11645 : return ret;
1315 : }
1316 :
1317 : /****************************************************************************/
1318 : /* advise */
1319 :
1320 2489611 : void advise_init(struct advise_struct* advise, int mode)
1321 : {
1322 2489611 : advise->mode = mode;
1323 2489611 : advise->dirty_begin = 0;
1324 2489611 : advise->dirty_end = 0;
1325 2489611 : }
1326 :
1327 2489611 : int advise_flags(struct advise_struct* advise)
1328 : {
1329 2489611 : int flags = 0;
1330 :
1331 2489611 : if (advise->mode == ADVISE_SEQUENTIAL
1332 2478269 : || advise->mode == ADVISE_FLUSH
1333 2478269 : || advise->mode == ADVISE_FLUSH_WINDOW
1334 2466927 : || advise->mode == ADVISE_DISCARD
1335 2466927 : || advise->mode == ADVISE_DISCARD_WINDOW
1336 : )
1337 34026 : flags |= O_SEQUENTIAL;
1338 :
1339 : #if HAVE_DIRECT_IO
1340 2489611 : if (advise->mode == ADVISE_DIRECT)
1341 0 : flags |= O_DIRECT;
1342 : #endif
1343 :
1344 2489611 : return flags;
1345 : }
1346 :
1347 2410879 : int advise_open(struct advise_struct* advise, int f)
1348 : {
1349 : (void)advise;
1350 : (void)f;
1351 :
1352 : #if HAVE_POSIX_FADVISE
1353 2410879 : if (advise->mode == ADVISE_SEQUENTIAL
1354 2399537 : || advise->mode == ADVISE_FLUSH
1355 2399537 : || advise->mode == ADVISE_FLUSH_WINDOW
1356 2388195 : || advise->mode == ADVISE_DISCARD
1357 2388195 : || advise->mode == ADVISE_DISCARD_WINDOW
1358 : ) {
1359 : int ret;
1360 :
1361 : /* advise noreuse access, this avoids to pollute the page cache */
1362 : /* supported from Linux Kernel 6.3 with this commit: https://github.com/torvalds/linux/commit/17e810229cb3068b692fa078bd9b3a6527e0866a */
1363 34026 : ret = posix_fadvise(f, 0, 0, POSIX_FADV_NOREUSE);
1364 34026 : if (ret == ENOSYS) {
1365 : /* call is not supported */
1366 0 : ret = 0;
1367 : }
1368 34026 : if (ret != 0) {
1369 : /* LCOV_EXCL_START */
1370 : errno = ret; /* posix_fadvise return the error code */
1371 : return -1;
1372 : /* LCOV_EXCL_STOP */
1373 : }
1374 :
1375 : /* advise sequential access, this doubles the read-ahead window size */
1376 34026 : ret = posix_fadvise(f, 0, 0, POSIX_FADV_SEQUENTIAL);
1377 34026 : if (ret == ENOSYS) {
1378 : /* call is not supported, like in armhf, see posix_fadvise manpage */
1379 0 : ret = 0;
1380 : }
1381 34026 : if (ret != 0) {
1382 : /* LCOV_EXCL_START */
1383 : errno = ret; /* posix_fadvise return the error code */
1384 : return -1;
1385 : /* LCOV_EXCL_STOP */
1386 : }
1387 : }
1388 : #endif
1389 :
1390 2410879 : return 0;
1391 : }
1392 :
1393 914575 : int advise_write(struct advise_struct* advise, int f, data_off_t offset, data_off_t size)
1394 : {
1395 : data_off_t flush_offset;
1396 : data_off_t flush_size;
1397 : data_off_t discard_offset;
1398 : data_off_t discard_size;
1399 :
1400 : (void)f;
1401 : (void)flush_offset;
1402 : (void)flush_size;
1403 : (void)discard_offset;
1404 : (void)discard_size;
1405 :
1406 914575 : flush_offset = 0;
1407 914575 : flush_size = 0;
1408 914575 : discard_offset = 0;
1409 914575 : discard_size = 0;
1410 :
1411 : /*
1412 : * Follow Linus recommendations about fast writes.
1413 : *
1414 : * Linus "Unexpected splice "always copy" behavior observed"
1415 : * http://thread.gmane.org/gmane.linux.kernel/987247/focus=988070
1416 : * ---
1417 : * I have had _very_ good experiences with even a rather trivial
1418 : * file writer that basically used (iirc) 8MB windows, and the logic was very
1419 : * trivial:
1420 : *
1421 : * - before writing a new 8M window, do "start writeback"
1422 : * (SYNC_FILE_RANGE_WRITE) on the previous window, and do
1423 : * a wait (SYNC_FILE_RANGE_WAIT_AFTER) on the window before that.
1424 : *
1425 : * in fact, in its simplest form, you can do it like this (this is from my
1426 : * "overwrite disk images" program that I use on old disks):
1427 : *
1428 : * for (index = 0; index < max_index ;index++) {
1429 : * if (write(fd, buffer, BUFSIZE) != BUFSIZE)
1430 : * break;
1431 : * // This won't block, but will start writeout asynchronously
1432 : * sync_file_range(fd, index*BUFSIZE, BUFSIZE, SYNC_FILE_RANGE_WRITE);
1433 : * // This does a blocking write-and-wait on any old ranges
1434 : * if (index)
1435 : * sync_file_range(fd, (index-1)*BUFSIZE, BUFSIZE, SYNC_FILE_RANGE_WAIT_BEFORE|SYNC_FILE_RANGE_WRITE|SYNC_FILE_RANGE_WAIT_AFTER);
1436 : * }
1437 : *
1438 : * and even if you don't actually do a discard (maybe we should add a
1439 : * SYNC_FILE_RANGE_DISCARD bit, right now you'd need to do a separate
1440 : * fadvise(FADV_DONTNEED) to throw it out) the system behavior is pretty
1441 : * nice, because the heavy writer gets good IO performance _and_ leaves only
1442 : * easy-to-free pages around after itself.
1443 : * ---
1444 : *
1445 : * Linus "Unexpected splice "always copy" behavior observed"
1446 : * http://thread.gmane.org/gmane.linux.kernel/987247/focus=988176
1447 : * ---
1448 : * The behavior for dirty page writeback is _not_ well defined, and
1449 : * if you do POSIX_FADV_DONTNEED, I would suggest you do it as part of that
1450 : * writeback logic, ie you do it only on ranges that you have just waited on.
1451 : *
1452 : * IOW, in my example, you'd couple the
1453 : *
1454 : * sync_file_range(fd, (index-1)*BUFSIZE, BUFSIZE, SYNC_FILE_RANGE_WAIT_BEFORE|SYNC_FILE_RANGE_WRITE|SYNC_FILE_RANGE_WAIT_AFTER);
1455 : *
1456 : * with a
1457 : *
1458 : * posix_fadvise(fd, (index-1)*BUFSIZE, BUFSIZE, POSIX_FADV_DONTNEED);
1459 : *
1460 : * afterwards to throw out the pages that you just waited for.
1461 : * ---
1462 : */
1463 :
1464 914575 : switch (advise->mode) {
1465 0 : case ADVISE_FLUSH :
1466 0 : flush_offset = offset;
1467 0 : flush_size = size;
1468 0 : break;
1469 0 : case ADVISE_DISCARD :
1470 0 : discard_offset = offset;
1471 0 : discard_size = size;
1472 0 : break;
1473 4687 : case ADVISE_FLUSH_WINDOW :
1474 : /* if the dirty range can be extended */
1475 4687 : if (advise->dirty_end == offset) {
1476 : /* extent the dirty range */
1477 4687 : advise->dirty_end += size;
1478 :
1479 : /* if we reached the window size */
1480 4687 : if (advise->dirty_end - advise->dirty_begin >= ADVISE_WINDOW_SIZE) {
1481 : /* flush the window */
1482 0 : flush_offset = advise->dirty_begin;
1483 0 : flush_size = ADVISE_WINDOW_SIZE;
1484 :
1485 : /* remove it from the dirty range */
1486 0 : advise->dirty_begin += ADVISE_WINDOW_SIZE;
1487 : }
1488 : } else {
1489 : /* otherwise flush the existing dirty */
1490 0 : flush_offset = advise->dirty_begin;
1491 0 : flush_size = advise->dirty_end - advise->dirty_begin;
1492 :
1493 : /* and set the new range as dirty */
1494 0 : advise->dirty_begin = offset;
1495 0 : advise->dirty_end = offset + size;
1496 : }
1497 4687 : break;
1498 4687 : case ADVISE_DISCARD_WINDOW :
1499 : /* if the dirty range can be extended */
1500 4687 : if (advise->dirty_end == offset) {
1501 : /* extent the dirty range */
1502 4687 : advise->dirty_end += size;
1503 :
1504 : /* if we reached the double window size */
1505 4687 : if (advise->dirty_end - advise->dirty_begin >= 2 * ADVISE_WINDOW_SIZE) {
1506 : /* discard the first window */
1507 0 : discard_offset = advise->dirty_begin;
1508 0 : discard_size = ADVISE_WINDOW_SIZE;
1509 :
1510 : /* remove it from the dirty range */
1511 0 : advise->dirty_begin += ADVISE_WINDOW_SIZE;
1512 :
1513 : /* flush the second window */
1514 0 : flush_offset = advise->dirty_begin;
1515 0 : flush_size = ADVISE_WINDOW_SIZE;
1516 : }
1517 : } else {
1518 : /* otherwise discard the existing dirty */
1519 0 : discard_offset = advise->dirty_begin;
1520 0 : discard_size = advise->dirty_end - advise->dirty_begin;
1521 :
1522 : /* and set the new range as dirty */
1523 0 : advise->dirty_begin = offset;
1524 0 : advise->dirty_end = offset + size;
1525 : }
1526 4687 : break;
1527 : }
1528 :
1529 : #if HAVE_SYNC_FILE_RANGE
1530 914575 : if (flush_size != 0) {
1531 : int ret;
1532 :
1533 : /* start writing immediately */
1534 0 : ret = sync_file_range(f, flush_offset, flush_size, SYNC_FILE_RANGE_WRITE);
1535 0 : if (ret != 0) {
1536 : /* LCOV_EXCL_START */
1537 : return -1;
1538 : /* LCOV_EXCL_STOP */
1539 : }
1540 : }
1541 : #endif
1542 :
1543 : #if HAVE_SYNC_FILE_RANGE && HAVE_POSIX_FADVISE
1544 914575 : if (discard_size != 0) {
1545 : int ret;
1546 :
1547 : /* send the data to the disk and wait until it's written */
1548 0 : ret = sync_file_range(f, discard_offset, discard_size, SYNC_FILE_RANGE_WAIT_BEFORE | SYNC_FILE_RANGE_WRITE | SYNC_FILE_RANGE_WAIT_AFTER);
1549 0 : if (ret != 0) {
1550 : /* LCOV_EXCL_START */
1551 : return -1;
1552 : /* LCOV_EXCL_STOP */
1553 : }
1554 :
1555 : /* flush the data from the cache */
1556 0 : ret = posix_fadvise(f, discard_offset, discard_size, POSIX_FADV_DONTNEED);
1557 : /* for POSIX_FADV_DONTNEED we don't allow failure with ENOSYS */
1558 0 : if (ret != 0) {
1559 : /* LCOV_EXCL_START */
1560 : errno = ret; /* posix_fadvise return the error code */
1561 : return -1;
1562 : /* LCOV_EXCL_STOP */
1563 : }
1564 : }
1565 : #endif
1566 :
1567 914575 : return 0;
1568 : }
1569 :
1570 8833871 : int advise_read(struct advise_struct* advise, int f, data_off_t offset, data_off_t size)
1571 : {
1572 : (void)advise;
1573 : (void)f;
1574 : (void)offset;
1575 : (void)size;
1576 :
1577 : #if HAVE_POSIX_FADVISE
1578 8833871 : if (advise->mode == ADVISE_DISCARD
1579 8833871 : || advise->mode == ADVISE_DISCARD_WINDOW
1580 : ) {
1581 : int ret;
1582 :
1583 : /* flush the data from the cache */
1584 27825 : ret = posix_fadvise(f, offset, size, POSIX_FADV_DONTNEED);
1585 : /* for POSIX_FADV_DONTNEED we don't allow failure with ENOSYS */
1586 27825 : if (ret != 0) {
1587 : /* LCOV_EXCL_START */
1588 : errno = ret; /* posix_fadvise return the error code */
1589 : return -1;
1590 : /* LCOV_EXCL_STOP */
1591 : }
1592 : }
1593 : #endif
1594 :
1595 : /*
1596 : * Here we cannot call posix_fadvise(..., POSIX_FADV_WILLNEED) for the next block
1597 : * because it may be blocking.
1598 : *
1599 : * Ted Ts'o "posix_fadvise(POSIX_FADV_WILLNEED) waits before returning?"
1600 : * https://lkml.org/lkml/2010/12/6/122
1601 : * ---
1602 : * readahead and posix_fadvise(POSIX_FADV_WILLNEED) work exactly the same
1603 : * way, and in fact share mostly the same code path (see
1604 : * force_page_cache_readahead() in mm/readahead.c).
1605 : *
1606 : * They are asynchronous in that there is no guarantee the pages will be
1607 : * in the page cache by the time they return. But at the same time, they
1608 : * are not guaranteed to be non-blocking. That is, the work of doing the
1609 : * readahead does not take place in a kernel thread. So if you try to
1610 : * request I/O than will fit in the request queue, the system call will
1611 : * block until some I/O is completed so that more I/O requested cam be
1612 : * loaded onto the request queue.
1613 : *
1614 : * The only way to fix this would be to either put the work on a kernel
1615 : * thread (i.e., some kind of workqueue) or in a userspace thread. For
1616 : * ion programmer wondering what to do today, I'd suggest the
1617 : * latter since it will be more portable across various kernel versions.
1618 : *
1619 : * This does leave the question about whether we should change the kernel
1620 : * to allow readahead() and posix_fadvise(POSIX_FADV_WILLNEED) to be
1621 : * non-blocking and do this work in a workqueue (or via some kind of
1622 : * callback/continuation scheme). My worry is just doing this if a user
1623 : * application does something crazy, like request gigabytes and gigabytes
1624 : * of readahead, and then repented of their craziness, there should be a
1625 : * way of cancelling the readahead request. Today, the user can just
1626 : * kill the application. But if we simply shove the work to a kernel
1627 : * thread, it becomes a lot harder to cancel the readahead request. We'd
1628 : * have to invent a new API, and then have a way to know whether the user
1629 : * has access to kill a particular readahead request, etc.
1630 : * ---
1631 : */
1632 :
1633 8833871 : return 0;
1634 : }
1635 :
1636 : /****************************************************************************/
1637 : /* memory */
1638 :
1639 : /**
1640 : * Total amount of memory allocated.
1641 : */
1642 : static size_t mcounter;
1643 :
1644 488 : size_t malloc_counter_get(void)
1645 : {
1646 : size_t ret;
1647 :
1648 488 : lock_memory();
1649 :
1650 488 : ret = mcounter;
1651 :
1652 488 : unlock_memory();
1653 :
1654 488 : return ret;
1655 : }
1656 :
1657 20940815 : void malloc_counter_inc(size_t inc)
1658 : {
1659 20940815 : lock_memory();
1660 :
1661 20940815 : mcounter += inc;
1662 :
1663 20940815 : unlock_memory();
1664 20940815 : }
1665 :
1666 : /* LCOV_EXCL_START */
1667 : static ssize_t malloc_print(int f, const char* str)
1668 : {
1669 : ssize_t len = 0;
1670 :
1671 : while (str[len])
1672 : ++len;
1673 : return write(f, str, len);
1674 : }
1675 : /* LCOV_EXCL_STOP */
1676 :
1677 : /* LCOV_EXCL_START */
1678 : static ssize_t malloc_printn(int f, size_t value)
1679 : {
1680 : char buf[32];
1681 : int i;
1682 :
1683 : if (!value)
1684 : return write(f, "0", 1);
1685 :
1686 : i = sizeof(buf);
1687 : while (value) {
1688 : buf[--i] = (value % 10) + '0';
1689 : value /= 10;
1690 : }
1691 :
1692 : return write(f, buf + i, sizeof(buf) - i);
1693 : }
1694 : /* LCOV_EXCL_STOP */
1695 :
1696 : /* LCOV_EXCL_START */
1697 : void malloc_fail(size_t size)
1698 : {
1699 : /* don't use printf to avoid any possible extra allocation */
1700 : int f = 2; /* stderr */
1701 :
1702 : malloc_print(f, "Failed for Low Memory!\n");
1703 : malloc_print(f, "Allocating ");
1704 : malloc_printn(f, size);
1705 : malloc_print(f, " bytes.\n");
1706 : malloc_print(f, "Already allocated ");
1707 : malloc_printn(f, malloc_counter_get());
1708 : malloc_print(f, " bytes.\n");
1709 : if (sizeof(void*) == 4) {
1710 : malloc_print(f, "You are currently using a 32 bits executable.\n");
1711 : malloc_print(f, "If you have more than 4GB of memory, please upgrade to a 64 bits one.\n");
1712 : }
1713 : }
1714 : /* LCOV_EXCL_STOP */
1715 :
1716 14819123 : void* malloc_nofail(size_t size)
1717 : {
1718 14819123 : void* ptr = malloc(size);
1719 :
1720 14819123 : if (!ptr) {
1721 : /* LCOV_EXCL_START */
1722 : malloc_fail(size);
1723 : exit(EXIT_FAILURE);
1724 : /* LCOV_EXCL_STOP */
1725 : }
1726 :
1727 : #ifndef CHECKER /* Don't preinitialize when running for valgrind */
1728 : /* Here we preinitialize the memory to ensure that the OS is really allocating it */
1729 : /* and not only reserving the addressable space. */
1730 : /* Otherwise we are risking that the OOM (Out Of Memory) killer in Linux will kill the process. */
1731 : /* Filling the memory doesn't ensure to disable OOM, but it increase a lot the chances to */
1732 : /* get a real error from malloc() instead than a process killed. */
1733 : /* Note that calloc() doesn't have the same effect. */
1734 14819123 : memset(ptr, 0xA5, size);
1735 : #endif
1736 :
1737 14819123 : malloc_counter_inc(size);
1738 :
1739 14819123 : return ptr;
1740 : }
1741 :
1742 156192 : void* calloc_nofail(size_t count, size_t size)
1743 : {
1744 : void* ptr;
1745 :
1746 156192 : size *= count;
1747 :
1748 : /* see the note in malloc_nofail() of why we don't use calloc() */
1749 156192 : ptr = malloc(size);
1750 :
1751 156192 : if (!ptr) {
1752 : /* LCOV_EXCL_START */
1753 : malloc_fail(size);
1754 : exit(EXIT_FAILURE);
1755 : /* LCOV_EXCL_STOP */
1756 : }
1757 :
1758 156192 : memset(ptr, 0, size);
1759 :
1760 156192 : malloc_counter_inc(size);
1761 :
1762 156192 : return ptr;
1763 : }
1764 :
1765 5965500 : char* strdup_nofail(const char* str)
1766 : {
1767 : size_t size;
1768 : char* ptr;
1769 :
1770 5965500 : size = strlen(str) + 1;
1771 :
1772 5965500 : ptr = malloc(size);
1773 :
1774 5965500 : if (!ptr) {
1775 : /* LCOV_EXCL_START */
1776 : malloc_fail(size);
1777 : exit(EXIT_FAILURE);
1778 : /* LCOV_EXCL_STOP */
1779 : }
1780 :
1781 5965500 : memcpy(ptr, str, size);
1782 :
1783 5965500 : malloc_counter_inc(size);
1784 :
1785 5965500 : return ptr;
1786 : }
1787 :
1788 : /****************************************************************************/
1789 : /* smartctl */
1790 :
1791 : /**
1792 : * Match a string with the specified pattern.
1793 : * Like sscanf() a space match any sequence of spaces.
1794 : * Return 0 if it matches.
1795 : */
1796 0 : static int smatch(const char* str, const char* pattern)
1797 : {
1798 0 : while (*pattern) {
1799 0 : if (isspace(*pattern)) {
1800 0 : ++pattern;
1801 0 : while (isspace(*str))
1802 0 : ++str;
1803 0 : } else if (*pattern == *str) {
1804 0 : ++pattern;
1805 0 : ++str;
1806 : } else
1807 0 : return -1;
1808 : }
1809 :
1810 0 : return 0;
1811 : }
1812 :
1813 : /*
1814 : * scomma()
1815 : *
1816 : * Matches a literal prefix (the second argument), then parses the following
1817 : * unsigned 64-bit integer, allowing comma thousand separators (U.S. style).
1818 : *
1819 : * Whitespace is flexible around the prefix and before the number.
1820 : * Commas are ignored during number parsing but basic validation is applied.
1821 : *
1822 : * Returns:
1823 : * 1 - successfully parsed a valid uint64_t
1824 : * 0 - prefix mismatch, no digits found, invalid format or overflow
1825 : */
1826 0 : int scomma(const char* str, const char* prefix, uint64_t* value)
1827 : {
1828 0 : const char* s = str;
1829 0 : const char* f = prefix;
1830 :
1831 : /* match literal prefix, tolerating whitespace differences */
1832 0 : while (*f) {
1833 : /* skip whitespace in both strings */
1834 0 : while (isspace((unsigned char)*f))
1835 0 : ++f;
1836 0 : while (isspace((unsigned char)*s))
1837 0 : ++s;
1838 :
1839 0 : if (*f == 0)
1840 0 : break;
1841 0 : if (*s != *f)
1842 0 : return 0; /* prefix mismatch */
1843 :
1844 0 : ++s;
1845 0 : ++f;
1846 : }
1847 :
1848 : /* skip whitespace before the number starts */
1849 0 : while (isspace((unsigned char)*s))
1850 0 : ++s;
1851 :
1852 0 : uint64_t num = 0;
1853 0 : int digits_seen = 0;
1854 0 : int comma_seen = 0;
1855 :
1856 : /* parse digits, ignoring commas */
1857 0 : while (*s) {
1858 0 : if (*s >= '0' && *s <= '9') {
1859 0 : unsigned digit = (unsigned)(*s - '0');
1860 :
1861 : /* check for uint64_t overflow before multiplying */
1862 0 : if (num > (UINT64_MAX - digit) / 10ULL)
1863 0 : return 0;
1864 :
1865 0 : num = num * 10ULL + digit;
1866 0 : ++digits_seen;
1867 0 : comma_seen = 0;
1868 0 : } else if (*s == ',') {
1869 : /* disallow leading commas */
1870 0 : if (digits_seen == 0)
1871 0 : return 0;
1872 :
1873 : /* if two consecutive commas, stop parsing */
1874 0 : if (comma_seen)
1875 0 : break;
1876 :
1877 0 : comma_seen = 1;
1878 : } else {
1879 : /* any other character ends the number */
1880 0 : break;
1881 : }
1882 :
1883 0 : ++s;
1884 : }
1885 :
1886 : /* require at least one digit */
1887 0 : if (digits_seen == 0)
1888 0 : return 0;
1889 :
1890 0 : *value = num;
1891 0 : return 1;
1892 : }
1893 :
1894 0 : int smartctl_attribute(FILE* f, const char* file, const char* name, struct smart_attr* smart, uint64_t* info, char* serial, char* family, char* model, char* inter)
1895 : {
1896 : unsigned i;
1897 : int inside;
1898 : struct smart_attr dummy_smart[SMART_COUNT];
1899 : uint64_t dummy_info[INFO_COUNT];
1900 : char dummy_serial[SMART_MAX];
1901 : char dummy_family[SMART_MAX];
1902 : char dummy_model[SMART_MAX];
1903 : char dummy_interface[SMART_MAX];
1904 :
1905 : /* dummy attributes */
1906 0 : if (!smart)
1907 0 : smart = dummy_smart;
1908 0 : if (!info)
1909 0 : info = dummy_info;
1910 0 : if (!serial)
1911 0 : serial = dummy_serial;
1912 0 : if (!family)
1913 0 : family = dummy_family;
1914 0 : if (!model)
1915 0 : model = dummy_model;
1916 0 : if (!inter)
1917 0 : inter = dummy_interface;
1918 :
1919 : /* preclear attributes */
1920 0 : *serial = 0;
1921 0 : *family = 0;
1922 0 : *model = 0;
1923 0 : *inter = 0;
1924 0 : memset(smart, 0, sizeof(struct smart_attr) * SMART_COUNT);
1925 0 : for (i = 0; i < SMART_COUNT; ++i)
1926 0 : smart[i].raw = SMART_UNASSIGNED;
1927 0 : for (i = 0; i < INFO_COUNT; ++i)
1928 0 : info[i] = SMART_UNASSIGNED;
1929 :
1930 : /* read the file */
1931 0 : inside = 0;
1932 0 : while (1) {
1933 : char buf[256];
1934 : unsigned id;
1935 : uint64_t raw;
1936 : uint64_t norm;
1937 : uint64_t worst;
1938 : uint64_t thresh;
1939 : char* s;
1940 :
1941 0 : s = fgets(buf, sizeof(buf), f);
1942 0 : if (s == 0)
1943 0 : break;
1944 :
1945 : /* remove extraneous chars */
1946 0 : s = strpolish(buf);
1947 :
1948 0 : log_tag("smartctl:%s:%s:out: %s\n", file, name, s);
1949 :
1950 : /* skip initial spaces */
1951 0 : while (isspace(*s))
1952 0 : ++s;
1953 :
1954 0 : if (*s == 0) {
1955 0 : inside = 0;
1956 : /* common */
1957 0 : } else if (smatch(s, "Rotation Rate: Solid State") == 0) {
1958 0 : info[INFO_ROTATION_RATE] = 0;
1959 0 : } else if (sscanf(s, "Rotation Rate: %" SCNu64, &info[INFO_ROTATION_RATE]) == 1) {
1960 0 : } else if (smatch(s, "User Capacity:") == 0) {
1961 0 : char* begin = strchr(s, ':');
1962 0 : char* end = strstr(s, "bytes");
1963 0 : if (begin != 0 && end != 0 && begin < end) {
1964 : char* p;
1965 0 : info[INFO_SIZE] = 0;
1966 0 : for (p = begin; p != end; ++p) {
1967 0 : if (isdigit(*p)) {
1968 0 : info[INFO_SIZE] *= 10;
1969 0 : info[INFO_SIZE] += *p - '0';
1970 : }
1971 : }
1972 : }
1973 0 : } else if (sscanf(s, "Model Family: %63[^\n]", family) == 1) {
1974 0 : strtrim(family);
1975 0 : } else if (sscanf(s, "Device Model: %63[^\n]", model) == 1) {
1976 0 : strtrim(model);
1977 0 : } else if (sscanf(s, "Serial number: %63s", serial) == 1) {
1978 0 : strtrim(serial);
1979 : /* SCSI */
1980 : /*
1981 : Vendor: WD
1982 : Product: WD4001FYYG-01SL3
1983 : Revision: VR08
1984 : Compliance: SPC-4
1985 : User Capacity: 4,000,787,030,016 bytes [4.00 TB]
1986 : Logical block size: 512 bytes
1987 : Rotation Rate: 7200 rpm
1988 : Form Factor: 3.5 inches
1989 : Logical Unit id: 0x50000c0f01f55dd0
1990 : Serial number: WMC1F0D41KD5
1991 : Device type: disk
1992 : Transport protocol: SAS (SPL-3)
1993 : Local Time is: Fri Jan 28 14:14:51 2022 CET
1994 : SMART support is: Available - device has SMART capability.
1995 : SMART support is: Enabled
1996 : Temperature Warning: Enabled
1997 :
1998 : Current Drive Temperature: 38 C
1999 : Drive Trip Temperature: 65 C
2000 :
2001 : Manufactured in week 25 of year 2012
2002 : Specified cycle count over device lifetime: 10000
2003 : Accumulated start-stop cycles: 103
2004 : Specified load-unload count over device lifetime: 300000
2005 : Accumulated load-unload cycles: 103
2006 : Elements in grown defect list: 5
2007 :
2008 : Vendor (Seagate) cache information
2009 : Blocks sent to initiator = 569127595
2010 : Blocks received from initiator = 2633690060
2011 : Blocks read from cache and sent to initiator = 1881027254
2012 : Number of read and write commands whose size <= segment size = 181284019
2013 : Number of read and write commands whose size > segment size = 0
2014 :
2015 : Vendor (Seagate/Hitachi) factory information
2016 : number of hours powered up = 25024.80
2017 : number of minutes until next internal SMART test = 42
2018 :
2019 : */
2020 0 : } else if (sscanf(s, "Transport protocol: %63[^\n]", inter) == 1) {
2021 0 : if (strcmp(inter, "Fibre channel (FCP-4)") == 0)
2022 0 : strcpy(inter, "Fibre");
2023 0 : else if (strcmp(inter, "SSA") == 0)
2024 0 : strcpy(inter, "SSA");
2025 0 : else if (strcmp(inter, "IEEE 1394 (SBP-3)") == 0)
2026 0 : strcpy(inter, "FireWire");
2027 0 : else if (strcmp(inter, "RDMA (SRP)") == 0)
2028 0 : strcpy(inter, "SCSI");
2029 0 : else if (strcmp(inter, "iSCSI") == 0)
2030 0 : strcpy(inter, "iSCSI");
2031 0 : else if (strcmp(inter, "SAS (SPL-4)") == 0)
2032 0 : strcpy(inter, "SAS");
2033 0 : else if (strcmp(inter, "ADT") == 0)
2034 0 : strcpy(inter, "SCSI");
2035 0 : else if (strcmp(inter, "ATA (ACS-2)") == 0)
2036 0 : strcpy(inter, "SATA");
2037 0 : else if (strcmp(inter, "UAS") == 0)
2038 0 : strcpy(inter, "USB");
2039 0 : else if (strcmp(inter, "SOP") == 0)
2040 0 : strcpy(inter, "NVMe");
2041 0 : else if (strcmp(inter, "PCIe") == 0)
2042 0 : strcpy(inter, "PCIe");
2043 : else
2044 0 : strcpy(inter, "SCSI");
2045 : /* map generic attributes to SMART attr */
2046 0 : } else if (sscanf(s, "Elements in grown defect list: %" SCNu64, &smart[SMART_REALLOCATED_SECTOR_COUNT].raw) == 1) {
2047 0 : pathcpy(smart[SMART_REALLOCATED_SECTOR_COUNT].name, sizeof(smart[SMART_REALLOCATED_SECTOR_COUNT].name), "Elements_In_Grown_Defect_List");
2048 0 : } else if (sscanf(s, "Current Drive Temperature: %" SCNu64, &smart[SMART_TEMPERATURE_CELSIUS].raw) == 1) {
2049 0 : pathcpy(smart[SMART_TEMPERATURE_CELSIUS].name, sizeof(smart[SMART_TEMPERATURE_CELSIUS].name), "Current_Drive_Temperature");
2050 0 : } else if (sscanf(s, "Drive Trip Temperature: %" SCNu64, &smart[SMART_AIRFLOW_TEMPERATURE_CELSIUS].raw) == 1) {
2051 0 : pathcpy(smart[SMART_AIRFLOW_TEMPERATURE_CELSIUS].name, sizeof(smart[SMART_AIRFLOW_TEMPERATURE_CELSIUS].name), "Drive_Trip_Temperature");
2052 0 : } else if (sscanf(s, "Accumulated start-stop cycles: %" SCNu64, &smart[SMART_START_STOP_COUNT].raw) == 1) {
2053 0 : pathcpy(smart[SMART_START_STOP_COUNT].name, sizeof(smart[SMART_START_STOP_COUNT].name), "Accumulated_Start-Stop_Cycles");
2054 0 : } else if (sscanf(s, "Accumulated load-unload cycles: %" SCNu64, &smart[SMART_LOAD_CYCLE_COUNT].raw) == 1) {
2055 0 : pathcpy(smart[SMART_LOAD_CYCLE_COUNT].name, sizeof(smart[SMART_LOAD_CYCLE_COUNT].name), "Accumulated_Load-Unload_Cycles");
2056 0 : } else if (sscanf(s, " number of hours powered up = %" SCNu64, &smart[SMART_POWER_ON_HOURS].raw) == 1) { /* note "n" of "number" lower case */
2057 0 : pathcpy(smart[SMART_POWER_ON_HOURS].name, sizeof(smart[SMART_POWER_ON_HOURS].name), "Number_Of_Hours_Powered_Up");
2058 : /* special entries */
2059 0 : } else if (sscanf(s, "Non-medium error count: %" SCNu64, &raw) == 1) {
2060 0 : smart[SMART_ERROR_PROTOCOL].raw = raw;
2061 : /* ATA */
2062 : /*
2063 : ID# ATTRIBUTE_NAME FLAG VALUE WORST THRESH TYPE UPDATED WHEN_FAILED RAW_VALUE
2064 : 1 Raw_Read_Error_Rate 0x002f 200 200 051 Pre-fail Always - 0
2065 : 3 Spin_Up_Time 0x0027 172 169 021 Pre-fail Always - 8383
2066 : 4 Start_Stop_Count 0x0032 100 100 000 Old_age Always - 24
2067 : 5 Reallocated_Sector_Ct 0x0033 200 200 140 Pre-fail Always - 0
2068 : 7 Seek_Error_Rate 0x002e 200 200 000 Old_age Always - 0
2069 : 9 Power_On_Hours 0x0032 083 083 000 Old_age Always - 12471
2070 : 10 Spin_Retry_Count 0x0032 100 253 000 Old_age Always - 0
2071 : 11 Calibration_Retry_Count 0x0032 100 253 000 Old_age Always - 0
2072 : 12 Power_Cycle_Count 0x0032 100 100 000 Old_age Always - 24
2073 : 192 Power-Off_Retract_Count 0x0032 200 200 000 Old_age Always - 9
2074 : 193 Load_Cycle_Count 0x0032 157 157 000 Old_age Always - 131565
2075 : 194 Temperature_Celsius 0x0022 127 119 000 Old_age Always - 25
2076 : 196 Reallocated_Event_Count 0x0032 200 200 000 Old_age Always - 0
2077 : 197 Current_Pending_Sector 0x0032 200 200 000 Old_age Always - 0
2078 : 198 Offline_Uncorrectable 0x0030 100 253 000 Old_age Offline - 0
2079 : 199 UDMA_CRC_Error_Count 0x0032 200 200 000 Old_age Always - 0
2080 : 200 Multi_Zone_Error_Rate 0x0008 200 200 000 Old_age Offline - 0
2081 : */
2082 0 : } else if (smatch(s, "ATA Version is:") == 0) {
2083 0 : strcpy(inter, "ATA");
2084 0 : } else if (smatch(s, "SATA Version is:") == 0) {
2085 0 : strcpy(inter, "SATA");
2086 0 : } else if (smatch(s, "Transport Type: PCIe") == 0) {
2087 0 : strcpy(inter, "PCIe");
2088 0 : } else if (smatch(s, "Transport Type: Parallel") == 0) {
2089 0 : strcpy(inter, "PATA");
2090 : /* special entries */
2091 0 : } else if (smatch(s, "No Errors Logged") == 0) {
2092 0 : smart[SMART_ERROR_PROTOCOL].raw = 0;
2093 0 : } else if (sscanf(s, "ATA Error Count: %" SCNu64, &raw) == 1) {
2094 0 : smart[SMART_ERROR_PROTOCOL].raw = raw;
2095 : /* NVME */
2096 : /*
2097 : Critical Warning: 0x00
2098 : Temperature: 55 Celsius
2099 : Available Spare: 100%
2100 : Available Spare Threshold: 10%
2101 : Percentage Used: 8%
2102 : Data Units Read: 213,006,510 [109 TB]
2103 : Data Units Written: 549,370,112 [281 TB]
2104 : Host Read Commands: 11,210,192,197
2105 : Host Write Commands: 20,687,602,229
2106 : Controller Busy Time: 14,055
2107 : Power Cycles: 39
2108 : Power On Hours: 4,204
2109 : Unsafe Shutdowns: 9
2110 : Media and Data Integrity Errors: 0
2111 : Error Information Log Entries: 1,479,242
2112 : Warning Comp. Temperature Time: 0
2113 : Critical Comp. Temperature Time: 0
2114 : Temperature Sensor 2: 75 Celsius
2115 : Thermal Temp. 1 Total Time: 58745
2116 : */
2117 0 : } else if (smatch(s, "NVMe Version:") == 0) {
2118 0 : strcpy(inter, "NVMe");
2119 : /* special entries */
2120 0 : } else if (scomma(s, "Media and Data Integrity Errors:", &raw) == 1) {
2121 0 : smart[SMART_ERROR_MEDIUM].raw = raw;
2122 0 : } else if (scomma(s, "Error Information Log Entries:", &raw) == 1) {
2123 0 : smart[SMART_ERROR_PROTOCOL].raw = raw;
2124 0 : } else if (sscanf(s, "Percentage Used: %" SCNu64 "%%", &raw) == 1) {
2125 0 : smart[SMART_WEAR_LEVEL].raw = raw; /* take care that it can be greather than 100%, meaning that it's used over the expected lifetime */
2126 : /* map generic attributes to SMART attr */
2127 0 : } else if (sscanf(s, "Temperature: %" SCNu64, &smart[SMART_TEMPERATURE_CELSIUS].raw) == 1) {
2128 0 : pathcpy(smart[SMART_TEMPERATURE_CELSIUS].name, sizeof(smart[SMART_TEMPERATURE_CELSIUS].name), "Temperature");
2129 0 : } else if (scomma(s, "Power On Hours:", &smart[SMART_POWER_ON_HOURS].raw) == 1) {
2130 0 : pathcpy(smart[SMART_POWER_ON_HOURS].name, sizeof(smart[SMART_POWER_ON_HOURS].name), "Power_On_Hours");
2131 0 : } else if (scomma(s, "Power Cycles:", &smart[SMART_POWER_CYCLE_COUNT].raw) == 1) {
2132 0 : pathcpy(smart[SMART_POWER_CYCLE_COUNT].name, sizeof(smart[SMART_POWER_CYCLE_COUNT].name), "Power_Cycles");
2133 : /* map specific attributes to UNUSED SMART attr */
2134 0 : } else if (sscanf(s, "Critical Warning: %" SCNx64, &smart[SMART_NVME_CRITICAL_WARNING].raw) == 1) {
2135 0 : pathcpy(smart[SMART_NVME_CRITICAL_WARNING].name, sizeof(smart[SMART_NVME_CRITICAL_WARNING].name), "Critical_Warning");
2136 0 : } else if (sscanf(s, "Available Spare: %" SCNu64 "%%", &smart[SMART_NVME_AVAILABLE_SPARE].raw) == 1) {
2137 0 : pathcpy(smart[SMART_NVME_AVAILABLE_SPARE].name, sizeof(smart[SMART_NVME_AVAILABLE_SPARE].name), "Available_Spare");
2138 0 : } else if (scomma(s, "Data Units Read:", &smart[SMART_NVME_DATA_UNITS_READ].raw) == 1) {
2139 0 : pathcpy(smart[SMART_NVME_DATA_UNITS_READ].name, sizeof(smart[SMART_NVME_DATA_UNITS_READ].name), "Data_Units_Read");
2140 0 : } else if (scomma(s, "Data Units Written:", &smart[SMART_NVME_DATA_UNITS_WRITTEN].raw) == 1) {
2141 0 : pathcpy(smart[SMART_NVME_DATA_UNITS_WRITTEN].name, sizeof(smart[SMART_NVME_DATA_UNITS_WRITTEN].name), "Data_Units_Written");
2142 0 : } else if (scomma(s, "Host Read Commands:", &smart[SMART_NVME_HOST_READ_COMMANDS].raw) == 1) {
2143 0 : pathcpy(smart[SMART_NVME_HOST_READ_COMMANDS].name, sizeof(smart[SMART_NVME_HOST_READ_COMMANDS].name), "Host_Read_Commands");
2144 0 : } else if (scomma(s, "Host Write Commands:", &smart[SMART_NVME_HOST_WRITE_COMMANDS].raw) == 1) {
2145 0 : pathcpy(smart[SMART_NVME_HOST_WRITE_COMMANDS].name, sizeof(smart[SMART_NVME_HOST_WRITE_COMMANDS].name), "Host_Write_Commands");
2146 0 : } else if (scomma(s, "Controller Busy Time:", &smart[SMART_NVME_CONTROLLER_BUSY_TIME].raw) == 1) {
2147 0 : pathcpy(smart[SMART_NVME_CONTROLLER_BUSY_TIME].name, sizeof(smart[SMART_NVME_CONTROLLER_BUSY_TIME].name), "Controller_Busy_Time");
2148 0 : } else if (scomma(s, "Unsafe Shutdowns:", &smart[SMART_NVME_UNSAFE_SHUTDOWNS].raw) == 1) {
2149 0 : pathcpy(smart[SMART_NVME_UNSAFE_SHUTDOWNS].name, sizeof(smart[SMART_NVME_UNSAFE_SHUTDOWNS].name), "Unsafe_Shutdowns");
2150 : /* smartctl doesn't print this with command, but %d */
2151 0 : } else if (scomma(s, "Warning Comp. Temperature Time:", &smart[SMART_NVME_WARNING_COMP_TEMPERATURE_TIME].raw) == 1) {
2152 0 : pathcpy(smart[SMART_NVME_WARNING_COMP_TEMPERATURE_TIME].name, sizeof(smart[SMART_NVME_WARNING_COMP_TEMPERATURE_TIME].name), "Warning_Comp_Temperature_Time");
2153 : /* smartctl doesn't print this with command, but %d */
2154 0 : } else if (scomma(s, "Critical Comp. Temperature Time:", &smart[SMART_NVME_CRITICAL_COMP_TEMPERATURE_TIME].raw) == 1) {
2155 0 : pathcpy(smart[SMART_NVME_CRITICAL_COMP_TEMPERATURE_TIME].name, sizeof(smart[SMART_NVME_CRITICAL_COMP_TEMPERATURE_TIME].name), "Critical_Comp_Temperature_Time");
2156 : /* ATA Attributes table */
2157 0 : } else if (smatch(s, "ID#") == 0) {
2158 0 : inside = 1;
2159 0 : } else if (inside) {
2160 0 : char id_name[128] = { 0 };
2161 0 : char type[64] = { 0 };
2162 0 : char updated[64] = { 0 };
2163 0 : char when_failed[64] = { 0 };
2164 : uint64_t min, max;
2165 : int minmax;
2166 : int flags;
2167 :
2168 0 : if (sscanf(s, "%u %127s %*s %" SCNu64 " %" SCNu64 " %" SCNu64 " %63s %63s %63s %" SCNu64 " (Min/Max %" SCNu64 "/%" SCNu64 ")", &id, id_name, &norm, &worst, &thresh, type, updated, when_failed, &raw, &min, &max) == 11) {
2169 0 : minmax = 1;
2170 0 : } else if (sscanf(s, "%u %127s %*s %" SCNu64 " %" SCNu64 " %" SCNu64 " %63s %63s %63s %" SCNu64, &id, id_name, &norm, &worst, &thresh, type, updated, when_failed, &raw) == 9) {
2171 0 : minmax = 0;
2172 : } else {
2173 0 : log_fatal(EEXTERNAL, "Invalid smartctl line '%s'.\n", s);
2174 0 : return -1;
2175 : }
2176 :
2177 0 : if (id >= 256) {
2178 : /* LCOV_EXCL_START */
2179 : log_fatal(EEXTERNAL, "Invalid SMART id '%u'.\n", id);
2180 : return -1;
2181 : /* LCOV_EXCL_STOP */
2182 : }
2183 :
2184 0 : flags = 0;
2185 0 : if (strcmp(type, "Pre-fail") == 0)
2186 0 : flags |= SMART_ATTR_TYPE_PREFAIL;
2187 0 : else if (strcmp(type, "Old_age") == 0)
2188 0 : flags |= SMART_ATTR_TYPE_OLDAGE;
2189 0 : if (strcmp(updated, "Always") == 0)
2190 0 : flags |= SMART_ATTR_UPDATE_ALWAYS;
2191 0 : else if (strcmp(updated, "Offline") == 0)
2192 0 : flags |= SMART_ATTR_UPDATE_OFFLINE;
2193 0 : if (strcmp(when_failed, "FAILING_NOW") == 0)
2194 0 : flags |= SMART_ATTR_WHEN_FAILED_NOW;
2195 0 : else if (strcmp(when_failed, "In_the_past") == 0)
2196 0 : flags |= SMART_ATTR_WHEN_FAILED_PAST;
2197 0 : else if (strcmp(when_failed, "-") == 0)
2198 0 : flags |= SMART_ATTR_WHEN_FAILED_NEVER;
2199 :
2200 : /* revert the min/max decoding done by smartctl */
2201 0 : if (minmax
2202 0 : && raw <= 0xFFFFUL
2203 0 : && min <= 0xFFFFUL
2204 0 : && max <= 0xFFFFUL) {
2205 0 : raw |= min << 16;
2206 0 : raw |= max << 32;
2207 : }
2208 :
2209 0 : smart[id].raw = raw;
2210 0 : smart[id].norm = norm;
2211 0 : smart[id].worst = worst;
2212 0 : smart[id].thresh = thresh;
2213 0 : smart[id].flags = flags;
2214 0 : pathcpy(smart[id].name, sizeof(smart[id].name), id_name);
2215 :
2216 : /*
2217 : * Map normalized health percentage to our unified wear level for SSDs
2218 : * 177: Wear_Leveling_Count (Samsung/Crucial)
2219 : * 231: SSD_Life_Left (Kingston/WD)
2220 : * 233: Media_Wearout_Indicator (Intel)
2221 : */
2222 0 : if (norm <= 100) {
2223 0 : switch (id) {
2224 0 : case 177 :
2225 : case 233 :
2226 : case 231 :
2227 0 : smart[SMART_WEAR_LEVEL].raw = 100 - norm;
2228 0 : break;
2229 : }
2230 : }
2231 : }
2232 : }
2233 :
2234 0 : return 0;
2235 : }
2236 :
2237 25 : int smartctl_flush(FILE* f, const char* file, const char* name)
2238 : {
2239 : /* read the file */
2240 20 : while (1) {
2241 : char buf[256];
2242 : char* s;
2243 :
2244 25 : s = fgets(buf, sizeof(buf), f);
2245 25 : if (s == 0)
2246 5 : break;
2247 :
2248 : /* remove extraneous chars */
2249 20 : s = strpolish(buf);
2250 :
2251 20 : log_tag("smartctl:%s:%s:out: %s\n", file, name, s);
2252 : }
2253 :
2254 5 : return 0;
2255 : }
2256 :
2257 145110 : int smart_temp(devinfo_t* devinfo)
2258 : {
2259 145110 : uint64_t t = devinfo->smart[SMART_TEMPERATURE_CELSIUS].raw;
2260 145110 : if (t == SMART_UNASSIGNED)
2261 0 : t = devinfo->smart[SMART_AIRFLOW_TEMPERATURE_CELSIUS].raw;
2262 145110 : if (t == SMART_UNASSIGNED)
2263 0 : return -1;
2264 :
2265 : /* mask out min/max values */
2266 145110 : t &= 0xFFFFUL;
2267 :
2268 145110 : if (t == 0)
2269 0 : return -1;
2270 145110 : if (t > 100)
2271 0 : return -1;
2272 :
2273 145110 : return t;
2274 : }
2275 :
2276 : /****************************************************************************/
2277 : /* thread */
2278 :
2279 : #if HAVE_THREAD
2280 3299 : void thread_mutex_init(thread_mutex_t* mutex)
2281 : {
2282 3299 : if (pthread_mutex_init(mutex, 0) != 0) {
2283 : /* LCOV_EXCL_START */
2284 : log_fatal(EINTERNAL, "Failed call to pthread_mutex_init().\n");
2285 : os_abort();
2286 : /* LCOV_EXCL_STOP */
2287 : }
2288 3299 : }
2289 :
2290 3167 : void thread_mutex_destroy(thread_mutex_t* mutex)
2291 : {
2292 3167 : if (pthread_mutex_destroy(mutex) != 0) {
2293 : /* LCOV_EXCL_START */
2294 : log_fatal(EINTERNAL, "Failed call to pthread_mutex_destroy().\n");
2295 : os_abort();
2296 : /* LCOV_EXCL_STOP */
2297 : }
2298 3167 : }
2299 :
2300 112510359 : void thread_mutex_lock(thread_mutex_t* mutex)
2301 : {
2302 112510359 : if (pthread_mutex_lock(mutex) != 0) {
2303 : /* LCOV_EXCL_START */
2304 : log_fatal(EINTERNAL, "Failed call to pthread_mutex_lock().\n");
2305 : os_abort();
2306 : /* LCOV_EXCL_STOP */
2307 : }
2308 112510359 : }
2309 :
2310 112510359 : void thread_mutex_unlock(thread_mutex_t* mutex)
2311 : {
2312 112510359 : if (pthread_mutex_unlock(mutex) != 0) {
2313 : /* LCOV_EXCL_START */
2314 : log_fatal(EINTERNAL, "Failed call to pthread_mutex_unlock().\n");
2315 : os_abort();
2316 : /* LCOV_EXCL_STOP */
2317 : }
2318 112510359 : }
2319 :
2320 404 : void thread_cond_init(thread_cond_t* cond)
2321 : {
2322 404 : if (pthread_cond_init(cond, 0) != 0) {
2323 : /* LCOV_EXCL_START */
2324 : log_fatal(EINTERNAL, "Failed call to pthread_cond_init().\n");
2325 : os_abort();
2326 : /* LCOV_EXCL_STOP */
2327 : }
2328 404 : }
2329 :
2330 404 : void thread_cond_destroy(thread_cond_t* cond)
2331 : {
2332 404 : if (pthread_cond_destroy(cond) != 0) {
2333 : /* LCOV_EXCL_START */
2334 : log_fatal(EINTERNAL, "Failed call to pthread_cond_destroy().\n");
2335 : os_abort();
2336 : /* LCOV_EXCL_STOP */
2337 : }
2338 404 : }
2339 :
2340 668 : void thread_cond_signal(thread_cond_t* cond)
2341 : {
2342 668 : if (pthread_cond_signal(cond) != 0) {
2343 : /* LCOV_EXCL_START */
2344 : log_fatal(EINTERNAL, "Failed call to pthread_cond_signal().\n");
2345 : os_abort();
2346 : /* LCOV_EXCL_STOP */
2347 : }
2348 668 : }
2349 :
2350 257671 : void thread_cond_broadcast(thread_cond_t* cond)
2351 : {
2352 257671 : if (pthread_cond_broadcast(cond) != 0) {
2353 : /* LCOV_EXCL_START */
2354 : log_fatal(EINTERNAL, "Failed call to pthread_cond_broadcast().\n");
2355 : os_abort();
2356 : /* LCOV_EXCL_STOP */
2357 : }
2358 257671 : }
2359 :
2360 1554330 : void thread_cond_wait(thread_cond_t* cond, thread_mutex_t* mutex)
2361 : {
2362 1554330 : if (pthread_cond_wait(cond, mutex) != 0) {
2363 : /* LCOV_EXCL_START */
2364 : log_fatal(EINTERNAL, "Failed call to pthread_cond_wait().\n");
2365 : os_abort();
2366 : /* LCOV_EXCL_STOP */
2367 : }
2368 1554330 : }
2369 :
2370 : /**
2371 : * Implementation note about conditional variables.
2372 : *
2373 : * The conditional variables can be signaled inside or outside the mutex,
2374 : * what is better it's debatable but in general doing that outside the mutex,
2375 : * reduces the number of context switches.
2376 : *
2377 : * But when testing with helgrind and drd, this disallows such tools to
2378 : * to see the dependency between the signal and the wait.
2379 : *
2380 : * To avoid it we signal everything inside the mutex. And we do this in both
2381 : * test mode (with CHECKER defined) and release mode (CHECKER not defined),
2382 : * to be on the safe side and avoid any difference in behaviour between test and
2383 : * release.
2384 : *
2385 : * Here some interesting discussion:
2386 : *
2387 : * Condvars: signal with mutex locked or not?
2388 : * http://www.domaigne.com/blog/computing/condvars-signal-with-mutex-locked-or-not/
2389 : *
2390 : * Calling pthread_cond_signal without locking mutex
2391 : * http://stackoverflow.com/questions/4544234/calling-pthread-cond-signal-without-locking-mutex/4544494#4544494
2392 : */
2393 :
2394 : /**
2395 : * Control when to signal the condition variables.
2396 : */
2397 : int thread_cond_signal_outside = 0;
2398 :
2399 668 : void thread_cond_signal_and_unlock(thread_cond_t* cond, thread_mutex_t* mutex)
2400 : {
2401 668 : if (thread_cond_signal_outside) {
2402 : /* without the thread checker unlock before signaling, */
2403 : /* this reduces the number of context switches */
2404 0 : thread_mutex_unlock(mutex);
2405 : }
2406 :
2407 668 : thread_cond_signal(cond);
2408 :
2409 668 : if (!thread_cond_signal_outside) {
2410 : /* with the thread checker unlock after signaling */
2411 : /* to make explicit the condition and mutex relation */
2412 668 : thread_mutex_unlock(mutex);
2413 : }
2414 668 : }
2415 :
2416 257469 : void thread_cond_broadcast_and_unlock(thread_cond_t* cond, thread_mutex_t* mutex)
2417 : {
2418 257469 : if (thread_cond_signal_outside) {
2419 : /* without the thread checker unlock before signaling, */
2420 : /* this reduces the number of context switches */
2421 0 : thread_mutex_unlock(mutex);
2422 : }
2423 :
2424 257469 : thread_cond_broadcast(cond);
2425 :
2426 257469 : if (!thread_cond_signal_outside) {
2427 : /* with the thread checker unlock after signaling */
2428 : /* to make explicit the condition and mutex relation */
2429 257469 : thread_mutex_unlock(mutex);
2430 : }
2431 257469 : }
2432 :
2433 2876 : void thread_create(thread_id_t* thread, void* (*func)(void*), void* arg)
2434 : {
2435 2876 : if (pthread_create(thread, 0, func, arg) != 0) {
2436 : /* LCOV_EXCL_START */
2437 : log_fatal(EINTERNAL, "Failed call to pthread_create().\n");
2438 : os_abort();
2439 : /* LCOV_EXCL_STOP */
2440 : }
2441 2876 : }
2442 :
2443 2876 : void thread_join(thread_id_t thread, void** retval)
2444 : {
2445 2876 : if (pthread_join(thread, retval) != 0) {
2446 : /* LCOV_EXCL_START */
2447 : log_fatal(EINTERNAL, "Failed call to pthread_join().\n");
2448 : os_abort();
2449 : /* LCOV_EXCL_STOP */
2450 : }
2451 2876 : }
2452 :
2453 105499 : void thread_yield(void)
2454 : {
2455 : #ifdef __MINGW32__
2456 : Sleep(0);
2457 : #else
2458 105499 : sched_yield();
2459 : #endif
2460 105499 : }
2461 : #endif
2462 :
2463 : /****************************************************************************/
2464 : /* wnmatch */
2465 :
2466 : /**
2467 : * Helper function for case-insensitive character comparison
2468 : */
2469 86982601 : static inline int char_match(char p, char t)
2470 : {
2471 : #ifdef WIN32
2472 : return tolower((unsigned char)p) == tolower((unsigned char)t);
2473 : #else
2474 86982601 : return p == t;
2475 : #endif
2476 : }
2477 :
2478 : /**
2479 : * Match character class [...]
2480 : * Return 0 if NOT matched
2481 : */
2482 28 : static const char* match_class(const char* p, char t)
2483 : {
2484 28 : int negate = 0;
2485 28 : int matched = 0;
2486 :
2487 28 : if (*p == '!' || *p == '^') {
2488 9 : negate = 1;
2489 9 : ++p;
2490 : }
2491 :
2492 77 : while (*p && *p != ']') {
2493 49 : if (p[1] == '-' && p[2] != ']' && p[2] != 0) {
2494 : /* range [a-z] */
2495 22 : char start = *p;
2496 22 : char end = p[2];
2497 : #ifdef WIN32
2498 : start = tolower((unsigned char)start);
2499 : end = tolower((unsigned char)end);
2500 : t = tolower((unsigned char)t);
2501 : #endif
2502 22 : if (t >= start && t <= end)
2503 10 : matched = 1;
2504 22 : p += 3;
2505 : } else {
2506 : /* single character */
2507 27 : if (char_match(*p, t))
2508 5 : matched = 1;
2509 27 : ++p;
2510 : }
2511 : }
2512 :
2513 28 : if (*p == ']')
2514 28 : ++p;
2515 :
2516 28 : if (negate)
2517 9 : matched = !matched;
2518 28 : if (!matched)
2519 14 : return 0;
2520 :
2521 14 : return p;
2522 : }
2523 :
2524 102260599 : int wnmatch(const char* p, const char* t)
2525 : {
2526 102260599 : char p1 = 0; /* previous char */
2527 105985464 : while (*p) {
2528 105852004 : char p0 = *p;
2529 105852004 : switch (p0) {
2530 20 : case '?' :
2531 : /* ? matches any single character except / */
2532 20 : if (*t == 0 || *t == '/')
2533 4 : return 1;
2534 16 : ++p;
2535 16 : ++t;
2536 16 : break;
2537 12656225 : case '*' :
2538 : /* check for ** */
2539 12656225 : if (p[1] == '*') {
2540 : /* skip the ** */
2541 104 : p += 2;
2542 :
2543 : /* munge all * */
2544 114 : while (*p == '*')
2545 10 : ++p;
2546 :
2547 : /* if its not near a slash, it's like a single * */
2548 104 : if (p1 == '/' || *p == '/') {
2549 : /* a ** at end matches everything */
2550 84 : if (*p == 0)
2551 10 : return 0;
2552 :
2553 : /*
2554 : * In between slashes matches to nothing
2555 : *
2556 : * Check for /##/ or ^##/ (^ start of string)
2557 : *
2558 : * This is required for:
2559 : * "/##/file.txt" matching "/file.txt"
2560 : * "##/file.txt" matching "file.txt"
2561 : * "x##/file.txt" NOT matching "xfile.txt"
2562 : */
2563 74 : if (*p == '/' && (p1 == 0 || p1 == '/')) {
2564 : /* try reducing to nothing */
2565 71 : if (wnmatch(p + 1, t) == 0)
2566 27 : return 0;
2567 : /* otherwise / should match in the text */
2568 : }
2569 :
2570 : /* try matching with 0 or more characters */
2571 275 : while (*t) {
2572 263 : if (wnmatch(p, t) == 0)
2573 35 : return 0;
2574 228 : ++t;
2575 : }
2576 :
2577 : /* try matching at the end */
2578 12 : return wnmatch(p, t);
2579 : }
2580 : } else {
2581 : /* skip the * */
2582 12656121 : ++p;
2583 : }
2584 :
2585 : /* a * at end matches rest of segment */
2586 12656141 : if (*p == 0) {
2587 60 : while (*t && *t != '/')
2588 49 : ++t;
2589 11 : return *t != 0;
2590 : }
2591 :
2592 : /* try matching with 0 or more characters */
2593 89476178 : while (*t && *t != '/') {
2594 76944779 : if (wnmatch(p, t) == 0)
2595 124731 : return 0;
2596 76820048 : ++t;
2597 : }
2598 :
2599 : /* try matching at the end */
2600 12531399 : return wnmatch(p, t);
2601 31 : case '[' :
2602 : /* character class */
2603 31 : if (*t == 0 || *t == '/')
2604 3 : return 1;
2605 :
2606 28 : p = match_class(p + 1, *t);
2607 28 : if (!p)
2608 14 : return 1;
2609 :
2610 14 : ++t;
2611 14 : break;
2612 93195728 : default :
2613 : /* literal character */
2614 93195728 : if (*t == 0 || !char_match(*p, *t))
2615 89470893 : return 1;
2616 3724835 : ++p;
2617 3724835 : ++t;
2618 3724835 : break;
2619 : }
2620 3724865 : p1 = p0;
2621 : }
2622 :
2623 : /* match successful if we've consumed all text */
2624 133460 : return *t != 0;
2625 : }
2626 :
|