Tomato 1.28
[tomato.git] / release / src / router / dropbear / dbutil.c
blobb016dc10ac76e768233820ebf237b7304c74bcc4
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);
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)
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, ...) {
142 va_list param;
144 if (!debug_trace) {
145 return;
148 va_start(param, format);
149 fprintf(stderr, "TRACE (%d): ", getpid());
150 vfprintf(stderr, format, param);
151 fprintf(stderr, "\n");
152 va_end(param);
154 #endif /* DEBUG_TRACE */
156 static void set_sock_priority(int sock) {
158 int val;
160 /* disable nagle */
161 val = 1;
162 setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (void*)&val, sizeof(val));
164 /* set the TOS bit. note that this will fail for ipv6, I can't find any
165 * equivalent. */
166 #ifdef IPTOS_LOWDELAY
167 val = IPTOS_LOWDELAY;
168 setsockopt(sock, IPPROTO_IP, IP_TOS, (void*)&val, sizeof(val));
169 #endif
171 #ifdef SO_PRIORITY
172 /* linux specific, sets QoS class.
173 * 6 looks to be optimal for interactive traffic (see tc-prio(8) ). */
174 val = 6;
175 setsockopt(sock, SOL_SOCKET, SO_PRIORITY, (void*) &val, sizeof(val));
176 #endif
180 /* Listen on address:port.
181 * Special cases are address of "" listening on everything,
182 * and address of NULL listening on localhost only.
183 * Returns the number of sockets bound on success, or -1 on failure. On
184 * failure, if errstring wasn't NULL, it'll be a newly malloced error
185 * string.*/
186 int dropbear_listen(const char* address, const char* port,
187 int *socks, unsigned int sockcount, char **errstring, int *maxfd) {
189 struct addrinfo hints, *res = NULL, *res0 = NULL;
190 int err;
191 unsigned int nsock;
192 struct linger linger;
193 int val;
194 int sock;
196 TRACE(("enter dropbear_listen"))
198 memset(&hints, 0, sizeof(hints));
199 hints.ai_family = AF_UNSPEC; /* TODO: let them flag v4 only etc */
200 hints.ai_socktype = SOCK_STREAM;
202 /* for calling getaddrinfo:
203 address == NULL and !AI_PASSIVE: local loopback
204 address == NULL and AI_PASSIVE: all interfaces
205 address != NULL: whatever the address says */
206 if (!address) {
207 TRACE(("dropbear_listen: local loopback"))
208 } else {
209 if (address[0] == '\0') {
210 TRACE(("dropbear_listen: all interfaces"))
211 address = NULL;
213 hints.ai_flags = AI_PASSIVE;
215 err = getaddrinfo(address, port, &hints, &res0);
217 if (err) {
218 if (errstring != NULL && *errstring == NULL) {
219 int len;
220 len = 20 + strlen(gai_strerror(err));
221 *errstring = (char*)m_malloc(len);
222 snprintf(*errstring, len, "Error resolving: %s", gai_strerror(err));
224 if (res0) {
225 freeaddrinfo(res0);
226 res0 = NULL;
228 TRACE(("leave dropbear_listen: failed resolving"))
229 return -1;
233 nsock = 0;
234 for (res = res0; res != NULL && nsock < sockcount;
235 res = res->ai_next) {
237 /* Get a socket */
238 socks[nsock] = socket(res->ai_family, res->ai_socktype,
239 res->ai_protocol);
241 sock = socks[nsock]; /* For clarity */
243 if (sock < 0) {
244 err = errno;
245 TRACE(("socket() failed"))
246 continue;
249 /* Various useful socket options */
250 val = 1;
251 /* set to reuse, quick timeout */
252 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*) &val, sizeof(val));
253 linger.l_onoff = 1;
254 linger.l_linger = 5;
255 setsockopt(sock, SOL_SOCKET, SO_LINGER, (void*)&linger, sizeof(linger));
257 set_sock_priority(sock);
259 if (bind(sock, res->ai_addr, res->ai_addrlen) < 0) {
260 err = errno;
261 close(sock);
262 TRACE(("bind(%s) failed", port))
263 continue;
266 if (listen(sock, 20) < 0) {
267 err = errno;
268 close(sock);
269 TRACE(("listen() failed"))
270 continue;
273 *maxfd = MAX(*maxfd, sock);
275 nsock++;
278 if (res0) {
279 freeaddrinfo(res0);
280 res0 = NULL;
283 if (nsock == 0) {
284 if (errstring != NULL && *errstring == NULL) {
285 int len;
286 len = 20 + strlen(strerror(err));
287 *errstring = (char*)m_malloc(len);
288 snprintf(*errstring, len, "Error listening: %s", strerror(err));
290 TRACE(("leave dropbear_listen: failure, %s", strerror(err)))
291 return -1;
294 TRACE(("leave dropbear_listen: success, %d socks bound", nsock))
295 return nsock;
298 /* Connect via TCP to a host. Connection will try ipv4 or ipv6, will
299 * return immediately if nonblocking is set. On failure, if errstring
300 * wasn't null, it will be a newly malloced error message */
302 /* TODO: maxfd */
303 int connect_remote(const char* remotehost, const char* remoteport,
304 int nonblocking, char ** errstring) {
306 struct addrinfo *res0 = NULL, *res = NULL, hints;
307 int sock;
308 int err;
310 TRACE(("enter connect_remote"))
312 if (errstring != NULL) {
313 *errstring = NULL;
316 memset(&hints, 0, sizeof(hints));
317 hints.ai_socktype = SOCK_STREAM;
318 hints.ai_family = PF_UNSPEC;
320 err = getaddrinfo(remotehost, remoteport, &hints, &res0);
321 if (err) {
322 if (errstring != NULL && *errstring == NULL) {
323 int len;
324 len = 100 + strlen(gai_strerror(err));
325 *errstring = (char*)m_malloc(len);
326 snprintf(*errstring, len, "Error resolving '%s' port '%s'. %s",
327 remotehost, remoteport, gai_strerror(err));
329 TRACE(("Error resolving: %s", gai_strerror(err)))
330 return -1;
333 sock = -1;
334 err = EADDRNOTAVAIL;
335 for (res = res0; res; res = res->ai_next) {
337 sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
338 if (sock < 0) {
339 err = errno;
340 continue;
343 if (nonblocking) {
344 if (fcntl(sock, F_SETFL, O_NONBLOCK) < 0) {
345 close(sock);
346 sock = -1;
347 if (errstring != NULL && *errstring == NULL) {
348 *errstring = m_strdup("Failed non-blocking");
350 TRACE(("Failed non-blocking: %s", strerror(errno)))
351 continue;
355 if (connect(sock, res->ai_addr, res->ai_addrlen) < 0) {
356 if (errno == EINPROGRESS && nonblocking) {
357 TRACE(("Connect in progress"))
358 break;
359 } else {
360 err = errno;
361 close(sock);
362 sock = -1;
363 continue;
367 break; /* Success */
370 if (sock < 0 && !(errno == EINPROGRESS && nonblocking)) {
371 /* Failed */
372 if (errstring != NULL && *errstring == NULL) {
373 int len;
374 len = 20 + strlen(strerror(err));
375 *errstring = (char*)m_malloc(len);
376 snprintf(*errstring, len, "Error connecting: %s", strerror(err));
378 TRACE(("Error connecting: %s", strerror(err)))
379 } else {
380 /* Success */
381 set_sock_priority(sock);
384 freeaddrinfo(res0);
385 if (sock > 0 && errstring != NULL && *errstring != NULL) {
386 m_free(*errstring);
389 TRACE(("leave connect_remote: sock %d\n", sock))
390 return sock;
393 /* Sets up a pipe for a, returning three non-blocking file descriptors
394 * and the pid. exec_fn is the function that will actually execute the child process,
395 * it will be run after the child has fork()ed, and is passed exec_data.
396 * If ret_errfd == NULL then stderr will not be captured.
397 * ret_pid can be passed as NULL to discard the pid. */
398 int spawn_command(void(*exec_fn)(void *user_data), void *exec_data,
399 int *ret_writefd, int *ret_readfd, int *ret_errfd, pid_t *ret_pid) {
400 int infds[2];
401 int outfds[2];
402 int errfds[2];
403 pid_t pid;
405 const int FDIN = 0;
406 const int FDOUT = 1;
408 /* redirect stdin/stdout/stderr */
409 if (pipe(infds) != 0) {
410 return DROPBEAR_FAILURE;
412 if (pipe(outfds) != 0) {
413 return DROPBEAR_FAILURE;
415 if (ret_errfd && pipe(errfds) != 0) {
416 return DROPBEAR_FAILURE;
419 #ifdef __uClinux__
420 pid = vfork();
421 #else
422 pid = fork();
423 #endif
425 if (pid < 0) {
426 return DROPBEAR_FAILURE;
429 if (!pid) {
430 /* child */
432 TRACE(("back to normal sigchld"))
433 /* Revert to normal sigchld handling */
434 if (signal(SIGCHLD, SIG_DFL) == SIG_ERR) {
435 dropbear_exit("signal() error");
438 /* redirect stdin/stdout */
440 if ((dup2(infds[FDIN], STDIN_FILENO) < 0) ||
441 (dup2(outfds[FDOUT], STDOUT_FILENO) < 0) ||
442 (ret_errfd && dup2(errfds[FDOUT], STDERR_FILENO) < 0)) {
443 TRACE(("leave noptycommand: error redirecting FDs"))
444 dropbear_exit("child dup2() failure");
447 close(infds[FDOUT]);
448 close(infds[FDIN]);
449 close(outfds[FDIN]);
450 close(outfds[FDOUT]);
451 if (ret_errfd)
453 close(errfds[FDIN]);
454 close(errfds[FDOUT]);
457 exec_fn(exec_data);
458 /* not reached */
459 return DROPBEAR_FAILURE;
460 } else {
461 /* parent */
462 close(infds[FDIN]);
463 close(outfds[FDOUT]);
465 setnonblocking(outfds[FDIN]);
466 setnonblocking(infds[FDOUT]);
468 if (ret_errfd) {
469 close(errfds[FDOUT]);
470 setnonblocking(errfds[FDIN]);
473 if (ret_pid) {
474 *ret_pid = pid;
477 *ret_writefd = infds[FDOUT];
478 *ret_readfd = outfds[FDIN];
479 if (ret_errfd) {
480 *ret_errfd = errfds[FDIN];
482 return DROPBEAR_SUCCESS;
486 /* Runs a command with "sh -c". Will close FDs (except stdin/stdout/stderr) and
487 * re-enabled SIGPIPE. If cmd is NULL, will run a login shell.
489 void run_shell_command(const char* cmd, unsigned int maxfd, char* usershell) {
490 char * argv[4];
491 char * baseshell = NULL;
492 unsigned int i;
494 baseshell = basename(usershell);
496 if (cmd != NULL) {
497 argv[0] = baseshell;
498 } else {
499 /* a login shell should be "-bash" for "/bin/bash" etc */
500 int len = strlen(baseshell) + 2; /* 2 for "-" */
501 argv[0] = (char*)m_malloc(len);
502 snprintf(argv[0], len, "-%s", baseshell);
505 if (cmd != NULL) {
506 argv[1] = "-c";
507 argv[2] = (char*)cmd;
508 argv[3] = NULL;
509 } else {
510 /* construct a shell of the form "-bash" etc */
511 argv[1] = NULL;
514 /* Re-enable SIGPIPE for the executed process */
515 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR) {
516 dropbear_exit("signal() error");
519 /* close file descriptors except stdin/stdout/stderr
520 * Need to be sure FDs are closed here to avoid reading files as root */
521 for (i = 3; i <= maxfd; i++) {
522 m_close(i);
525 execv(usershell, argv);
528 /* Return a string representation of the socket address passed. The return
529 * value is allocated with malloc() */
530 unsigned char * getaddrstring(struct sockaddr_storage* addr, int withport) {
532 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
533 char *retstring = NULL;
534 int ret;
535 unsigned int len;
537 len = sizeof(struct sockaddr_storage);
538 /* Some platforms such as Solaris 8 require that len is the length
539 * of the specific structure. Some older linux systems (glibc 2.1.3
540 * such as debian potato) have sockaddr_storage.__ss_family instead
541 * but we'll ignore them */
542 #ifdef HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY
543 if (addr->ss_family == AF_INET) {
544 len = sizeof(struct sockaddr_in);
546 #ifdef AF_INET6
547 if (addr->ss_family == AF_INET6) {
548 len = sizeof(struct sockaddr_in6);
550 #endif
551 #endif
553 ret = getnameinfo((struct sockaddr*)addr, len, hbuf, sizeof(hbuf),
554 sbuf, sizeof(sbuf), NI_NUMERICSERV | NI_NUMERICHOST);
556 if (ret != 0) {
557 /* This is a fairly bad failure - it'll fallback to IP if it
558 * just can't resolve */
559 dropbear_exit("failed lookup (%d, %d)", ret, errno);
562 if (withport) {
563 len = strlen(hbuf) + 2 + strlen(sbuf);
564 retstring = (char*)m_malloc(len);
565 snprintf(retstring, len, "%s:%s", hbuf, sbuf);
566 } else {
567 retstring = m_strdup(hbuf);
570 return retstring;
574 /* Get the hostname corresponding to the address addr. On failure, the IP
575 * address is returned. The return value is allocated with strdup() */
576 char* getaddrhostname(struct sockaddr_storage * addr) {
578 char hbuf[NI_MAXHOST];
579 char sbuf[NI_MAXSERV];
580 int ret;
581 unsigned int len;
582 #ifdef DO_HOST_LOOKUP
583 const int flags = NI_NUMERICSERV;
584 #else
585 const int flags = NI_NUMERICHOST | NI_NUMERICSERV;
586 #endif
588 len = sizeof(struct sockaddr_storage);
589 /* Some platforms such as Solaris 8 require that len is the length
590 * of the specific structure. */
591 #ifdef HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY
592 if (addr->ss_family == AF_INET) {
593 len = sizeof(struct sockaddr_in);
595 #ifdef AF_INET6
596 if (addr->ss_family == AF_INET6) {
597 len = sizeof(struct sockaddr_in6);
599 #endif
600 #endif
603 ret = getnameinfo((struct sockaddr*)addr, len, hbuf, sizeof(hbuf),
604 sbuf, sizeof(sbuf), flags);
606 if (ret != 0) {
607 /* On some systems (Darwin does it) we get EINTR from getnameinfo
608 * somehow. Eew. So we'll just return the IP, since that doesn't seem
609 * to exhibit that behaviour. */
610 return getaddrstring(addr, 0);
613 return m_strdup(hbuf);
616 #ifdef DEBUG_TRACE
617 void printhex(const char * label, const unsigned char * buf, int len) {
619 int i;
621 fprintf(stderr, "%s\n", label);
622 for (i = 0; i < len; i++) {
623 fprintf(stderr, "%02x", buf[i]);
624 if (i % 16 == 15) {
625 fprintf(stderr, "\n");
627 else if (i % 2 == 1) {
628 fprintf(stderr, " ");
631 fprintf(stderr, "\n");
633 #endif
635 /* Strip all control characters from text (a null-terminated string), except
636 * for '\n', '\r' and '\t'.
637 * The result returned is a newly allocated string, this must be free()d after
638 * use */
639 char * stripcontrol(const char * text) {
641 char * ret;
642 int len, pos;
643 int i;
645 len = strlen(text);
646 ret = m_malloc(len+1);
648 pos = 0;
649 for (i = 0; i < len; i++) {
650 if ((text[i] <= '~' && text[i] >= ' ') /* normal printable range */
651 || text[i] == '\n' || text[i] == '\r' || text[i] == '\t') {
652 ret[pos] = text[i];
653 pos++;
656 ret[pos] = 0x0;
657 return ret;
661 /* reads the contents of filename into the buffer buf, from the current
662 * position, either to the end of the file, or the buffer being full.
663 * Returns DROPBEAR_SUCCESS or DROPBEAR_FAILURE */
664 int buf_readfile(buffer* buf, const char* filename) {
666 int fd = -1;
667 int len;
668 int maxlen;
669 int ret = DROPBEAR_FAILURE;
671 fd = open(filename, O_RDONLY);
673 if (fd < 0) {
674 goto out;
677 do {
678 maxlen = buf->size - buf->pos;
679 len = read(fd, buf_getwriteptr(buf, maxlen), maxlen);
680 if (len < 0) {
681 if (errno == EINTR || errno == EAGAIN) {
682 continue;
684 goto out;
686 buf_incrwritepos(buf, len);
687 } while (len < maxlen && len > 0);
689 ret = DROPBEAR_SUCCESS;
691 out:
692 if (fd >= 0) {
693 m_close(fd);
695 return ret;
698 /* get a line from the file into buffer in the style expected for an
699 * authkeys file.
700 * Will return DROPBEAR_SUCCESS if data is read, or DROPBEAR_FAILURE on EOF.*/
701 /* Only used for ~/.ssh/known_hosts and ~/.ssh/authorized_keys */
702 #if defined(DROPBEAR_CLIENT) || defined(ENABLE_SVR_PUBKEY_AUTH)
703 int buf_getline(buffer * line, FILE * authfile) {
705 int c = EOF;
707 TRACE(("enter buf_getline"))
709 buf_setpos(line, 0);
710 buf_setlen(line, 0);
712 while (line->pos < line->size) {
714 c = fgetc(authfile); /*getc() is weird with some uClibc systems*/
715 if (c == EOF || c == '\n' || c == '\r') {
716 goto out;
719 buf_putbyte(line, (unsigned char)c);
722 TRACE(("leave getauthline: line too long"))
723 /* We return success, but the line length will be zeroed - ie we just
724 * ignore that line */
725 buf_setlen(line, 0);
727 out:
730 /* if we didn't read anything before EOF or error, exit */
731 if (c == EOF && line->pos == 0) {
732 TRACE(("leave buf_getline: failure"))
733 return DROPBEAR_FAILURE;
734 } else {
735 TRACE(("leave buf_getline: success"))
736 buf_setpos(line, 0);
737 return DROPBEAR_SUCCESS;
741 #endif
743 /* make sure that the socket closes */
744 void m_close(int fd) {
746 int val;
747 do {
748 val = close(fd);
749 } while (val < 0 && errno == EINTR);
751 if (val < 0 && errno != EBADF) {
752 /* Linux says EIO can happen */
753 dropbear_exit("Error closing fd %d, %s", fd, strerror(errno));
757 void * m_malloc(size_t size) {
759 void* ret;
761 if (size == 0) {
762 dropbear_exit("m_malloc failed");
764 ret = calloc(1, size);
765 if (ret == NULL) {
766 dropbear_exit("m_malloc failed");
768 return ret;
772 void * m_strdup(const char * str) {
773 char* ret;
775 ret = strdup(str);
776 if (ret == NULL) {
777 dropbear_exit("m_strdup failed");
779 return ret;
782 void __m_free(void* ptr) {
783 if (ptr != NULL) {
784 free(ptr);
788 void * m_realloc(void* ptr, size_t size) {
790 void *ret;
792 if (size == 0) {
793 dropbear_exit("m_realloc failed");
795 ret = realloc(ptr, size);
796 if (ret == NULL) {
797 dropbear_exit("m_realloc failed");
799 return ret;
802 /* Clear the data, based on the method in David Wheeler's
803 * "Secure Programming for Linux and Unix HOWTO" */
804 /* Beware of calling this from within dbutil.c - things might get
805 * optimised away */
806 void m_burn(void *data, unsigned int len) {
807 volatile char *p = data;
809 if (data == NULL)
810 return;
811 while (len--) {
812 *p++ = 0x66;
817 void setnonblocking(int fd) {
819 TRACE(("setnonblocking: %d", fd))
821 if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) {
822 if (errno == ENODEV) {
823 /* Some devices (like /dev/null redirected in)
824 * can't be set to non-blocking */
825 TRACE(("ignoring ENODEV for setnonblocking"))
826 } else {
827 dropbear_exit("Couldn't set nonblocking");
830 TRACE(("leave setnonblocking"))
833 void disallow_core() {
834 struct rlimit lim;
835 lim.rlim_cur = lim.rlim_max = 0;
836 setrlimit(RLIMIT_CORE, &lim);
839 /* Returns DROPBEAR_SUCCESS or DROPBEAR_FAILURE, with the result in *val */
840 int m_str_to_uint(const char* str, unsigned int *val) {
841 errno = 0;
842 *val = strtoul(str, NULL, 10);
843 /* The c99 spec doesn't actually seem to define EINVAL, but most platforms
844 * I've looked at mention it in their manpage */
845 if ((*val == 0 && errno == EINVAL)
846 || (*val == ULONG_MAX && errno == ERANGE)) {
847 return DROPBEAR_FAILURE;
848 } else {
849 return DROPBEAR_SUCCESS;