Correct PPTP server firewall rules chain.
[tomato/davidwu.git] / release / src / router / dropbear / dbutil.c
blob082a5a20a63c6a63538800e0cbeef16f85376d8a
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 void set_sock_nodelay(int sock) {
181 int val;
183 /* disable nagle */
184 val = 1;
185 setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (void*)&val, sizeof(val));
188 void set_sock_priority(int sock, enum dropbear_prio prio) {
190 int iptos_val = 0, so_prio_val = 0, rc;
192 /* set the TOS bit for either ipv4 or ipv6 */
193 #ifdef IPTOS_LOWDELAY
194 if (prio == DROPBEAR_PRIO_LOWDELAY) {
195 iptos_val = IPTOS_LOWDELAY;
196 } else if (prio == DROPBEAR_PRIO_BULK) {
197 iptos_val = IPTOS_THROUGHPUT;
199 #if defined(IPPROTO_IPV6) && defined(IPV6_TCLASS)
200 rc = setsockopt(sock, IPPROTO_IPV6, IPV6_TCLASS, (void*)&iptos_val, sizeof(iptos_val));
201 if (rc < 0) {
202 TRACE(("Couldn't set IPV6_TCLASS (%s)", strerror(errno)));
204 #endif
205 rc = setsockopt(sock, IPPROTO_IP, IP_TOS, (void*)&iptos_val, sizeof(iptos_val));
206 if (rc < 0) {
207 TRACE(("Couldn't set IP_TOS (%s)", strerror(errno)));
209 #endif
211 #ifdef SO_PRIORITY
212 if (prio == DROPBEAR_PRIO_LOWDELAY) {
213 so_prio_val = TC_PRIO_INTERACTIVE;
214 } else if (prio == DROPBEAR_PRIO_BULK) {
215 so_prio_val = TC_PRIO_BULK;
217 /* linux specific, sets QoS class. see tc-prio(8) */
218 rc = setsockopt(sock, SOL_SOCKET, SO_PRIORITY, (void*) &so_prio_val, sizeof(so_prio_val));
219 if (rc < 0)
220 dropbear_log(LOG_WARNING, "Couldn't set SO_PRIORITY (%s)",
221 strerror(errno));
222 #endif
226 /* Listen on address:port.
227 * Special cases are address of "" listening on everything,
228 * and address of NULL listening on localhost only.
229 * Returns the number of sockets bound on success, or -1 on failure. On
230 * failure, if errstring wasn't NULL, it'll be a newly malloced error
231 * string.*/
232 int dropbear_listen(const char* address, const char* port,
233 int *socks, unsigned int sockcount, char **errstring, int *maxfd) {
235 struct addrinfo hints, *res = NULL, *res0 = NULL;
236 int err;
237 unsigned int nsock;
238 struct linger linger;
239 int val;
240 int sock;
242 TRACE(("enter dropbear_listen"))
244 memset(&hints, 0, sizeof(hints));
245 hints.ai_family = AF_UNSPEC; /* TODO: let them flag v4 only etc */
246 hints.ai_socktype = SOCK_STREAM;
248 /* for calling getaddrinfo:
249 address == NULL and !AI_PASSIVE: local loopback
250 address == NULL and AI_PASSIVE: all interfaces
251 address != NULL: whatever the address says */
252 if (!address) {
253 TRACE(("dropbear_listen: local loopback"))
254 } else {
255 if (address[0] == '\0') {
256 TRACE(("dropbear_listen: all interfaces"))
257 address = NULL;
259 hints.ai_flags = AI_PASSIVE;
261 err = getaddrinfo(address, port, &hints, &res0);
263 if (err) {
264 if (errstring != NULL && *errstring == NULL) {
265 int len;
266 len = 20 + strlen(gai_strerror(err));
267 *errstring = (char*)m_malloc(len);
268 snprintf(*errstring, len, "Error resolving: %s", gai_strerror(err));
270 if (res0) {
271 freeaddrinfo(res0);
272 res0 = NULL;
274 TRACE(("leave dropbear_listen: failed resolving"))
275 return -1;
279 nsock = 0;
280 for (res = res0; res != NULL && nsock < sockcount;
281 res = res->ai_next) {
283 /* Get a socket */
284 socks[nsock] = socket(res->ai_family, res->ai_socktype,
285 res->ai_protocol);
287 sock = socks[nsock]; /* For clarity */
289 if (sock < 0) {
290 err = errno;
291 TRACE(("socket() failed"))
292 continue;
295 /* Various useful socket options */
296 val = 1;
297 /* set to reuse, quick timeout */
298 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*) &val, sizeof(val));
299 linger.l_onoff = 1;
300 linger.l_linger = 5;
301 setsockopt(sock, SOL_SOCKET, SO_LINGER, (void*)&linger, sizeof(linger));
303 #if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
304 if (res->ai_family == AF_INET6) {
305 int on = 1;
306 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY,
307 &on, sizeof(on)) == -1) {
308 dropbear_log(LOG_WARNING, "Couldn't set IPV6_V6ONLY");
311 #endif
313 set_sock_nodelay(sock);
315 if (bind(sock, res->ai_addr, res->ai_addrlen) < 0) {
316 err = errno;
317 close(sock);
318 TRACE(("bind(%s) failed", port))
319 continue;
322 if (listen(sock, 20) < 0) {
323 err = errno;
324 close(sock);
325 TRACE(("listen() failed"))
326 continue;
329 *maxfd = MAX(*maxfd, sock);
331 nsock++;
334 if (res0) {
335 freeaddrinfo(res0);
336 res0 = NULL;
339 if (nsock == 0) {
340 if (errstring != NULL && *errstring == NULL) {
341 int len;
342 len = 20 + strlen(strerror(err));
343 *errstring = (char*)m_malloc(len);
344 snprintf(*errstring, len, "Error listening: %s", strerror(err));
346 TRACE(("leave dropbear_listen: failure, %s", strerror(err)))
347 return -1;
350 TRACE(("leave dropbear_listen: success, %d socks bound", nsock))
351 return nsock;
354 /* Connect to a given unix socket. The socket is blocking */
355 #ifdef ENABLE_CONNECT_UNIX
356 int connect_unix(const char* path) {
357 struct sockaddr_un addr;
358 int fd = -1;
360 memset((void*)&addr, 0x0, sizeof(addr));
361 addr.sun_family = AF_UNIX;
362 strlcpy(addr.sun_path, path, sizeof(addr.sun_path));
363 fd = socket(PF_UNIX, SOCK_STREAM, 0);
364 if (fd < 0) {
365 TRACE(("Failed to open unix socket"))
366 return -1;
368 if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
369 TRACE(("Failed to connect to '%s' socket", path))
370 m_close(fd);
371 return -1;
373 return fd;
375 #endif
377 /* Connect via TCP to a host. Connection will try ipv4 or ipv6, will
378 * return immediately if nonblocking is set. On failure, if errstring
379 * wasn't null, it will be a newly malloced error message */
381 /* TODO: maxfd */
382 int connect_remote(const char* remotehost, const char* remoteport,
383 int nonblocking, char ** errstring) {
385 struct addrinfo *res0 = NULL, *res = NULL, hints;
386 int sock;
387 int err;
389 TRACE(("enter connect_remote"))
391 if (errstring != NULL) {
392 *errstring = NULL;
395 memset(&hints, 0, sizeof(hints));
396 hints.ai_socktype = SOCK_STREAM;
397 hints.ai_family = PF_UNSPEC;
399 err = getaddrinfo(remotehost, remoteport, &hints, &res0);
400 if (err) {
401 if (errstring != NULL && *errstring == NULL) {
402 int len;
403 len = 100 + strlen(gai_strerror(err));
404 *errstring = (char*)m_malloc(len);
405 snprintf(*errstring, len, "Error resolving '%s' port '%s'. %s",
406 remotehost, remoteport, gai_strerror(err));
408 TRACE(("Error resolving: %s", gai_strerror(err)))
409 return -1;
412 sock = -1;
413 err = EADDRNOTAVAIL;
414 for (res = res0; res; res = res->ai_next) {
416 sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
417 if (sock < 0) {
418 err = errno;
419 continue;
422 if (nonblocking) {
423 setnonblocking(sock);
426 if (connect(sock, res->ai_addr, res->ai_addrlen) < 0) {
427 if (errno == EINPROGRESS && nonblocking) {
428 TRACE(("Connect in progress"))
429 break;
430 } else {
431 err = errno;
432 close(sock);
433 sock = -1;
434 continue;
438 break; /* Success */
441 if (sock < 0 && !(errno == EINPROGRESS && nonblocking)) {
442 /* Failed */
443 if (errstring != NULL && *errstring == NULL) {
444 int len;
445 len = 20 + strlen(strerror(err));
446 *errstring = (char*)m_malloc(len);
447 snprintf(*errstring, len, "Error connecting: %s", strerror(err));
449 TRACE(("Error connecting: %s", strerror(err)))
450 } else {
451 /* Success */
452 set_sock_nodelay(sock);
455 freeaddrinfo(res0);
456 if (sock > 0 && errstring != NULL && *errstring != NULL) {
457 m_free(*errstring);
460 TRACE(("leave connect_remote: sock %d\n", sock))
461 return sock;
464 /* Sets up a pipe for a, returning three non-blocking file descriptors
465 * and the pid. exec_fn is the function that will actually execute the child process,
466 * it will be run after the child has fork()ed, and is passed exec_data.
467 * If ret_errfd == NULL then stderr will not be captured.
468 * ret_pid can be passed as NULL to discard the pid. */
469 int spawn_command(void(*exec_fn)(void *user_data), void *exec_data,
470 int *ret_writefd, int *ret_readfd, int *ret_errfd, pid_t *ret_pid) {
471 int infds[2];
472 int outfds[2];
473 int errfds[2];
474 pid_t pid;
476 const int FDIN = 0;
477 const int FDOUT = 1;
479 /* redirect stdin/stdout/stderr */
480 if (pipe(infds) != 0) {
481 return DROPBEAR_FAILURE;
483 if (pipe(outfds) != 0) {
484 return DROPBEAR_FAILURE;
486 if (ret_errfd && pipe(errfds) != 0) {
487 return DROPBEAR_FAILURE;
490 #ifdef USE_VFORK
491 pid = vfork();
492 #else
493 pid = fork();
494 #endif
496 if (pid < 0) {
497 return DROPBEAR_FAILURE;
500 if (!pid) {
501 /* child */
503 TRACE(("back to normal sigchld"))
504 /* Revert to normal sigchld handling */
505 if (signal(SIGCHLD, SIG_DFL) == SIG_ERR) {
506 dropbear_exit("signal() error");
509 /* redirect stdin/stdout */
511 if ((dup2(infds[FDIN], STDIN_FILENO) < 0) ||
512 (dup2(outfds[FDOUT], STDOUT_FILENO) < 0) ||
513 (ret_errfd && dup2(errfds[FDOUT], STDERR_FILENO) < 0)) {
514 TRACE(("leave noptycommand: error redirecting FDs"))
515 dropbear_exit("Child dup2() failure");
518 close(infds[FDOUT]);
519 close(infds[FDIN]);
520 close(outfds[FDIN]);
521 close(outfds[FDOUT]);
522 if (ret_errfd)
524 close(errfds[FDIN]);
525 close(errfds[FDOUT]);
528 exec_fn(exec_data);
529 /* not reached */
530 return DROPBEAR_FAILURE;
531 } else {
532 /* parent */
533 close(infds[FDIN]);
534 close(outfds[FDOUT]);
536 setnonblocking(outfds[FDIN]);
537 setnonblocking(infds[FDOUT]);
539 if (ret_errfd) {
540 close(errfds[FDOUT]);
541 setnonblocking(errfds[FDIN]);
544 if (ret_pid) {
545 *ret_pid = pid;
548 *ret_writefd = infds[FDOUT];
549 *ret_readfd = outfds[FDIN];
550 if (ret_errfd) {
551 *ret_errfd = errfds[FDIN];
553 return DROPBEAR_SUCCESS;
557 /* Runs a command with "sh -c". Will close FDs (except stdin/stdout/stderr) and
558 * re-enabled SIGPIPE. If cmd is NULL, will run a login shell.
560 void run_shell_command(const char* cmd, unsigned int maxfd, char* usershell) {
561 char * argv[4];
562 char * baseshell = NULL;
563 unsigned int i;
565 baseshell = basename(usershell);
567 if (cmd != NULL) {
568 argv[0] = baseshell;
569 } else {
570 /* a login shell should be "-bash" for "/bin/bash" etc */
571 int len = strlen(baseshell) + 2; /* 2 for "-" */
572 argv[0] = (char*)m_malloc(len);
573 snprintf(argv[0], len, "-%s", baseshell);
576 if (cmd != NULL) {
577 argv[1] = "-c";
578 argv[2] = (char*)cmd;
579 argv[3] = NULL;
580 } else {
581 /* construct a shell of the form "-bash" etc */
582 argv[1] = NULL;
585 /* Re-enable SIGPIPE for the executed process */
586 if (signal(SIGPIPE, SIG_DFL) == SIG_ERR) {
587 dropbear_exit("signal() error");
590 /* close file descriptors except stdin/stdout/stderr
591 * Need to be sure FDs are closed here to avoid reading files as root */
592 for (i = 3; i <= maxfd; i++) {
593 m_close(i);
596 execv(usershell, argv);
599 void get_socket_address(int fd, char **local_host, char **local_port,
600 char **remote_host, char **remote_port, int host_lookup)
602 struct sockaddr_storage addr;
603 socklen_t addrlen;
605 if (local_host || local_port) {
606 addrlen = sizeof(addr);
607 if (getsockname(fd, (struct sockaddr*)&addr, &addrlen) < 0) {
608 dropbear_exit("Failed socket address: %s", strerror(errno));
610 getaddrstring(&addr, local_host, local_port, host_lookup);
612 if (remote_host || remote_port) {
613 addrlen = sizeof(addr);
614 if (getpeername(fd, (struct sockaddr*)&addr, &addrlen) < 0) {
615 dropbear_exit("Failed socket address: %s", strerror(errno));
617 getaddrstring(&addr, remote_host, remote_port, host_lookup);
621 /* Return a string representation of the socket address passed. The return
622 * value is allocated with malloc() */
623 void getaddrstring(struct sockaddr_storage* addr,
624 char **ret_host, char **ret_port,
625 int host_lookup) {
627 char host[NI_MAXHOST+1], serv[NI_MAXSERV+1];
628 unsigned int len;
629 int ret;
631 int flags = NI_NUMERICSERV | NI_NUMERICHOST;
633 #ifndef DO_HOST_LOOKUP
634 host_lookup = 0;
635 #endif
637 if (host_lookup) {
638 flags = NI_NUMERICSERV;
641 len = sizeof(struct sockaddr_storage);
642 /* Some platforms such as Solaris 8 require that len is the length
643 * of the specific structure. Some older linux systems (glibc 2.1.3
644 * such as debian potato) have sockaddr_storage.__ss_family instead
645 * but we'll ignore them */
646 #ifdef HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY
647 if (addr->ss_family == AF_INET) {
648 len = sizeof(struct sockaddr_in);
650 #ifdef AF_INET6
651 if (addr->ss_family == AF_INET6) {
652 len = sizeof(struct sockaddr_in6);
654 #endif
655 #endif
657 ret = getnameinfo((struct sockaddr*)addr, len, host, sizeof(host)-1,
658 serv, sizeof(serv)-1, flags);
660 if (ret != 0) {
661 if (host_lookup) {
662 /* On some systems (Darwin does it) we get EINTR from getnameinfo
663 * somehow. Eew. So we'll just return the IP, since that doesn't seem
664 * to exhibit that behaviour. */
665 getaddrstring(addr, ret_host, ret_port, 0);
666 return;
667 } else {
668 /* if we can't do a numeric lookup, something's gone terribly wrong */
669 dropbear_exit("Failed lookup: %s", gai_strerror(ret));
673 if (ret_host) {
674 *ret_host = m_strdup(host);
676 if (ret_port) {
677 *ret_port = m_strdup(serv);
681 #ifdef DEBUG_TRACE
682 void printhex(const char * label, const unsigned char * buf, int len) {
684 int i;
686 fprintf(stderr, "%s\n", label);
687 for (i = 0; i < len; i++) {
688 fprintf(stderr, "%02x", buf[i]);
689 if (i % 16 == 15) {
690 fprintf(stderr, "\n");
692 else if (i % 2 == 1) {
693 fprintf(stderr, " ");
696 fprintf(stderr, "\n");
699 void printmpint(const char *label, mp_int *mp) {
700 buffer *buf = buf_new(1000);
701 buf_putmpint(buf, mp);
702 printhex(label, buf->data, buf->len);
703 buf_free(buf);
706 #endif
708 /* Strip all control characters from text (a null-terminated string), except
709 * for '\n', '\r' and '\t'.
710 * The result returned is a newly allocated string, this must be free()d after
711 * use */
712 char * stripcontrol(const char * text) {
714 char * ret;
715 int len, pos;
716 int i;
718 len = strlen(text);
719 ret = m_malloc(len+1);
721 pos = 0;
722 for (i = 0; i < len; i++) {
723 if ((text[i] <= '~' && text[i] >= ' ') /* normal printable range */
724 || text[i] == '\n' || text[i] == '\r' || text[i] == '\t') {
725 ret[pos] = text[i];
726 pos++;
729 ret[pos] = 0x0;
730 return ret;
734 /* reads the contents of filename into the buffer buf, from the current
735 * position, either to the end of the file, or the buffer being full.
736 * Returns DROPBEAR_SUCCESS or DROPBEAR_FAILURE */
737 int buf_readfile(buffer* buf, const char* filename) {
739 int fd = -1;
740 int len;
741 int maxlen;
742 int ret = DROPBEAR_FAILURE;
744 fd = open(filename, O_RDONLY);
746 if (fd < 0) {
747 goto out;
750 do {
751 maxlen = buf->size - buf->pos;
752 len = read(fd, buf_getwriteptr(buf, maxlen), maxlen);
753 if (len < 0) {
754 if (errno == EINTR || errno == EAGAIN) {
755 continue;
757 goto out;
759 buf_incrwritepos(buf, len);
760 } while (len < maxlen && len > 0);
762 ret = DROPBEAR_SUCCESS;
764 out:
765 if (fd >= 0) {
766 m_close(fd);
768 return ret;
771 /* get a line from the file into buffer in the style expected for an
772 * authkeys file.
773 * Will return DROPBEAR_SUCCESS if data is read, or DROPBEAR_FAILURE on EOF.*/
774 /* Only used for ~/.ssh/known_hosts and ~/.ssh/authorized_keys */
775 #if defined(DROPBEAR_CLIENT) || defined(ENABLE_SVR_PUBKEY_AUTH)
776 int buf_getline(buffer * line, FILE * authfile) {
778 int c = EOF;
780 buf_setpos(line, 0);
781 buf_setlen(line, 0);
783 while (line->pos < line->size) {
785 c = fgetc(authfile); /*getc() is weird with some uClibc systems*/
786 if (c == EOF || c == '\n' || c == '\r') {
787 goto out;
790 buf_putbyte(line, (unsigned char)c);
793 TRACE(("leave getauthline: line too long"))
794 /* We return success, but the line length will be zeroed - ie we just
795 * ignore that line */
796 buf_setlen(line, 0);
798 out:
801 /* if we didn't read anything before EOF or error, exit */
802 if (c == EOF && line->pos == 0) {
803 return DROPBEAR_FAILURE;
804 } else {
805 buf_setpos(line, 0);
806 return DROPBEAR_SUCCESS;
810 #endif
812 /* make sure that the socket closes */
813 void m_close(int fd) {
815 int val;
816 do {
817 val = close(fd);
818 } while (val < 0 && errno == EINTR);
820 if (val < 0 && errno != EBADF) {
821 /* Linux says EIO can happen */
822 dropbear_exit("Error closing fd %d, %s", fd, strerror(errno));
826 void * m_malloc(size_t size) {
828 void* ret;
830 if (size == 0) {
831 dropbear_exit("m_malloc failed");
833 ret = calloc(1, size);
834 if (ret == NULL) {
835 dropbear_exit("m_malloc failed");
837 return ret;
841 void * m_strdup(const char * str) {
842 char* ret;
844 ret = strdup(str);
845 if (ret == NULL) {
846 dropbear_exit("m_strdup failed");
848 return ret;
851 void * m_realloc(void* ptr, size_t size) {
853 void *ret;
855 if (size == 0) {
856 dropbear_exit("m_realloc failed");
858 ret = realloc(ptr, size);
859 if (ret == NULL) {
860 dropbear_exit("m_realloc failed");
862 return ret;
865 /* Clear the data, based on the method in David Wheeler's
866 * "Secure Programming for Linux and Unix HOWTO" */
867 /* Beware of calling this from within dbutil.c - things might get
868 * optimised away */
869 void m_burn(void *data, unsigned int len) {
870 volatile char *p = data;
872 if (data == NULL)
873 return;
874 while (len--) {
875 *p++ = 0x0;
880 void setnonblocking(int fd) {
882 TRACE(("setnonblocking: %d", fd))
884 if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) {
885 if (errno == ENODEV) {
886 /* Some devices (like /dev/null redirected in)
887 * can't be set to non-blocking */
888 TRACE(("ignoring ENODEV for setnonblocking"))
889 } else {
890 dropbear_exit("Couldn't set nonblocking");
893 TRACE(("leave setnonblocking"))
896 void disallow_core() {
897 struct rlimit lim;
898 lim.rlim_cur = lim.rlim_max = 0;
899 setrlimit(RLIMIT_CORE, &lim);
902 /* Returns DROPBEAR_SUCCESS or DROPBEAR_FAILURE, with the result in *val */
903 int m_str_to_uint(const char* str, unsigned int *val) {
904 unsigned long l;
905 errno = 0;
906 l = strtoul(str, NULL, 10);
907 /* The c99 spec doesn't actually seem to define EINVAL, but most platforms
908 * I've looked at mention it in their manpage */
909 if ((l == 0 && errno == EINVAL)
910 || (l == ULONG_MAX && errno == ERANGE)
911 || (l > UINT_MAX)) {
912 return DROPBEAR_FAILURE;
913 } else {
914 *val = l;
915 return DROPBEAR_SUCCESS;
919 int constant_time_memcmp(const void* a, const void *b, size_t n)
921 const char *xa = a, *xb = b;
922 uint8_t c = 0;
923 size_t i;
924 for (i = 0; i < n; i++)
926 c |= (xa[i] ^ xb[i]);
928 return c;