remove unused variable
[dropbear.git] / dbutil.c
blob9fd90d1e7bdf54dc7f6c401437b6f32a16e99777
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 to a given unix socket. The socket is blocking */
299 #ifdef ENABLE_CONNECT_UNIX
300 int connect_unix(const char* path) {
301 struct sockaddr_un addr;
302 int fd = -1;
304 memset((void*)&addr, 0x0, sizeof(addr));
305 addr.sun_family = AF_UNIX;
306 strlcpy(addr.sun_path, path, sizeof(addr.sun_path));
307 fd = socket(PF_UNIX, SOCK_STREAM, 0);
308 if (fd < 0) {
309 TRACE(("Failed to open unix socket"))
310 return -1;
312 if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
313 TRACE(("Failed to connect to '%s' socket", path))
314 return -1;
316 return fd;
318 #endif
320 /* Connect via TCP to a host. Connection will try ipv4 or ipv6, will
321 * return immediately if nonblocking is set. On failure, if errstring
322 * wasn't null, it will be a newly malloced error message */
324 /* TODO: maxfd */
325 int connect_remote(const char* remotehost, const char* remoteport,
326 int nonblocking, char ** errstring) {
328 struct addrinfo *res0 = NULL, *res = NULL, hints;
329 int sock;
330 int err;
332 TRACE(("enter connect_remote"))
334 if (errstring != NULL) {
335 *errstring = NULL;
338 memset(&hints, 0, sizeof(hints));
339 hints.ai_socktype = SOCK_STREAM;
340 hints.ai_family = PF_UNSPEC;
342 err = getaddrinfo(remotehost, remoteport, &hints, &res0);
343 if (err) {
344 if (errstring != NULL && *errstring == NULL) {
345 int len;
346 len = 100 + strlen(gai_strerror(err));
347 *errstring = (char*)m_malloc(len);
348 snprintf(*errstring, len, "Error resolving '%s' port '%s'. %s",
349 remotehost, remoteport, gai_strerror(err));
351 TRACE(("Error resolving: %s", gai_strerror(err)))
352 return -1;
355 sock = -1;
356 err = EADDRNOTAVAIL;
357 for (res = res0; res; res = res->ai_next) {
359 sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
360 if (sock < 0) {
361 err = errno;
362 continue;
365 if (nonblocking) {
366 setnonblocking(sock);
369 if (connect(sock, res->ai_addr, res->ai_addrlen) < 0) {
370 if (errno == EINPROGRESS && nonblocking) {
371 TRACE(("Connect in progress"))
372 break;
373 } else {
374 err = errno;
375 close(sock);
376 sock = -1;
377 continue;
381 break; /* Success */
384 if (sock < 0 && !(errno == EINPROGRESS && nonblocking)) {
385 /* Failed */
386 if (errstring != NULL && *errstring == NULL) {
387 int len;
388 len = 20 + strlen(strerror(err));
389 *errstring = (char*)m_malloc(len);
390 snprintf(*errstring, len, "Error connecting: %s", strerror(err));
392 TRACE(("Error connecting: %s", strerror(err)))
393 } else {
394 /* Success */
395 set_sock_priority(sock);
398 freeaddrinfo(res0);
399 if (sock > 0 && errstring != NULL && *errstring != NULL) {
400 m_free(*errstring);
403 TRACE(("leave connect_remote: sock %d\n", sock))
404 return sock;
407 /* Sets up a pipe for a, returning three non-blocking file descriptors
408 * and the pid. exec_fn is the function that will actually execute the child process,
409 * it will be run after the child has fork()ed, and is passed exec_data.
410 * If ret_errfd == NULL then stderr will not be captured.
411 * ret_pid can be passed as NULL to discard the pid. */
412 int spawn_command(void(*exec_fn)(void *user_data), void *exec_data,
413 int *ret_writefd, int *ret_readfd, int *ret_errfd, pid_t *ret_pid) {
414 int infds[2];
415 int outfds[2];
416 int errfds[2];
417 pid_t pid;
419 const int FDIN = 0;
420 const int FDOUT = 1;
422 /* redirect stdin/stdout/stderr */
423 if (pipe(infds) != 0) {
424 return DROPBEAR_FAILURE;
426 if (pipe(outfds) != 0) {
427 return DROPBEAR_FAILURE;
429 if (ret_errfd && pipe(errfds) != 0) {
430 return DROPBEAR_FAILURE;
433 #ifdef __uClinux__
434 pid = vfork();
435 #else
436 pid = fork();
437 #endif
439 if (pid < 0) {
440 return DROPBEAR_FAILURE;
443 if (!pid) {
444 /* child */
446 TRACE(("back to normal sigchld"))
447 /* Revert to normal sigchld handling */
448 if (signal(SIGCHLD, SIG_DFL) == SIG_ERR) {
449 dropbear_exit("signal() error");
452 /* redirect stdin/stdout */
454 if ((dup2(infds[FDIN], STDIN_FILENO) < 0) ||
455 (dup2(outfds[FDOUT], STDOUT_FILENO) < 0) ||
456 (ret_errfd && dup2(errfds[FDOUT], STDERR_FILENO) < 0)) {
457 TRACE(("leave noptycommand: error redirecting FDs"))
458 dropbear_exit("child dup2() failure");
461 close(infds[FDOUT]);
462 close(infds[FDIN]);
463 close(outfds[FDIN]);
464 close(outfds[FDOUT]);
465 if (ret_errfd)
467 close(errfds[FDIN]);
468 close(errfds[FDOUT]);
471 exec_fn(exec_data);
472 /* not reached */
473 return DROPBEAR_FAILURE;
474 } else {
475 /* parent */
476 close(infds[FDIN]);
477 close(outfds[FDOUT]);
479 setnonblocking(outfds[FDIN]);
480 setnonblocking(infds[FDOUT]);
482 if (ret_errfd) {
483 close(errfds[FDOUT]);
484 setnonblocking(errfds[FDIN]);
487 if (ret_pid) {
488 *ret_pid = pid;
491 *ret_writefd = infds[FDOUT];
492 *ret_readfd = outfds[FDIN];
493 if (ret_errfd) {
494 *ret_errfd = errfds[FDIN];
496 return DROPBEAR_SUCCESS;
500 /* Runs a command with "sh -c". Will close FDs (except stdin/stdout/stderr) and
501 * re-enabled SIGPIPE. If cmd is NULL, will run a login shell.
503 void run_shell_command(const char* cmd, unsigned int maxfd, char* usershell) {
504 char * argv[4];
505 char * baseshell = NULL;
506 unsigned int i;
508 baseshell = basename(usershell);
510 if (cmd != NULL) {
511 argv[0] = baseshell;
512 } else {
513 /* a login shell should be "-bash" for "/bin/bash" etc */
514 int len = strlen(baseshell) + 2; /* 2 for "-" */
515 argv[0] = (char*)m_malloc(len);
516 snprintf(argv[0], len, "-%s", baseshell);
519 if (cmd != NULL) {
520 argv[1] = "-c";
521 argv[2] = (char*)cmd;
522 argv[3] = NULL;
523 } else {
524 /* construct a shell of the form "-bash" etc */
525 argv[1] = NULL;
528 /* Re-enable SIGPIPE for the executed process */
529 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR) {
530 dropbear_exit("signal() error");
533 /* close file descriptors except stdin/stdout/stderr
534 * Need to be sure FDs are closed here to avoid reading files as root */
535 for (i = 3; i <= maxfd; i++) {
536 m_close(i);
539 execv(usershell, argv);
542 void get_socket_address(int fd, char **local_host, char **local_port,
543 char **remote_host, char **remote_port, int host_lookup)
545 struct sockaddr_storage addr;
546 socklen_t addrlen;
548 if (local_host || local_port) {
549 addrlen = sizeof(addr);
550 if (getsockname(fd, (struct sockaddr*)&addr, &addrlen) < 0) {
551 dropbear_exit("Failed socket address: %s", strerror(errno));
553 getaddrstring(&addr, local_host, local_port, host_lookup);
555 if (remote_host || remote_port) {
556 addrlen = sizeof(addr);
557 if (getpeername(fd, (struct sockaddr*)&addr, &addrlen) < 0) {
558 dropbear_exit("Failed socket address: %s", strerror(errno));
560 getaddrstring(&addr, remote_host, remote_port, host_lookup);
564 /* Return a string representation of the socket address passed. The return
565 * value is allocated with malloc() */
566 void getaddrstring(struct sockaddr_storage* addr,
567 char **ret_host, char **ret_port,
568 int host_lookup) {
570 char host[NI_MAXHOST+1], serv[NI_MAXSERV+1];
571 unsigned int len;
572 int ret;
574 int flags = NI_NUMERICSERV | NI_NUMERICHOST;
576 #ifndef DO_HOST_LOOKUP
577 host_lookup = 0;
578 #endif
580 if (host_lookup) {
581 flags = NI_NUMERICSERV;
584 len = sizeof(struct sockaddr_storage);
585 /* Some platforms such as Solaris 8 require that len is the length
586 * of the specific structure. Some older linux systems (glibc 2.1.3
587 * such as debian potato) have sockaddr_storage.__ss_family instead
588 * but we'll ignore them */
589 #ifdef HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY
590 if (addr->ss_family == AF_INET) {
591 len = sizeof(struct sockaddr_in);
593 #ifdef AF_INET6
594 if (addr->ss_family == AF_INET6) {
595 len = sizeof(struct sockaddr_in6);
597 #endif
598 #endif
600 ret = getnameinfo((struct sockaddr*)addr, len, host, sizeof(host)-1,
601 serv, sizeof(serv)-1, flags);
603 if (ret != 0) {
604 if (host_lookup) {
605 /* On some systems (Darwin does it) we get EINTR from getnameinfo
606 * somehow. Eew. So we'll just return the IP, since that doesn't seem
607 * to exhibit that behaviour. */
608 getaddrstring(addr, ret_host, ret_port, 0);
609 return;
610 } else {
611 /* if we can't do a numeric lookup, something's gone terribly wrong */
612 dropbear_exit("Failed lookup: %s", gai_strerror(ret));
616 if (ret_host) {
617 *ret_host = m_strdup(host);
619 if (ret_port) {
620 *ret_port = m_strdup(serv);
624 #ifdef DEBUG_TRACE
625 void printhex(const char * label, const unsigned char * buf, int len) {
627 int i;
629 fprintf(stderr, "%s\n", label);
630 for (i = 0; i < len; i++) {
631 fprintf(stderr, "%02x", buf[i]);
632 if (i % 16 == 15) {
633 fprintf(stderr, "\n");
635 else if (i % 2 == 1) {
636 fprintf(stderr, " ");
639 fprintf(stderr, "\n");
641 #endif
643 /* Strip all control characters from text (a null-terminated string), except
644 * for '\n', '\r' and '\t'.
645 * The result returned is a newly allocated string, this must be free()d after
646 * use */
647 char * stripcontrol(const char * text) {
649 char * ret;
650 int len, pos;
651 int i;
653 len = strlen(text);
654 ret = m_malloc(len+1);
656 pos = 0;
657 for (i = 0; i < len; i++) {
658 if ((text[i] <= '~' && text[i] >= ' ') /* normal printable range */
659 || text[i] == '\n' || text[i] == '\r' || text[i] == '\t') {
660 ret[pos] = text[i];
661 pos++;
664 ret[pos] = 0x0;
665 return ret;
669 /* reads the contents of filename into the buffer buf, from the current
670 * position, either to the end of the file, or the buffer being full.
671 * Returns DROPBEAR_SUCCESS or DROPBEAR_FAILURE */
672 int buf_readfile(buffer* buf, const char* filename) {
674 int fd = -1;
675 int len;
676 int maxlen;
677 int ret = DROPBEAR_FAILURE;
679 fd = open(filename, O_RDONLY);
681 if (fd < 0) {
682 goto out;
685 do {
686 maxlen = buf->size - buf->pos;
687 len = read(fd, buf_getwriteptr(buf, maxlen), maxlen);
688 if (len < 0) {
689 if (errno == EINTR || errno == EAGAIN) {
690 continue;
692 goto out;
694 buf_incrwritepos(buf, len);
695 } while (len < maxlen && len > 0);
697 ret = DROPBEAR_SUCCESS;
699 out:
700 if (fd >= 0) {
701 m_close(fd);
703 return ret;
706 /* get a line from the file into buffer in the style expected for an
707 * authkeys file.
708 * Will return DROPBEAR_SUCCESS if data is read, or DROPBEAR_FAILURE on EOF.*/
709 /* Only used for ~/.ssh/known_hosts and ~/.ssh/authorized_keys */
710 #if defined(DROPBEAR_CLIENT) || defined(ENABLE_SVR_PUBKEY_AUTH)
711 int buf_getline(buffer * line, FILE * authfile) {
713 int c = EOF;
715 TRACE(("enter buf_getline"))
717 buf_setpos(line, 0);
718 buf_setlen(line, 0);
720 while (line->pos < line->size) {
722 c = fgetc(authfile); /*getc() is weird with some uClibc systems*/
723 if (c == EOF || c == '\n' || c == '\r') {
724 goto out;
727 buf_putbyte(line, (unsigned char)c);
730 TRACE(("leave getauthline: line too long"))
731 /* We return success, but the line length will be zeroed - ie we just
732 * ignore that line */
733 buf_setlen(line, 0);
735 out:
738 /* if we didn't read anything before EOF or error, exit */
739 if (c == EOF && line->pos == 0) {
740 TRACE(("leave buf_getline: failure"))
741 return DROPBEAR_FAILURE;
742 } else {
743 TRACE(("leave buf_getline: success"))
744 buf_setpos(line, 0);
745 return DROPBEAR_SUCCESS;
749 #endif
751 /* make sure that the socket closes */
752 void m_close(int fd) {
754 int val;
755 do {
756 val = close(fd);
757 } while (val < 0 && errno == EINTR);
759 if (val < 0 && errno != EBADF) {
760 /* Linux says EIO can happen */
761 dropbear_exit("Error closing fd %d, %s", fd, strerror(errno));
765 void * m_malloc(size_t size) {
767 void* ret;
769 if (size == 0) {
770 dropbear_exit("m_malloc failed");
772 ret = calloc(1, size);
773 if (ret == NULL) {
774 dropbear_exit("m_malloc failed");
776 return ret;
780 void * m_strdup(const char * str) {
781 char* ret;
783 ret = strdup(str);
784 if (ret == NULL) {
785 dropbear_exit("m_strdup failed");
787 return ret;
790 void __m_free(void* ptr) {
791 if (ptr != NULL) {
792 free(ptr);
796 void * m_realloc(void* ptr, size_t size) {
798 void *ret;
800 if (size == 0) {
801 dropbear_exit("m_realloc failed");
803 ret = realloc(ptr, size);
804 if (ret == NULL) {
805 dropbear_exit("m_realloc failed");
807 return ret;
810 /* Clear the data, based on the method in David Wheeler's
811 * "Secure Programming for Linux and Unix HOWTO" */
812 /* Beware of calling this from within dbutil.c - things might get
813 * optimised away */
814 void m_burn(void *data, unsigned int len) {
815 volatile char *p = data;
817 if (data == NULL)
818 return;
819 while (len--) {
820 *p++ = 0x66;
825 void setnonblocking(int fd) {
827 TRACE(("setnonblocking: %d", fd))
829 if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) {
830 if (errno == ENODEV) {
831 /* Some devices (like /dev/null redirected in)
832 * can't be set to non-blocking */
833 TRACE(("ignoring ENODEV for setnonblocking"))
834 } else {
835 dropbear_exit("Couldn't set nonblocking");
838 TRACE(("leave setnonblocking"))
841 void disallow_core() {
842 struct rlimit lim;
843 lim.rlim_cur = lim.rlim_max = 0;
844 setrlimit(RLIMIT_CORE, &lim);
847 /* Returns DROPBEAR_SUCCESS or DROPBEAR_FAILURE, with the result in *val */
848 int m_str_to_uint(const char* str, unsigned int *val) {
849 errno = 0;
850 *val = strtoul(str, NULL, 10);
851 /* The c99 spec doesn't actually seem to define EINVAL, but most platforms
852 * I've looked at mention it in their manpage */
853 if ((*val == 0 && errno == EINVAL)
854 || (*val == ULONG_MAX && errno == ERANGE)) {
855 return DROPBEAR_FAILURE;
856 } else {
857 return DROPBEAR_SUCCESS;