dropbar: Update to version 2013.60.1.
[tomato.git] / release / src / router / dropbear / dbutil.c
blob2589e1a77d869a488dd862694176ace046eafa1c
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:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
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.
25 * strlcat() is copyright as follows:
26 * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
27 * All rights reserved.
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.
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. */
51 #include "includes.h"
52 #include "dbutil.h"
53 #include "buffer.h"
54 #include "session.h"
55 #include "atomicio.h"
57 #define MAX_FMT 100
59 static void generic_dropbear_exit(int exitcode, const char* format,
60 va_list param) ATTRIB_NORETURN;
61 static void generic_dropbear_log(int priority, const char* format,
62 va_list param);
64 void (*_dropbear_exit)(int exitcode, const char* format, va_list param) ATTRIB_NORETURN
65 = generic_dropbear_exit;
66 void (*_dropbear_log)(int priority, const char* format, va_list param)
67 = generic_dropbear_log;
69 #ifdef DEBUG_TRACE
70 int debug_trace = 0;
71 #endif
73 #ifndef DISABLE_SYSLOG
74 void startsyslog() {
76 openlog(PROGNAME, LOG_PID, LOG_AUTHPRIV);
79 #endif /* DISABLE_SYSLOG */
81 /* the "format" string must be <= 100 characters */
82 void dropbear_close(const char* format, ...) {
84 va_list param;
86 va_start(param, format);
87 _dropbear_exit(EXIT_SUCCESS, format, param);
88 va_end(param);
92 void dropbear_exit(const char* format, ...) {
94 va_list param;
96 va_start(param, format);
97 _dropbear_exit(EXIT_FAILURE, format, param);
98 va_end(param);
101 static void generic_dropbear_exit(int exitcode, const char* format,
102 va_list param) {
104 char fmtbuf[300];
106 snprintf(fmtbuf, sizeof(fmtbuf), "Exited: %s", format);
108 _dropbear_log(LOG_INFO, fmtbuf, param);
110 exit(exitcode);
113 void fail_assert(const char* expr, const char* file, int line) {
114 dropbear_exit("Failed assertion (%s:%d): `%s'", file, line, expr);
117 static void generic_dropbear_log(int UNUSED(priority), const char* format,
118 va_list param) {
120 char printbuf[1024];
122 vsnprintf(printbuf, sizeof(printbuf), format, param);
124 fprintf(stderr, "%s\n", printbuf);
128 /* this is what can be called to write arbitrary log messages */
129 void dropbear_log(int priority, const char* format, ...) {
131 va_list param;
133 va_start(param, format);
134 _dropbear_log(priority, format, param);
135 va_end(param);
139 #ifdef DEBUG_TRACE
140 void dropbear_trace(const char* format, ...) {
141 va_list param;
142 struct timeval tv;
144 if (!debug_trace) {
145 return;
148 gettimeofday(&tv, NULL);
150 va_start(param, format);
151 fprintf(stderr, "TRACE (%d) %d.%d: ", getpid(), tv.tv_sec, tv.tv_usec);
152 vfprintf(stderr, format, param);
153 fprintf(stderr, "\n");
154 va_end(param);
157 void dropbear_trace2(const char* format, ...) {
158 static int trace_env = -1;
159 va_list param;
160 struct timeval tv;
162 if (trace_env == -1) {
163 trace_env = getenv("DROPBEAR_TRACE2") ? 1 : 0;
166 if (!(debug_trace && trace_env)) {
167 return;
170 gettimeofday(&tv, NULL);
172 va_start(param, format);
173 fprintf(stderr, "TRACE2 (%d) %d.%d: ", getpid(), tv.tv_sec, tv.tv_usec);
174 vfprintf(stderr, format, param);
175 fprintf(stderr, "\n");
176 va_end(param);
178 #endif /* DEBUG_TRACE */
180 static void set_sock_priority(int sock) {
182 int val;
184 /* disable nagle */
185 val = 1;
186 setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (void*)&val, sizeof(val));
188 /* set the TOS bit for either ipv4 or ipv6 */
189 #ifdef IPTOS_LOWDELAY
190 val = IPTOS_LOWDELAY;
191 #if defined(IPPROTO_IPV6) && defined(IPV6_TCLASS)
192 setsockopt(sock, IPPROTO_IPV6, IPV6_TCLASS, (void*)&val, sizeof(val));
193 #endif
194 setsockopt(sock, IPPROTO_IP, IP_TOS, (void*)&val, sizeof(val));
195 #endif
197 #ifdef SO_PRIORITY
198 /* linux specific, sets QoS class.
199 * 6 looks to be optimal for interactive traffic (see tc-prio(8) ). */
200 val = 6;
201 setsockopt(sock, SOL_SOCKET, SO_PRIORITY, (void*) &val, sizeof(val));
202 #endif
206 /* Listen on address:port.
207 * Special cases are address of "" listening on everything,
208 * and address of NULL listening on localhost only.
209 * Returns the number of sockets bound on success, or -1 on failure. On
210 * failure, if errstring wasn't NULL, it'll be a newly malloced error
211 * string.*/
212 int dropbear_listen(const char* address, const char* port,
213 int *socks, unsigned int sockcount, char **errstring, int *maxfd) {
215 struct addrinfo hints, *res = NULL, *res0 = NULL;
216 int err;
217 unsigned int nsock;
218 struct linger linger;
219 int val;
220 int sock;
222 TRACE(("enter dropbear_listen"))
224 memset(&hints, 0, sizeof(hints));
225 hints.ai_family = AF_UNSPEC; /* TODO: let them flag v4 only etc */
226 hints.ai_socktype = SOCK_STREAM;
228 /* for calling getaddrinfo:
229 address == NULL and !AI_PASSIVE: local loopback
230 address == NULL and AI_PASSIVE: all interfaces
231 address != NULL: whatever the address says */
232 if (!address) {
233 TRACE(("dropbear_listen: local loopback"))
234 } else {
235 if (address[0] == '\0') {
236 TRACE(("dropbear_listen: all interfaces"))
237 address = NULL;
239 hints.ai_flags = AI_PASSIVE;
241 err = getaddrinfo(address, port, &hints, &res0);
243 if (err) {
244 if (errstring != NULL && *errstring == NULL) {
245 int len;
246 len = 20 + strlen(gai_strerror(err));
247 *errstring = (char*)m_malloc(len);
248 snprintf(*errstring, len, "Error resolving: %s", gai_strerror(err));
250 if (res0) {
251 freeaddrinfo(res0);
252 res0 = NULL;
254 TRACE(("leave dropbear_listen: failed resolving"))
255 return -1;
259 nsock = 0;
260 for (res = res0; res != NULL && nsock < sockcount;
261 res = res->ai_next) {
263 /* Get a socket */
264 socks[nsock] = socket(res->ai_family, res->ai_socktype,
265 res->ai_protocol);
267 sock = socks[nsock]; /* For clarity */
269 if (sock < 0) {
270 err = errno;
271 TRACE(("socket() failed"))
272 continue;
275 /* Various useful socket options */
276 val = 1;
277 /* set to reuse, quick timeout */
278 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*) &val, sizeof(val));
279 linger.l_onoff = 1;
280 linger.l_linger = 5;
281 setsockopt(sock, SOL_SOCKET, SO_LINGER, (void*)&linger, sizeof(linger));
283 #if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
284 if (res->ai_family == AF_INET6) {
285 int on = 1;
286 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY,
287 &on, sizeof(on)) == -1) {
288 dropbear_log(LOG_WARNING, "Couldn't set IPV6_V6ONLY");
291 #endif
293 set_sock_priority(sock);
295 if (bind(sock, res->ai_addr, res->ai_addrlen) < 0) {
296 err = errno;
297 close(sock);
298 TRACE(("bind(%s) failed", port))
299 continue;
302 if (listen(sock, 20) < 0) {
303 err = errno;
304 close(sock);
305 TRACE(("listen() failed"))
306 continue;
309 *maxfd = MAX(*maxfd, sock);
311 nsock++;
314 if (res0) {
315 freeaddrinfo(res0);
316 res0 = NULL;
319 if (nsock == 0) {
320 if (errstring != NULL && *errstring == NULL) {
321 int len;
322 len = 20 + strlen(strerror(err));
323 *errstring = (char*)m_malloc(len);
324 snprintf(*errstring, len, "Error listening: %s", strerror(err));
326 TRACE(("leave dropbear_listen: failure, %s", strerror(err)))
327 return -1;
330 TRACE(("leave dropbear_listen: success, %d socks bound", nsock))
331 return nsock;
334 /* Connect to a given unix socket. The socket is blocking */
335 #ifdef ENABLE_CONNECT_UNIX
336 int connect_unix(const char* path) {
337 struct sockaddr_un addr;
338 int fd = -1;
340 memset((void*)&addr, 0x0, sizeof(addr));
341 addr.sun_family = AF_UNIX;
342 strlcpy(addr.sun_path, path, sizeof(addr.sun_path));
343 fd = socket(PF_UNIX, SOCK_STREAM, 0);
344 if (fd < 0) {
345 TRACE(("Failed to open unix socket"))
346 return -1;
348 if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
349 TRACE(("Failed to connect to '%s' socket", path))
350 m_close(fd);
351 return -1;
353 return fd;
355 #endif
357 /* Connect via TCP to a host. Connection will try ipv4 or ipv6, will
358 * return immediately if nonblocking is set. On failure, if errstring
359 * wasn't null, it will be a newly malloced error message */
361 /* TODO: maxfd */
362 int connect_remote(const char* remotehost, const char* remoteport,
363 int nonblocking, char ** errstring) {
365 struct addrinfo *res0 = NULL, *res = NULL, hints;
366 int sock;
367 int err;
369 TRACE(("enter connect_remote"))
371 if (errstring != NULL) {
372 *errstring = NULL;
375 memset(&hints, 0, sizeof(hints));
376 hints.ai_socktype = SOCK_STREAM;
377 hints.ai_family = PF_UNSPEC;
379 err = getaddrinfo(remotehost, remoteport, &hints, &res0);
380 if (err) {
381 if (errstring != NULL && *errstring == NULL) {
382 int len;
383 len = 100 + strlen(gai_strerror(err));
384 *errstring = (char*)m_malloc(len);
385 snprintf(*errstring, len, "Error resolving '%s' port '%s'. %s",
386 remotehost, remoteport, gai_strerror(err));
388 TRACE(("Error resolving: %s", gai_strerror(err)))
389 return -1;
392 sock = -1;
393 err = EADDRNOTAVAIL;
394 for (res = res0; res; res = res->ai_next) {
396 sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
397 if (sock < 0) {
398 err = errno;
399 continue;
402 if (nonblocking) {
403 setnonblocking(sock);
406 if (connect(sock, res->ai_addr, res->ai_addrlen) < 0) {
407 if (errno == EINPROGRESS && nonblocking) {
408 TRACE(("Connect in progress"))
409 break;
410 } else {
411 err = errno;
412 close(sock);
413 sock = -1;
414 continue;
418 break; /* Success */
421 if (sock < 0 && !(errno == EINPROGRESS && nonblocking)) {
422 /* Failed */
423 if (errstring != NULL && *errstring == NULL) {
424 int len;
425 len = 20 + strlen(strerror(err));
426 *errstring = (char*)m_malloc(len);
427 snprintf(*errstring, len, "Error connecting: %s", strerror(err));
429 TRACE(("Error connecting: %s", strerror(err)))
430 } else {
431 /* Success */
432 set_sock_priority(sock);
435 freeaddrinfo(res0);
436 if (sock > 0 && errstring != NULL && *errstring != NULL) {
437 m_free(*errstring);
440 TRACE(("leave connect_remote: sock %d\n", sock))
441 return sock;
444 /* Sets up a pipe for a, returning three non-blocking file descriptors
445 * and the pid. exec_fn is the function that will actually execute the child process,
446 * it will be run after the child has fork()ed, and is passed exec_data.
447 * If ret_errfd == NULL then stderr will not be captured.
448 * ret_pid can be passed as NULL to discard the pid. */
449 int spawn_command(void(*exec_fn)(void *user_data), void *exec_data,
450 int *ret_writefd, int *ret_readfd, int *ret_errfd, pid_t *ret_pid) {
451 int infds[2];
452 int outfds[2];
453 int errfds[2];
454 pid_t pid;
456 const int FDIN = 0;
457 const int FDOUT = 1;
459 /* redirect stdin/stdout/stderr */
460 if (pipe(infds) != 0) {
461 return DROPBEAR_FAILURE;
463 if (pipe(outfds) != 0) {
464 return DROPBEAR_FAILURE;
466 if (ret_errfd && pipe(errfds) != 0) {
467 return DROPBEAR_FAILURE;
470 #ifdef USE_VFORK
471 pid = vfork();
472 #else
473 pid = fork();
474 #endif
476 if (pid < 0) {
477 return DROPBEAR_FAILURE;
480 if (!pid) {
481 /* child */
483 TRACE(("back to normal sigchld"))
484 /* Revert to normal sigchld handling */
485 if (signal(SIGCHLD, SIG_DFL) == SIG_ERR) {
486 dropbear_exit("signal() error");
489 /* redirect stdin/stdout */
491 if ((dup2(infds[FDIN], STDIN_FILENO) < 0) ||
492 (dup2(outfds[FDOUT], STDOUT_FILENO) < 0) ||
493 (ret_errfd && dup2(errfds[FDOUT], STDERR_FILENO) < 0)) {
494 TRACE(("leave noptycommand: error redirecting FDs"))
495 dropbear_exit("Child dup2() failure");
498 close(infds[FDOUT]);
499 close(infds[FDIN]);
500 close(outfds[FDIN]);
501 close(outfds[FDOUT]);
502 if (ret_errfd)
504 close(errfds[FDIN]);
505 close(errfds[FDOUT]);
508 exec_fn(exec_data);
509 /* not reached */
510 return DROPBEAR_FAILURE;
511 } else {
512 /* parent */
513 close(infds[FDIN]);
514 close(outfds[FDOUT]);
516 setnonblocking(outfds[FDIN]);
517 setnonblocking(infds[FDOUT]);
519 if (ret_errfd) {
520 close(errfds[FDOUT]);
521 setnonblocking(errfds[FDIN]);
524 if (ret_pid) {
525 *ret_pid = pid;
528 *ret_writefd = infds[FDOUT];
529 *ret_readfd = outfds[FDIN];
530 if (ret_errfd) {
531 *ret_errfd = errfds[FDIN];
533 return DROPBEAR_SUCCESS;
537 /* Runs a command with "sh -c". Will close FDs (except stdin/stdout/stderr) and
538 * re-enabled SIGPIPE. If cmd is NULL, will run a login shell.
540 void run_shell_command(const char* cmd, unsigned int maxfd, char* usershell) {
541 char * argv[4];
542 char * baseshell = NULL;
543 unsigned int i;
545 baseshell = basename(usershell);
547 if (cmd != NULL) {
548 argv[0] = baseshell;
549 } else {
550 /* a login shell should be "-bash" for "/bin/bash" etc */
551 int len = strlen(baseshell) + 2; /* 2 for "-" */
552 argv[0] = (char*)m_malloc(len);
553 snprintf(argv[0], len, "-%s", baseshell);
556 if (cmd != NULL) {
557 argv[1] = "-c";
558 argv[2] = (char*)cmd;
559 argv[3] = NULL;
560 } else {
561 /* construct a shell of the form "-bash" etc */
562 argv[1] = NULL;
565 /* Re-enable SIGPIPE for the executed process */
566 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR) {
567 dropbear_exit("signal() error");
570 /* close file descriptors except stdin/stdout/stderr
571 * Need to be sure FDs are closed here to avoid reading files as root */
572 for (i = 3; i <= maxfd; i++) {
573 m_close(i);
576 execv(usershell, argv);
579 void get_socket_address(int fd, char **local_host, char **local_port,
580 char **remote_host, char **remote_port, int host_lookup)
582 struct sockaddr_storage addr;
583 socklen_t addrlen;
585 if (local_host || local_port) {
586 addrlen = sizeof(addr);
587 if (getsockname(fd, (struct sockaddr*)&addr, &addrlen) < 0) {
588 dropbear_exit("Failed socket address: %s", strerror(errno));
590 getaddrstring(&addr, local_host, local_port, host_lookup);
592 if (remote_host || remote_port) {
593 addrlen = sizeof(addr);
594 if (getpeername(fd, (struct sockaddr*)&addr, &addrlen) < 0) {
595 dropbear_exit("Failed socket address: %s", strerror(errno));
597 getaddrstring(&addr, remote_host, remote_port, host_lookup);
601 /* Return a string representation of the socket address passed. The return
602 * value is allocated with malloc() */
603 void getaddrstring(struct sockaddr_storage* addr,
604 char **ret_host, char **ret_port,
605 int host_lookup) {
607 char host[NI_MAXHOST+1], serv[NI_MAXSERV+1];
608 unsigned int len;
609 int ret;
611 int flags = NI_NUMERICSERV | NI_NUMERICHOST;
613 #ifndef DO_HOST_LOOKUP
614 host_lookup = 0;
615 #endif
617 if (host_lookup) {
618 flags = NI_NUMERICSERV;
621 len = sizeof(struct sockaddr_storage);
622 /* Some platforms such as Solaris 8 require that len is the length
623 * of the specific structure. Some older linux systems (glibc 2.1.3
624 * such as debian potato) have sockaddr_storage.__ss_family instead
625 * but we'll ignore them */
626 #ifdef HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY
627 if (addr->ss_family == AF_INET) {
628 len = sizeof(struct sockaddr_in);
630 #ifdef AF_INET6
631 if (addr->ss_family == AF_INET6) {
632 len = sizeof(struct sockaddr_in6);
634 #endif
635 #endif
637 ret = getnameinfo((struct sockaddr*)addr, len, host, sizeof(host)-1,
638 serv, sizeof(serv)-1, flags);
640 if (ret != 0) {
641 if (host_lookup) {
642 /* On some systems (Darwin does it) we get EINTR from getnameinfo
643 * somehow. Eew. So we'll just return the IP, since that doesn't seem
644 * to exhibit that behaviour. */
645 getaddrstring(addr, ret_host, ret_port, 0);
646 return;
647 } else {
648 /* if we can't do a numeric lookup, something's gone terribly wrong */
649 dropbear_exit("Failed lookup: %s", gai_strerror(ret));
653 if (ret_host) {
654 *ret_host = m_strdup(host);
656 if (ret_port) {
657 *ret_port = m_strdup(serv);
661 #ifdef DEBUG_TRACE
662 void printhex(const char * label, const unsigned char * buf, int len) {
664 int i;
666 fprintf(stderr, "%s\n", label);
667 for (i = 0; i < len; i++) {
668 fprintf(stderr, "%02x", buf[i]);
669 if (i % 16 == 15) {
670 fprintf(stderr, "\n");
672 else if (i % 2 == 1) {
673 fprintf(stderr, " ");
676 fprintf(stderr, "\n");
678 #endif
680 /* Strip all control characters from text (a null-terminated string), except
681 * for '\n', '\r' and '\t'.
682 * The result returned is a newly allocated string, this must be free()d after
683 * use */
684 char * stripcontrol(const char * text) {
686 char * ret;
687 int len, pos;
688 int i;
690 len = strlen(text);
691 ret = m_malloc(len+1);
693 pos = 0;
694 for (i = 0; i < len; i++) {
695 if ((text[i] <= '~' && text[i] >= ' ') /* normal printable range */
696 || text[i] == '\n' || text[i] == '\r' || text[i] == '\t') {
697 ret[pos] = text[i];
698 pos++;
701 ret[pos] = 0x0;
702 return ret;
706 /* reads the contents of filename into the buffer buf, from the current
707 * position, either to the end of the file, or the buffer being full.
708 * Returns DROPBEAR_SUCCESS or DROPBEAR_FAILURE */
709 int buf_readfile(buffer* buf, const char* filename) {
711 int fd = -1;
712 int len;
713 int maxlen;
714 int ret = DROPBEAR_FAILURE;
716 fd = open(filename, O_RDONLY);
718 if (fd < 0) {
719 goto out;
722 do {
723 maxlen = buf->size - buf->pos;
724 len = read(fd, buf_getwriteptr(buf, maxlen), maxlen);
725 if (len < 0) {
726 if (errno == EINTR || errno == EAGAIN) {
727 continue;
729 goto out;
731 buf_incrwritepos(buf, len);
732 } while (len < maxlen && len > 0);
734 ret = DROPBEAR_SUCCESS;
736 out:
737 if (fd >= 0) {
738 m_close(fd);
740 return ret;
743 /* get a line from the file into buffer in the style expected for an
744 * authkeys file.
745 * Will return DROPBEAR_SUCCESS if data is read, or DROPBEAR_FAILURE on EOF.*/
746 /* Only used for ~/.ssh/known_hosts and ~/.ssh/authorized_keys */
747 #if defined(DROPBEAR_CLIENT) || defined(ENABLE_SVR_PUBKEY_AUTH)
748 int buf_getline(buffer * line, FILE * authfile) {
750 int c = EOF;
752 buf_setpos(line, 0);
753 buf_setlen(line, 0);
755 while (line->pos < line->size) {
757 c = fgetc(authfile); /*getc() is weird with some uClibc systems*/
758 if (c == EOF || c == '\n' || c == '\r') {
759 goto out;
762 buf_putbyte(line, (unsigned char)c);
765 TRACE(("leave getauthline: line too long"))
766 /* We return success, but the line length will be zeroed - ie we just
767 * ignore that line */
768 buf_setlen(line, 0);
770 out:
773 /* if we didn't read anything before EOF or error, exit */
774 if (c == EOF && line->pos == 0) {
775 return DROPBEAR_FAILURE;
776 } else {
777 buf_setpos(line, 0);
778 return DROPBEAR_SUCCESS;
782 #endif
784 /* make sure that the socket closes */
785 void m_close(int fd) {
787 int val;
788 do {
789 val = close(fd);
790 } while (val < 0 && errno == EINTR);
792 if (val < 0 && errno != EBADF) {
793 /* Linux says EIO can happen */
794 dropbear_exit("Error closing fd %d, %s", fd, strerror(errno));
798 void * m_malloc(size_t size) {
800 void* ret;
802 if (size == 0) {
803 dropbear_exit("m_malloc failed");
805 ret = calloc(1, size);
806 if (ret == NULL) {
807 dropbear_exit("m_malloc failed");
809 return ret;
813 void * m_strdup(const char * str) {
814 char* ret;
816 ret = strdup(str);
817 if (ret == NULL) {
818 dropbear_exit("m_strdup failed");
820 return ret;
823 void * m_realloc(void* ptr, size_t size) {
825 void *ret;
827 if (size == 0) {
828 dropbear_exit("m_realloc failed");
830 ret = realloc(ptr, size);
831 if (ret == NULL) {
832 dropbear_exit("m_realloc failed");
834 return ret;
837 /* Clear the data, based on the method in David Wheeler's
838 * "Secure Programming for Linux and Unix HOWTO" */
839 /* Beware of calling this from within dbutil.c - things might get
840 * optimised away */
841 void m_burn(void *data, unsigned int len) {
842 volatile char *p = data;
844 if (data == NULL)
845 return;
846 while (len--) {
847 *p++ = 0x0;
852 void setnonblocking(int fd) {
854 TRACE(("setnonblocking: %d", fd))
856 if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) {
857 if (errno == ENODEV) {
858 /* Some devices (like /dev/null redirected in)
859 * can't be set to non-blocking */
860 TRACE(("ignoring ENODEV for setnonblocking"))
861 } else {
862 dropbear_exit("Couldn't set nonblocking");
865 TRACE(("leave setnonblocking"))
868 void disallow_core() {
869 struct rlimit lim;
870 lim.rlim_cur = lim.rlim_max = 0;
871 setrlimit(RLIMIT_CORE, &lim);
874 /* Returns DROPBEAR_SUCCESS or DROPBEAR_FAILURE, with the result in *val */
875 int m_str_to_uint(const char* str, unsigned int *val) {
876 errno = 0;
877 *val = strtoul(str, NULL, 10);
878 /* The c99 spec doesn't actually seem to define EINVAL, but most platforms
879 * I've looked at mention it in their manpage */
880 if ((*val == 0 && errno == EINVAL)
881 || (*val == ULONG_MAX && errno == ERANGE)) {
882 return DROPBEAR_FAILURE;
883 } else {
884 return DROPBEAR_SUCCESS;
888 int constant_time_memcmp(const void* a, const void *b, size_t n)
890 const char *xa = a, *xb = b;
891 uint8_t c = 0;
892 size_t i;
893 for (i = 0; i < n; i++)
895 c |= (xa[i] ^ xb[i]);
897 return c;