1 /*
2  * Dropbear - a SSH2 server
3  *
4  * Copyright (c) 2002,2003 Matt Johnston
5  * All rights reserved.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23  * SOFTWARE.
24  *
25  * strlcat() is copyright as follows:
26  * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
27  * All rights reserved.
28  *
29  * Redistribution and use in source and binary forms, with or without
30  * modification, are permitted provided that the following conditions
31  * are met:
32  * 1. Redistributions of source code must retain the above copyright
33  *    notice, this list of conditions and the following disclaimer.
34  * 2. Redistributions in binary form must reproduce the above copyright
35  *    notice, this list of conditions and the following disclaimer in the
36  *    documentation and/or other materials provided with the distribution.
37  * 3. The name of the author may not be used to endorse or promote products
38  *    derived from this software without specific prior written permission.
39  *
40  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
41  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
42  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
43  * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
44  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
45  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
46  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
47  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
48  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
49  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
50 
51 #include "config.h"
52 
53 #ifdef __linux__
54 #define _GNU_SOURCE
55 /* To call clock_gettime() directly */
56 #include <sys/syscall.h>
57 #endif /* __linux */
58 
59 #ifdef HAVE_MACH_MACH_TIME_H
60 #include <mach/mach_time.h>
61 #include <mach/mach.h>
62 #endif
63 
64 #include "includes.h"
65 #include "dbutil.h"
66 #include "buffer.h"
67 #include "session.h"
68 #include "atomicio.h"
69 
70 #define MAX_FMT 100
71 
72 static void generic_dropbear_exit(int exitcode, const char* format,
73 		va_list param) ATTRIB_NORETURN;
74 static void generic_dropbear_log(int priority, const char* format,
75 		va_list param);
76 
77 void (*_dropbear_exit)(int exitcode, const char* format, va_list param) ATTRIB_NORETURN
78 						= generic_dropbear_exit;
79 void (*_dropbear_log)(int priority, const char* format, va_list param)
80 						= generic_dropbear_log;
81 
82 #if DEBUG_TRACE
83 int debug_trace = 0;
84 #endif
85 
86 #ifndef DISABLE_SYSLOG
startsyslog(const char * ident)87 void startsyslog(const char *ident) {
88 
89 	openlog(ident, LOG_PID, LOG_AUTHPRIV);
90 
91 }
92 #endif /* DISABLE_SYSLOG */
93 
94 /* the "format" string must be <= 100 characters */
dropbear_close(const char * format,...)95 void dropbear_close(const char* format, ...) {
96 
97 	va_list param;
98 
99 	va_start(param, format);
100 	_dropbear_exit(EXIT_SUCCESS, format, param);
101 	va_end(param);
102 
103 }
104 
dropbear_exit(const char * format,...)105 void dropbear_exit(const char* format, ...) {
106 
107 	va_list param;
108 
109 	va_start(param, format);
110 	_dropbear_exit(EXIT_FAILURE, format, param);
111 	va_end(param);
112 }
113 
generic_dropbear_exit(int exitcode,const char * format,va_list param)114 static void generic_dropbear_exit(int exitcode, const char* format,
115 		va_list param) {
116 
117 	char fmtbuf[300];
118 
119 	snprintf(fmtbuf, sizeof(fmtbuf), "Exited: %s", format);
120 
121 	_dropbear_log(LOG_INFO, fmtbuf, param);
122 
123 #if DROPBEAR_FUZZ
124     if (fuzz.do_jmp) {
125         longjmp(fuzz.jmp, 1);
126     }
127 #endif
128 
129 	exit(exitcode);
130 }
131 
fail_assert(const char * expr,const char * file,int line)132 void fail_assert(const char* expr, const char* file, int line) {
133 	dropbear_exit("Failed assertion (%s:%d): `%s'", file, line, expr);
134 }
135 
generic_dropbear_log(int UNUSED (priority),const char * format,va_list param)136 static void generic_dropbear_log(int UNUSED(priority), const char* format,
137 		va_list param) {
138 
139 	char printbuf[1024];
140 
141 	vsnprintf(printbuf, sizeof(printbuf), format, param);
142 
143 	fprintf(stderr, "%s\n", printbuf);
144 
145 }
146 
147 /* this is what can be called to write arbitrary log messages */
dropbear_log(int priority,const char * format,...)148 void dropbear_log(int priority, const char* format, ...) {
149 
150 	va_list param;
151 
152 	va_start(param, format);
153 	_dropbear_log(priority, format, param);
154 	va_end(param);
155 }
156 
157 
158 #if DEBUG_TRACE
159 
160 static double debug_start_time = -1;
161 
debug_start_net()162 void debug_start_net()
163 {
164 	if (getenv("DROPBEAR_DEBUG_NET_TIMESTAMP"))
165 	{
166 		/* Timestamps start from first network activity */
167 		struct timeval tv;
168 		gettimeofday(&tv, NULL);
169 		debug_start_time = tv.tv_sec + (tv.tv_usec / 1000000.0);
170 		TRACE(("Resetting Dropbear TRACE timestamps"))
171 	}
172 }
173 
time_since_start()174 static double time_since_start()
175 {
176 	double nowf;
177 	struct timeval tv;
178 	gettimeofday(&tv, NULL);
179 	nowf = tv.tv_sec + (tv.tv_usec / 1000000.0);
180 	if (debug_start_time < 0)
181 	{
182 		debug_start_time = nowf;
183 		return 0;
184 	}
185 	return nowf - debug_start_time;
186 }
187 
dropbear_trace(const char * format,...)188 void dropbear_trace(const char* format, ...) {
189 	va_list param;
190 
191 	if (!debug_trace) {
192 		return;
193 	}
194 
195 	va_start(param, format);
196 	fprintf(stderr, "TRACE  (%d) %f: ", getpid(), time_since_start());
197 	vfprintf(stderr, format, param);
198 	fprintf(stderr, "\n");
199 	va_end(param);
200 }
201 
dropbear_trace2(const char * format,...)202 void dropbear_trace2(const char* format, ...) {
203 	static int trace_env = -1;
204 	va_list param;
205 
206 	if (trace_env == -1) {
207 		trace_env = getenv("DROPBEAR_TRACE2") ? 1 : 0;
208 	}
209 
210 	if (!(debug_trace && trace_env)) {
211 		return;
212 	}
213 
214 	va_start(param, format);
215 	fprintf(stderr, "TRACE2 (%d) %f: ", getpid(), time_since_start());
216 	vfprintf(stderr, format, param);
217 	fprintf(stderr, "\n");
218 	va_end(param);
219 }
220 #endif /* DEBUG_TRACE */
221 
222 /* Connect to a given unix socket. The socket is blocking */
223 #if ENABLE_CONNECT_UNIX
connect_unix(const char * path)224 int connect_unix(const char* path) {
225 	struct sockaddr_un addr;
226 	int fd = -1;
227 
228 	memset((void*)&addr, 0x0, sizeof(addr));
229 	addr.sun_family = AF_UNIX;
230 	strlcpy(addr.sun_path, path, sizeof(addr.sun_path));
231 	fd = socket(PF_UNIX, SOCK_STREAM, 0);
232 	if (fd < 0) {
233 		TRACE(("Failed to open unix socket"))
234 		return -1;
235 	}
236 	if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
237 		TRACE(("Failed to connect to '%s' socket", path))
238 		m_close(fd);
239 		return -1;
240 	}
241 	return fd;
242 }
243 #endif
244 
245 /* Sets up a pipe for a, returning three non-blocking file descriptors
246  * and the pid. exec_fn is the function that will actually execute the child process,
247  * it will be run after the child has fork()ed, and is passed exec_data.
248  * If ret_errfd == NULL then stderr will not be captured.
249  * ret_pid can be passed as  NULL to discard the pid. */
spawn_command(void (* exec_fn)(const void * user_data),const void * exec_data,int * ret_writefd,int * ret_readfd,int * ret_errfd,pid_t * ret_pid)250 int spawn_command(void(*exec_fn)(const void *user_data), const void *exec_data,
251 		int *ret_writefd, int *ret_readfd, int *ret_errfd, pid_t *ret_pid) {
252 	int infds[2];
253 	int outfds[2];
254 	int errfds[2];
255 	pid_t pid;
256 
257 	const int FDIN = 0;
258 	const int FDOUT = 1;
259 
260 #if DROPBEAR_FUZZ
261 	if (fuzz.fuzzing) {
262 		return fuzz_spawn_command(ret_writefd, ret_readfd, ret_errfd, ret_pid);
263 	}
264 #endif
265 
266 	/* redirect stdin/stdout/stderr */
267 	if (pipe(infds) != 0) {
268 		return DROPBEAR_FAILURE;
269 	}
270 	if (pipe(outfds) != 0) {
271 		return DROPBEAR_FAILURE;
272 	}
273 	if (ret_errfd && pipe(errfds) != 0) {
274 		return DROPBEAR_FAILURE;
275 	}
276 
277 #if DROPBEAR_VFORK
278 	pid = vfork();
279 #else
280 	pid = fork();
281 #endif
282 
283 	if (pid < 0) {
284 		return DROPBEAR_FAILURE;
285 	}
286 
287 	if (!pid) {
288 		/* child */
289 
290 		TRACE(("back to normal sigchld"))
291 		/* Revert to normal sigchld handling */
292 		if (signal(SIGCHLD, SIG_DFL) == SIG_ERR) {
293 			dropbear_exit("signal() error");
294 		}
295 
296 		/* redirect stdin/stdout */
297 
298 		if ((dup2(infds[FDIN], STDIN_FILENO) < 0) ||
299 			(dup2(outfds[FDOUT], STDOUT_FILENO) < 0) ||
300 			(ret_errfd && dup2(errfds[FDOUT], STDERR_FILENO) < 0)) {
301 			TRACE(("leave noptycommand: error redirecting FDs"))
302 			dropbear_exit("Child dup2() failure");
303 		}
304 
305 		close(infds[FDOUT]);
306 		close(infds[FDIN]);
307 		close(outfds[FDIN]);
308 		close(outfds[FDOUT]);
309 		if (ret_errfd)
310 		{
311 			close(errfds[FDIN]);
312 			close(errfds[FDOUT]);
313 		}
314 
315 		exec_fn(exec_data);
316 		/* not reached */
317 		return DROPBEAR_FAILURE;
318 	} else {
319 		/* parent */
320 		close(infds[FDIN]);
321 		close(outfds[FDOUT]);
322 
323 		setnonblocking(outfds[FDIN]);
324 		setnonblocking(infds[FDOUT]);
325 
326 		if (ret_errfd) {
327 			close(errfds[FDOUT]);
328 			setnonblocking(errfds[FDIN]);
329 		}
330 
331 		if (ret_pid) {
332 			*ret_pid = pid;
333 		}
334 
335 		*ret_writefd = infds[FDOUT];
336 		*ret_readfd = outfds[FDIN];
337 		if (ret_errfd) {
338 			*ret_errfd = errfds[FDIN];
339 		}
340 		return DROPBEAR_SUCCESS;
341 	}
342 }
343 
344 /* Runs a command with "sh -c". Will close FDs (except stdin/stdout/stderr) and
345  * re-enabled SIGPIPE. If cmd is NULL, will run a login shell.
346  */
run_shell_command(const char * cmd,unsigned int maxfd,char * usershell)347 void run_shell_command(const char* cmd, unsigned int maxfd, char* usershell) {
348 	char * argv[4];
349 	char * baseshell = NULL;
350 	unsigned int i;
351 
352 	baseshell = basename(usershell);
353 
354 	if (cmd != NULL) {
355 		argv[0] = baseshell;
356 	} else {
357 		/* a login shell should be "-bash" for "/bin/bash" etc */
358 		int len = strlen(baseshell) + 2; /* 2 for "-" */
359 		argv[0] = (char*)m_malloc(len);
360 		snprintf(argv[0], len, "-%s", baseshell);
361 	}
362 
363 	if (cmd != NULL) {
364 		argv[1] = "-c";
365 		argv[2] = (char*)cmd;
366 		argv[3] = NULL;
367 	} else {
368 		/* construct a shell of the form "-bash" etc */
369 		argv[1] = NULL;
370 	}
371 
372 	/* Re-enable SIGPIPE for the executed process */
373 	if (signal(SIGPIPE, SIG_DFL) == SIG_ERR) {
374 		dropbear_exit("signal() error");
375 	}
376 
377 	/* close file descriptors except stdin/stdout/stderr
378 	 * Need to be sure FDs are closed here to avoid reading files as root */
379 	for (i = 3; i <= maxfd; i++) {
380 		m_close(i);
381 	}
382 
383 	execv(usershell, argv);
384 }
385 
386 #if DEBUG_TRACE
printhex(const char * label,const unsigned char * buf,int len)387 void printhex(const char * label, const unsigned char * buf, int len) {
388 
389 	int i;
390 
391 	fprintf(stderr, "%s\n", label);
392 	for (i = 0; i < len; i++) {
393 		fprintf(stderr, "%02x", buf[i]);
394 		if (i % 16 == 15) {
395 			fprintf(stderr, "\n");
396 		}
397 		else if (i % 2 == 1) {
398 			fprintf(stderr, " ");
399 		}
400 	}
401 	fprintf(stderr, "\n");
402 }
403 
printmpint(const char * label,mp_int * mp)404 void printmpint(const char *label, mp_int *mp) {
405 	buffer *buf = buf_new(1000);
406 	buf_putmpint(buf, mp);
407 	fprintf(stderr, "%d bits ", mp_count_bits(mp));
408 	printhex(label, buf->data, buf->len);
409 	buf_free(buf);
410 
411 }
412 #endif
413 
414 /* Strip all control characters from text (a null-terminated string), except
415  * for '\n', '\r' and '\t'.
416  * The result returned is a newly allocated string, this must be free()d after
417  * use */
stripcontrol(const char * text)418 char * stripcontrol(const char * text) {
419 
420 	char * ret;
421 	int len, pos;
422 	int i;
423 
424 	len = strlen(text);
425 	ret = m_malloc(len+1);
426 
427 	pos = 0;
428 	for (i = 0; i < len; i++) {
429 		if ((text[i] <= '~' && text[i] >= ' ') /* normal printable range */
430 				|| text[i] == '\n' || text[i] == '\r' || text[i] == '\t') {
431 			ret[pos] = text[i];
432 			pos++;
433 		}
434 	}
435 	ret[pos] = 0x0;
436 	return ret;
437 }
438 
439 
440 /* reads the contents of filename into the buffer buf, from the current
441  * position, either to the end of the file, or the buffer being full.
442  * Returns DROPBEAR_SUCCESS or DROPBEAR_FAILURE */
buf_readfile(buffer * buf,const char * filename)443 int buf_readfile(buffer* buf, const char* filename) {
444 
445 	int fd = -1;
446 	int len;
447 	int maxlen;
448 	int ret = DROPBEAR_FAILURE;
449 
450 	fd = open(filename, O_RDONLY);
451 
452 	if (fd < 0) {
453 		goto out;
454 	}
455 
456 	do {
457 		maxlen = buf->size - buf->pos;
458 		len = read(fd, buf_getwriteptr(buf, maxlen), maxlen);
459 		if (len < 0) {
460 			if (errno == EINTR || errno == EAGAIN) {
461 				continue;
462 			}
463 			goto out;
464 		}
465 		buf_incrwritepos(buf, len);
466 	} while (len < maxlen && len > 0);
467 
468 	ret = DROPBEAR_SUCCESS;
469 
470 out:
471 	if (fd >= 0) {
472 		m_close(fd);
473 	}
474 	return ret;
475 }
476 
477 /* get a line from the file into buffer in the style expected for an
478  * authkeys file.
479  * Will return DROPBEAR_SUCCESS if data is read, or DROPBEAR_FAILURE on EOF.*/
480 /* Only used for ~/.ssh/known_hosts and ~/.ssh/authorized_keys */
481 #if DROPBEAR_CLIENT || DROPBEAR_SVR_PUBKEY_AUTH
buf_getline(buffer * line,FILE * authfile)482 int buf_getline(buffer * line, FILE * authfile) {
483 
484 	int c = EOF;
485 
486 	buf_setpos(line, 0);
487 	buf_setlen(line, 0);
488 
489 	while (line->pos < line->size) {
490 
491 		c = fgetc(authfile); /*getc() is weird with some uClibc systems*/
492 		if (c == EOF || c == '\n' || c == '\r') {
493 			goto out;
494 		}
495 
496 		buf_putbyte(line, (unsigned char)c);
497 	}
498 
499 	TRACE(("leave getauthline: line too long"))
500 	/* We return success, but the line length will be zeroed - ie we just
501 	 * ignore that line */
502 	buf_setlen(line, 0);
503 
504 out:
505 
506 
507 	/* if we didn't read anything before EOF or error, exit */
508 	if (c == EOF && line->pos == 0) {
509 		return DROPBEAR_FAILURE;
510 	} else {
511 		buf_setpos(line, 0);
512 		return DROPBEAR_SUCCESS;
513 	}
514 
515 }
516 #endif
517 
518 /* make sure that the socket closes */
m_close(int fd)519 void m_close(int fd) {
520 	int val;
521 
522 	if (fd < 0) {
523 		return;
524 	}
525 
526 	do {
527 		val = close(fd);
528 	} while (val < 0 && errno == EINTR);
529 
530 	if (val < 0 && errno != EBADF) {
531 		/* Linux says EIO can happen */
532 		dropbear_exit("Error closing fd %d, %s", fd, strerror(errno));
533 	}
534 }
535 
setnonblocking(int fd)536 void setnonblocking(int fd) {
537 
538 	TRACE(("setnonblocking: %d", fd))
539 
540 #if DROPBEAR_FUZZ
541 	if (fuzz.fuzzing) {
542 		return;
543 	}
544 #endif
545 
546 	if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) {
547 		if (errno == ENODEV) {
548 			/* Some devices (like /dev/null redirected in)
549 			 * can't be set to non-blocking */
550 			TRACE(("ignoring ENODEV for setnonblocking"))
551 		} else {
552 		{
553 			dropbear_exit("Couldn't set nonblocking");
554 		}
555 		}
556 	}
557 	TRACE(("leave setnonblocking"))
558 }
559 
disallow_core()560 void disallow_core() {
561 	struct rlimit lim;
562 	lim.rlim_cur = lim.rlim_max = 0;
563 	setrlimit(RLIMIT_CORE, &lim);
564 }
565 
566 /* Returns DROPBEAR_SUCCESS or DROPBEAR_FAILURE, with the result in *val */
m_str_to_uint(const char * str,unsigned int * val)567 int m_str_to_uint(const char* str, unsigned int *val) {
568 	unsigned long l;
569 	errno = 0;
570 	l = strtoul(str, NULL, 10);
571 	/* The c99 spec doesn't actually seem to define EINVAL, but most platforms
572 	 * I've looked at mention it in their manpage */
573 	if ((l == 0 && errno == EINVAL)
574 		|| (l == ULONG_MAX && errno == ERANGE)
575 		|| (l > UINT_MAX)) {
576 		return DROPBEAR_FAILURE;
577 	} else {
578 		*val = l;
579 		return DROPBEAR_SUCCESS;
580 	}
581 }
582 
583 /* Returns malloced path. inpath beginning with '/' is returned as-is,
584 otherwise home directory is prepended */
expand_homedir_path(const char * inpath)585 char * expand_homedir_path(const char *inpath) {
586 	struct passwd *pw = NULL;
587 	if (inpath[0] != '/') {
588 		pw = getpwuid(getuid());
589 		if (pw && pw->pw_dir) {
590 			int len = strlen(inpath) + strlen(pw->pw_dir) + 2;
591 			char *buf = m_malloc(len);
592 			snprintf(buf, len, "%s/%s", pw->pw_dir, inpath);
593 			return buf;
594 		}
595 	}
596 
597 	/* Fallback */
598 	return m_strdup(inpath);
599 }
600 
constant_time_memcmp(const void * a,const void * b,size_t n)601 int constant_time_memcmp(const void* a, const void *b, size_t n)
602 {
603 	const char *xa = a, *xb = b;
604 	uint8_t c = 0;
605 	size_t i;
606 	for (i = 0; i < n; i++)
607 	{
608 		c |= (xa[i] ^ xb[i]);
609 	}
610 	return c;
611 }
612 
613 /* higher-resolution monotonic timestamp, falls back to gettimeofday */
gettime_wrapper(struct timespec * now)614 void gettime_wrapper(struct timespec *now) {
615 	struct timeval tv;
616 #if DROPBEAR_FUZZ
617 	if (fuzz.fuzzing) {
618 		/* time stands still when fuzzing */
619 		now->tv_sec = 5;
620 		now->tv_nsec = 0;
621 	}
622 #endif
623 
624 #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
625 	/* POSIX monotonic clock. Newer Linux, BSD, MacOSX >10.12 */
626 	if (clock_gettime(CLOCK_MONOTONIC, now) == 0) {
627 		return;
628 	}
629 #endif
630 
631 #if defined(__linux__) && defined(SYS_clock_gettime)
632 	{
633 	/* Old linux toolchain - kernel might support it but not the build headers */
634 	/* Also glibc <2.17 requires -lrt which we neglect to add */
635 	static int linux_monotonic_failed = 0;
636 	if (!linux_monotonic_failed) {
637 		/* CLOCK_MONOTONIC isn't in some headers */
638 		int clock_source_monotonic = 1;
639 		if (syscall(SYS_clock_gettime, clock_source_monotonic, now) == 0) {
640 			return;
641 		} else {
642 			/* Don't try again */
643 			linux_monotonic_failed = 1;
644 		}
645 	}
646 	}
647 #endif /* linux fallback clock_gettime */
648 
649 #if defined(HAVE_MACH_ABSOLUTE_TIME)
650 	{
651 	/* OS X pre 10.12, see https://developer.apple.com/library/mac/qa/qa1398/_index.html */
652 	static mach_timebase_info_data_t timebase_info;
653 	uint64_t scaled_time;
654 	if (timebase_info.denom == 0) {
655 		mach_timebase_info(&timebase_info);
656 	}
657 	scaled_time = mach_absolute_time() * timebase_info.numer / timebase_info.denom;
658 	now->tv_sec = scaled_time / 1000000000;
659 	now->tv_nsec = scaled_time % 1000000000;
660 	}
661 #endif /* osx mach_absolute_time */
662 
663 	/* Fallback for everything else - this will sometimes go backwards */
664 	gettimeofday(&tv, NULL);
665 	now->tv_sec = tv.tv_sec;
666 	now->tv_nsec = 1000*tv.tv_usec;
667 }
668 
669 /* second-resolution monotonic timestamp */
monotonic_now()670 time_t monotonic_now() {
671 	struct timespec ts;
672 	gettime_wrapper(&ts);
673 	return ts.tv_sec;
674 }
675 
fsync_parent_dir(const char * fn)676 void fsync_parent_dir(const char* fn) {
677 #ifdef HAVE_LIBGEN_H
678 	char *fn_dir = m_strdup(fn);
679 	char *dir = dirname(fn_dir);
680 	int dirfd = open(dir, O_RDONLY);
681 
682 	if (dirfd != -1) {
683 		if (fsync(dirfd) != 0) {
684 			TRACE(("fsync of directory %s failed: %s", dir, strerror(errno)))
685 		}
686 		m_close(dirfd);
687 	} else {
688 		TRACE(("error opening directory %s for fsync: %s", dir, strerror(errno)))
689 	}
690 
691 	m_free(fn_dir);
692 #endif
693 }
694