xref: /openbsd-src/usr.sbin/ntpd/ntp_msg.c (revision a28daedfc357b214be5c701aa8ba8adb29a7f1c2)
1 /*	$OpenBSD: ntp_msg.c,v 1.18 2007/10/19 15:53:57 otto Exp $ */
2 
3 /*
4  * Copyright (c) 2003, 2004 Henning Brauer <henning@openbsd.org>
5  * Copyright (c) 2004 Alexander Guy <alexander.guy@andern.org>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
16  * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
17  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 #include <sys/param.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <errno.h>
25 
26 #include "ntpd.h"
27 
28 int
29 ntp_getmsg(struct sockaddr *sa, char *p, ssize_t len, struct ntp_msg *msg)
30 {
31 	if (len != NTP_MSGSIZE_NOAUTH && len != NTP_MSGSIZE) {
32 		log_debug("malformed packet received from %s",
33 		    log_sockaddr(sa));
34 		return (-1);
35 	}
36 
37 	memcpy(msg, p, sizeof(*msg));
38 
39 	return (0);
40 }
41 
42 int
43 ntp_sendmsg(int fd, struct sockaddr *sa, struct ntp_msg *msg, ssize_t len,
44     int auth)
45 {
46 	socklen_t	sa_len;
47 	ssize_t		n;
48 
49 	if (sa != NULL)
50 		sa_len = SA_LEN(sa);
51 	else
52 		sa_len = 0;
53 
54 	n = sendto(fd, msg, sizeof(*msg), 0, sa, sa_len);
55 	if (n == -1) {
56 		if (errno == ENOBUFS || errno == EHOSTUNREACH ||
57 		    errno == ENETDOWN || errno == EHOSTDOWN) {
58 			/* logging is futile */
59 			return (-1);
60 		}
61 		log_warn("sendto");
62 		return (-1);
63 	}
64 
65 	if (n != sizeof(*msg)) {
66 		log_warnx("ntp_sendmsg: only %ld of %ld bytes sent", n,
67 		    sizeof(*msg));
68 		return (-1);
69 	}
70 
71 	return (0);
72 }
73