Allow IPv6 address entry in tools>ping - Loosens valid character check
[tomato/davidwu.git] / release / src / router / dropbear / dbutil.c
blob9a6d846a22d50b19bc3344649849a6cc355e97c5
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, ...) {
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 for either ipv4 or ipv6 */
165 #ifdef IPTOS_LOWDELAY
166 val = IPTOS_LOWDELAY;
167 #if defined(IPPROTO_IPV6) && defined(IPV6_TCLASS)
168 setsockopt(sock, IPPROTO_IPV6, IPV6_TCLASS, (void*)&val, sizeof(val));
169 #endif
170 setsockopt(sock, IPPROTO_IP, IP_TOS, (void*)&val, sizeof(val));
171 #endif
173 #ifdef SO_PRIORITY
174 /* linux specific, sets QoS class.
175 * 6 looks to be optimal for interactive traffic (see tc-prio(8) ). */
176 val = 6;
177 setsockopt(sock, SOL_SOCKET, SO_PRIORITY, (void*) &val, sizeof(val));
178 #endif
182 /* Listen on address:port.
183 * Special cases are address of "" listening on everything,
184 * and address of NULL listening on localhost only.
185 * Returns the number of sockets bound on success, or -1 on failure. On
186 * failure, if errstring wasn't NULL, it'll be a newly malloced error
187 * string.*/
188 int dropbear_listen(const char* address, const char* port,
189 int *socks, unsigned int sockcount, char **errstring, int *maxfd) {
191 struct addrinfo hints, *res = NULL, *res0 = NULL;
192 int err;
193 unsigned int nsock;
194 struct linger linger;
195 int val;
196 int sock;
198 TRACE(("enter dropbear_listen"))
200 memset(&hints, 0, sizeof(hints));
201 hints.ai_family = AF_UNSPEC; /* TODO: let them flag v4 only etc */
202 hints.ai_socktype = SOCK_STREAM;
204 /* for calling getaddrinfo:
205 address == NULL and !AI_PASSIVE: local loopback
206 address == NULL and AI_PASSIVE: all interfaces
207 address != NULL: whatever the address says */
208 if (!address) {
209 TRACE(("dropbear_listen: local loopback"))
210 } else {
211 if (address[0] == '\0') {
212 TRACE(("dropbear_listen: all interfaces"))
213 address = NULL;
215 hints.ai_flags = AI_PASSIVE;
217 err = getaddrinfo(address, port, &hints, &res0);
219 if (err) {
220 if (errstring != NULL && *errstring == NULL) {
221 int len;
222 len = 20 + strlen(gai_strerror(err));
223 *errstring = (char*)m_malloc(len);
224 snprintf(*errstring, len, "Error resolving: %s", gai_strerror(err));
226 if (res0) {
227 freeaddrinfo(res0);
228 res0 = NULL;
230 TRACE(("leave dropbear_listen: failed resolving"))
231 return -1;
235 nsock = 0;
236 for (res = res0; res != NULL && nsock < sockcount;
237 res = res->ai_next) {
239 /* Get a socket */
240 socks[nsock] = socket(res->ai_family, res->ai_socktype,
241 res->ai_protocol);
243 sock = socks[nsock]; /* For clarity */
245 if (sock < 0) {
246 err = errno;
247 TRACE(("socket() failed"))
248 continue;
251 /* Various useful socket options */
252 val = 1;
253 /* set to reuse, quick timeout */
254 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*) &val, sizeof(val));
255 linger.l_onoff = 1;
256 linger.l_linger = 5;
257 setsockopt(sock, SOL_SOCKET, SO_LINGER, (void*)&linger, sizeof(linger));
259 #if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
260 if (res->ai_family == AF_INET6) {
261 int on = 1;
262 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY,
263 &on, sizeof(on)) == -1) {
264 dropbear_log(LOG_WARNING, "Couldn't set IPV6_V6ONLY");
267 #endif
269 set_sock_priority(sock);
271 if (bind(sock, res->ai_addr, res->ai_addrlen) < 0) {
272 err = errno;
273 close(sock);
274 TRACE(("bind(%s) failed", port))
275 continue;
278 if (listen(sock, 20) < 0) {
279 err = errno;
280 close(sock);
281 TRACE(("listen() failed"))
282 continue;
285 *maxfd = MAX(*maxfd, sock);
287 nsock++;
290 if (res0) {
291 freeaddrinfo(res0);
292 res0 = NULL;
295 if (nsock == 0) {
296 if (errstring != NULL && *errstring == NULL) {
297 int len;
298 len = 20 + strlen(strerror(err));
299 *errstring = (char*)m_malloc(len);
300 snprintf(*errstring, len, "Error listening: %s", strerror(err));
302 TRACE(("leave dropbear_listen: failure, %s", strerror(err)))
303 return -1;
306 TRACE(("leave dropbear_listen: success, %d socks bound", nsock))
307 return nsock;
310 /* Connect to a given unix socket. The socket is blocking */
311 #ifdef ENABLE_CONNECT_UNIX
312 int connect_unix(const char* path) {
313 struct sockaddr_un addr;
314 int fd = -1;
316 memset((void*)&addr, 0x0, sizeof(addr));
317 addr.sun_family = AF_UNIX;
318 strlcpy(addr.sun_path, path, sizeof(addr.sun_path));
319 fd = socket(PF_UNIX, SOCK_STREAM, 0);
320 if (fd < 0) {
321 TRACE(("Failed to open unix socket"))
322 return -1;
324 if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
325 TRACE(("Failed to connect to '%s' socket", path))
326 m_close(fd);
327 return -1;
329 return fd;
331 #endif
333 /* Connect via TCP to a host. Connection will try ipv4 or ipv6, will
334 * return immediately if nonblocking is set. On failure, if errstring
335 * wasn't null, it will be a newly malloced error message */
337 /* TODO: maxfd */
338 int connect_remote(const char* remotehost, const char* remoteport,
339 int nonblocking, char ** errstring) {
341 struct addrinfo *res0 = NULL, *res = NULL, hints;
342 int sock;
343 int err;
345 TRACE(("enter connect_remote"))
347 if (errstring != NULL) {
348 *errstring = NULL;
351 memset(&hints, 0, sizeof(hints));
352 hints.ai_socktype = SOCK_STREAM;
353 hints.ai_family = PF_UNSPEC;
355 err = getaddrinfo(remotehost, remoteport, &hints, &res0);
356 if (err) {
357 if (errstring != NULL && *errstring == NULL) {
358 int len;
359 len = 100 + strlen(gai_strerror(err));
360 *errstring = (char*)m_malloc(len);
361 snprintf(*errstring, len, "Error resolving '%s' port '%s'. %s",
362 remotehost, remoteport, gai_strerror(err));
364 TRACE(("Error resolving: %s", gai_strerror(err)))
365 return -1;
368 sock = -1;
369 err = EADDRNOTAVAIL;
370 for (res = res0; res; res = res->ai_next) {
372 sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
373 if (sock < 0) {
374 err = errno;
375 continue;
378 if (nonblocking) {
379 setnonblocking(sock);
382 if (connect(sock, res->ai_addr, res->ai_addrlen) < 0) {
383 if (errno == EINPROGRESS && nonblocking) {
384 TRACE(("Connect in progress"))
385 break;
386 } else {
387 err = errno;
388 close(sock);
389 sock = -1;
390 continue;
394 break; /* Success */
397 if (sock < 0 && !(errno == EINPROGRESS && nonblocking)) {
398 /* Failed */
399 if (errstring != NULL && *errstring == NULL) {
400 int len;
401 len = 20 + strlen(strerror(err));
402 *errstring = (char*)m_malloc(len);
403 snprintf(*errstring, len, "Error connecting: %s", strerror(err));
405 TRACE(("Error connecting: %s", strerror(err)))
406 } else {
407 /* Success */
408 set_sock_priority(sock);
411 freeaddrinfo(res0);
412 if (sock > 0 && errstring != NULL && *errstring != NULL) {
413 m_free(*errstring);
416 TRACE(("leave connect_remote: sock %d\n", sock))
417 return sock;
420 /* Sets up a pipe for a, returning three non-blocking file descriptors
421 * and the pid. exec_fn is the function that will actually execute the child process,
422 * it will be run after the child has fork()ed, and is passed exec_data.
423 * If ret_errfd == NULL then stderr will not be captured.
424 * ret_pid can be passed as NULL to discard the pid. */
425 int spawn_command(void(*exec_fn)(void *user_data), void *exec_data,
426 int *ret_writefd, int *ret_readfd, int *ret_errfd, pid_t *ret_pid) {
427 int infds[2];
428 int outfds[2];
429 int errfds[2];
430 pid_t pid;
432 const int FDIN = 0;
433 const int FDOUT = 1;
435 /* redirect stdin/stdout/stderr */
436 if (pipe(infds) != 0) {
437 return DROPBEAR_FAILURE;
439 if (pipe(outfds) != 0) {
440 return DROPBEAR_FAILURE;
442 if (ret_errfd && pipe(errfds) != 0) {
443 return DROPBEAR_FAILURE;
446 #ifdef __uClinux__
447 pid = vfork();
448 #else
449 pid = fork();
450 #endif
452 if (pid < 0) {
453 return DROPBEAR_FAILURE;
456 if (!pid) {
457 /* child */
459 TRACE(("back to normal sigchld"))
460 /* Revert to normal sigchld handling */
461 if (signal(SIGCHLD, SIG_DFL) == SIG_ERR) {
462 dropbear_exit("signal() error");
465 /* redirect stdin/stdout */
467 if ((dup2(infds[FDIN], STDIN_FILENO) < 0) ||
468 (dup2(outfds[FDOUT], STDOUT_FILENO) < 0) ||
469 (ret_errfd && dup2(errfds[FDOUT], STDERR_FILENO) < 0)) {
470 TRACE(("leave noptycommand: error redirecting FDs"))
471 dropbear_exit("Child dup2() failure");
474 close(infds[FDOUT]);
475 close(infds[FDIN]);
476 close(outfds[FDIN]);
477 close(outfds[FDOUT]);
478 if (ret_errfd)
480 close(errfds[FDIN]);
481 close(errfds[FDOUT]);
484 exec_fn(exec_data);
485 /* not reached */
486 return DROPBEAR_FAILURE;
487 } else {
488 /* parent */
489 close(infds[FDIN]);
490 close(outfds[FDOUT]);
492 setnonblocking(outfds[FDIN]);
493 setnonblocking(infds[FDOUT]);
495 if (ret_errfd) {
496 close(errfds[FDOUT]);
497 setnonblocking(errfds[FDIN]);
500 if (ret_pid) {
501 *ret_pid = pid;
504 *ret_writefd = infds[FDOUT];
505 *ret_readfd = outfds[FDIN];
506 if (ret_errfd) {
507 *ret_errfd = errfds[FDIN];
509 return DROPBEAR_SUCCESS;
513 /* Runs a command with "sh -c". Will close FDs (except stdin/stdout/stderr) and
514 * re-enabled SIGPIPE. If cmd is NULL, will run a login shell.
516 void run_shell_command(const char* cmd, unsigned int maxfd, char* usershell) {
517 char * argv[4];
518 char * baseshell = NULL;
519 unsigned int i;
521 baseshell = basename(usershell);
523 if (cmd != NULL) {
524 argv[0] = baseshell;
525 } else {
526 /* a login shell should be "-bash" for "/bin/bash" etc */
527 int len = strlen(baseshell) + 2; /* 2 for "-" */
528 argv[0] = (char*)m_malloc(len);
529 snprintf(argv[0], len, "-%s", baseshell);
532 if (cmd != NULL) {
533 argv[1] = "-c";
534 argv[2] = (char*)cmd;
535 argv[3] = NULL;
536 } else {
537 /* construct a shell of the form "-bash" etc */
538 argv[1] = NULL;
541 /* Re-enable SIGPIPE for the executed process */
542 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR) {
543 dropbear_exit("signal() error");
546 /* close file descriptors except stdin/stdout/stderr
547 * Need to be sure FDs are closed here to avoid reading files as root */
548 for (i = 3; i <= maxfd; i++) {
549 m_close(i);
552 execv(usershell, argv);
555 void get_socket_address(int fd, char **local_host, char **local_port,
556 char **remote_host, char **remote_port, int host_lookup)
558 struct sockaddr_storage addr;
559 socklen_t addrlen;
561 if (local_host || local_port) {
562 addrlen = sizeof(addr);
563 if (getsockname(fd, (struct sockaddr*)&addr, &addrlen) < 0) {
564 dropbear_exit("Failed socket address: %s", strerror(errno));
566 getaddrstring(&addr, local_host, local_port, host_lookup);
568 if (remote_host || remote_port) {
569 addrlen = sizeof(addr);
570 if (getpeername(fd, (struct sockaddr*)&addr, &addrlen) < 0) {
571 dropbear_exit("Failed socket address: %s", strerror(errno));
573 getaddrstring(&addr, remote_host, remote_port, host_lookup);
577 /* Return a string representation of the socket address passed. The return
578 * value is allocated with malloc() */
579 void getaddrstring(struct sockaddr_storage* addr,
580 char **ret_host, char **ret_port,
581 int host_lookup) {
583 char host[NI_MAXHOST+1], serv[NI_MAXSERV+1];
584 unsigned int len;
585 int ret;
587 int flags = NI_NUMERICSERV | NI_NUMERICHOST;
589 #ifndef DO_HOST_LOOKUP
590 host_lookup = 0;
591 #endif
593 if (host_lookup) {
594 flags = NI_NUMERICSERV;
597 len = sizeof(struct sockaddr_storage);
598 /* Some platforms such as Solaris 8 require that len is the length
599 * of the specific structure. Some older linux systems (glibc 2.1.3
600 * such as debian potato) have sockaddr_storage.__ss_family instead
601 * but we'll ignore them */
602 #ifdef HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY
603 if (addr->ss_family == AF_INET) {
604 len = sizeof(struct sockaddr_in);
606 #ifdef AF_INET6
607 if (addr->ss_family == AF_INET6) {
608 len = sizeof(struct sockaddr_in6);
610 #endif
611 #endif
613 ret = getnameinfo((struct sockaddr*)addr, len, host, sizeof(host)-1,
614 serv, sizeof(serv)-1, flags);
616 if (ret != 0) {
617 if (host_lookup) {
618 /* On some systems (Darwin does it) we get EINTR from getnameinfo
619 * somehow. Eew. So we'll just return the IP, since that doesn't seem
620 * to exhibit that behaviour. */
621 getaddrstring(addr, ret_host, ret_port, 0);
622 return;
623 } else {
624 /* if we can't do a numeric lookup, something's gone terribly wrong */
625 dropbear_exit("Failed lookup: %s", gai_strerror(ret));
629 if (ret_host) {
630 *ret_host = m_strdup(host);
632 if (ret_port) {
633 *ret_port = m_strdup(serv);
637 #ifdef DEBUG_TRACE
638 void printhex(const char * label, const unsigned char * buf, int len) {
640 int i;
642 fprintf(stderr, "%s\n", label);
643 for (i = 0; i < len; i++) {
644 fprintf(stderr, "%02x", buf[i]);
645 if (i % 16 == 15) {
646 fprintf(stderr, "\n");
648 else if (i % 2 == 1) {
649 fprintf(stderr, " ");
652 fprintf(stderr, "\n");
654 #endif
656 /* Strip all control characters from text (a null-terminated string), except
657 * for '\n', '\r' and '\t'.
658 * The result returned is a newly allocated string, this must be free()d after
659 * use */
660 char * stripcontrol(const char * text) {
662 char * ret;
663 int len, pos;
664 int i;
666 len = strlen(text);
667 ret = m_malloc(len+1);
669 pos = 0;
670 for (i = 0; i < len; i++) {
671 if ((text[i] <= '~' && text[i] >= ' ') /* normal printable range */
672 || text[i] == '\n' || text[i] == '\r' || text[i] == '\t') {
673 ret[pos] = text[i];
674 pos++;
677 ret[pos] = 0x0;
678 return ret;
682 /* reads the contents of filename into the buffer buf, from the current
683 * position, either to the end of the file, or the buffer being full.
684 * Returns DROPBEAR_SUCCESS or DROPBEAR_FAILURE */
685 int buf_readfile(buffer* buf, const char* filename) {
687 int fd = -1;
688 int len;
689 int maxlen;
690 int ret = DROPBEAR_FAILURE;
692 fd = open(filename, O_RDONLY);
694 if (fd < 0) {
695 goto out;
698 do {
699 maxlen = buf->size - buf->pos;
700 len = read(fd, buf_getwriteptr(buf, maxlen), maxlen);
701 if (len < 0) {
702 if (errno == EINTR || errno == EAGAIN) {
703 continue;
705 goto out;
707 buf_incrwritepos(buf, len);
708 } while (len < maxlen && len > 0);
710 ret = DROPBEAR_SUCCESS;
712 out:
713 if (fd >= 0) {
714 m_close(fd);
716 return ret;
719 /* get a line from the file into buffer in the style expected for an
720 * authkeys file.
721 * Will return DROPBEAR_SUCCESS if data is read, or DROPBEAR_FAILURE on EOF.*/
722 /* Only used for ~/.ssh/known_hosts and ~/.ssh/authorized_keys */
723 #if defined(DROPBEAR_CLIENT) || defined(ENABLE_SVR_PUBKEY_AUTH)
724 int buf_getline(buffer * line, FILE * authfile) {
726 int c = EOF;
728 TRACE(("enter buf_getline"))
730 buf_setpos(line, 0);
731 buf_setlen(line, 0);
733 while (line->pos < line->size) {
735 c = fgetc(authfile); /*getc() is weird with some uClibc systems*/
736 if (c == EOF || c == '\n' || c == '\r') {
737 goto out;
740 buf_putbyte(line, (unsigned char)c);
743 TRACE(("leave getauthline: line too long"))
744 /* We return success, but the line length will be zeroed - ie we just
745 * ignore that line */
746 buf_setlen(line, 0);
748 out:
751 /* if we didn't read anything before EOF or error, exit */
752 if (c == EOF && line->pos == 0) {
753 TRACE(("leave buf_getline: failure"))
754 return DROPBEAR_FAILURE;
755 } else {
756 TRACE(("leave buf_getline: success"))
757 buf_setpos(line, 0);
758 return DROPBEAR_SUCCESS;
762 #endif
764 /* make sure that the socket closes */
765 void m_close(int fd) {
767 int val;
768 do {
769 val = close(fd);
770 } while (val < 0 && errno == EINTR);
772 if (val < 0 && errno != EBADF) {
773 /* Linux says EIO can happen */
774 dropbear_exit("Error closing fd %d, %s", fd, strerror(errno));
778 void * m_malloc(size_t size) {
780 void* ret;
782 if (size == 0) {
783 dropbear_exit("m_malloc failed");
785 ret = calloc(1, size);
786 if (ret == NULL) {
787 dropbear_exit("m_malloc failed");
789 return ret;
793 void * m_strdup(const char * str) {
794 char* ret;
796 ret = strdup(str);
797 if (ret == NULL) {
798 dropbear_exit("m_strdup failed");
800 return ret;
803 void * m_realloc(void* ptr, size_t size) {
805 void *ret;
807 if (size == 0) {
808 dropbear_exit("m_realloc failed");
810 ret = realloc(ptr, size);
811 if (ret == NULL) {
812 dropbear_exit("m_realloc failed");
814 return ret;
817 /* Clear the data, based on the method in David Wheeler's
818 * "Secure Programming for Linux and Unix HOWTO" */
819 /* Beware of calling this from within dbutil.c - things might get
820 * optimised away */
821 void m_burn(void *data, unsigned int len) {
822 volatile char *p = data;
824 if (data == NULL)
825 return;
826 while (len--) {
827 *p++ = 0x0;
832 void setnonblocking(int fd) {
834 TRACE(("setnonblocking: %d", fd))
836 if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) {
837 if (errno == ENODEV) {
838 /* Some devices (like /dev/null redirected in)
839 * can't be set to non-blocking */
840 TRACE(("ignoring ENODEV for setnonblocking"))
841 } else {
842 dropbear_exit("Couldn't set nonblocking");
845 TRACE(("leave setnonblocking"))
848 void disallow_core() {
849 struct rlimit lim;
850 lim.rlim_cur = lim.rlim_max = 0;
851 setrlimit(RLIMIT_CORE, &lim);
854 /* Returns DROPBEAR_SUCCESS or DROPBEAR_FAILURE, with the result in *val */
855 int m_str_to_uint(const char* str, unsigned int *val) {
856 errno = 0;
857 *val = strtoul(str, NULL, 10);
858 /* The c99 spec doesn't actually seem to define EINVAL, but most platforms
859 * I've looked at mention it in their manpage */
860 if ((*val == 0 && errno == EINVAL)
861 || (*val == ULONG_MAX && errno == ERANGE)) {
862 return DROPBEAR_FAILURE;
863 } else {
864 return DROPBEAR_SUCCESS;