summaryrefslogtreecommitdiff
path: root/lib/init/init_socket_send_status.c
blob: ecad94c2a160b84f1265d15617406ff111fd97d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/* SPDX-License-Identifier: ISC */
#include <sys/types.h>
#include <sys/socket.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include "initsock.h"


static int send_retry(int fd, const void *dst, size_t addrlen,
		      const void *buffer, size_t size)
{
	ssize_t ret;
retry:
	ret = sendto(fd, buffer, size, MSG_NOSIGNAL, dst, addrlen);
	if (ret < 0 && errno == EINTR)
		goto retry;

	if (ret < 0 || (size_t)ret < size)
		return -1;

	return 0;
}

static int send_string(int fd, const void *dst, size_t addrlen,
		       const char *str)
{
	size_t len = strlen(str);
	uint8_t raw_len[2];

	raw_len[0] = (len >> 8) & 0xFF;
	raw_len[1] = len & 0xFF;

	if (send_retry(fd, dst, addrlen, raw_len, 2))
		return -1;

	return len > 0 ? send_retry(fd, dst, addrlen, str, len) : 0;
}

int init_socket_send_status(int fd, const void *dest_addr, size_t addrlen,
			    E_SERVICE_STATE state, service_t *svc)
{
	uint8_t info[2];

	if (svc == NULL || state == ESS_NONE) {
		info[0] = ESS_NONE;
		info[1] = 0;
	} else {
		info[0] = state;
		info[1] = svc->status & 0xFF;
	}

	if (send_retry(fd, dest_addr, addrlen, info, 2))
		return -1;

	if (svc != NULL && state != ESS_NONE) {
		if (send_string(fd, dest_addr, addrlen, svc->fname))
			return -1;
		if (send_string(fd, dest_addr, addrlen, svc->name))
			return -1;
	}
	return 0;
}