blob: 89d751b1b0af84aaac9e1dfed083a6630a78b85a [file] [log] [blame]
Ratan Gupta309ac442016-12-13 20:40:06 +05301#include "slp_server.hpp"
2
Patrick Venture537ff142018-11-01 16:37:09 -07003#include "sock_channel.hpp"
Ratan Gupta309ac442016-12-13 20:40:06 +05304
5#include <stdio.h>
6#include <stdlib.h>
7#include <string.h>
8#include <unistd.h>
9
Patrick Venture537ff142018-11-01 16:37:09 -070010#include <memory>
Ratan Gupta309ac442016-12-13 20:40:06 +053011
12/** General udp server which waits for the POLLIN event
13 on the port and calls the call back once it gets the event.
14 usage would be create the server with the port and the call back
15 and call the run method.
16 */
17int slp::udp::Server::run()
18{
Patrick Venture537ff142018-11-01 16:37:09 -070019 struct sockaddr_in6 serverAddr
20 {
21 };
Ratan Gupta309ac442016-12-13 20:40:06 +053022
23 sd_event* event = nullptr;
24
Patrick Venture537ff142018-11-01 16:37:09 -070025 slp::deleted_unique_ptr<sd_event> eventPtr(event, [](sd_event* event) {
Ratan Gupta309ac442016-12-13 20:40:06 +053026 if (!event)
27 {
28 event = sd_event_unref(event);
29 }
30 });
31
32 int fd = -1, r;
33 sigset_t ss;
34
35 r = sd_event_default(&event);
36 if (r < 0)
37 {
38 goto finish;
39 }
40
41 eventPtr.reset(event);
42 event = nullptr;
43
44 if (sigemptyset(&ss) < 0 || sigaddset(&ss, SIGTERM) < 0 ||
45 sigaddset(&ss, SIGINT) < 0)
46 {
47 r = -errno;
48 goto finish;
49 }
50 /* Block SIGTERM first, so that the event loop can handle it */
51 if (sigprocmask(SIG_BLOCK, &ss, NULL) < 0)
52 {
53 r = -errno;
54 goto finish;
55 }
56
57 /* Let's make use of the default handler and "floating"
58 reference features of sd_event_add_signal() */
59
60 r = sd_event_add_signal(eventPtr.get(), NULL, SIGTERM, NULL, NULL);
61 if (r < 0)
62 {
63 goto finish;
64 }
65
66 r = sd_event_add_signal(eventPtr.get(), NULL, SIGINT, NULL, NULL);
67 if (r < 0)
68 {
69 goto finish;
70 }
71
Ratan Gupta70b85272017-01-05 20:52:18 +053072 fd = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0);
Ratan Gupta309ac442016-12-13 20:40:06 +053073 if (fd < 0)
74 {
75 r = -errno;
76 goto finish;
77 }
78
Ratan Gupta70b85272017-01-05 20:52:18 +053079 serverAddr.sin6_family = AF_INET6;
80 serverAddr.sin6_port = htons(this->port);
Ratan Gupta309ac442016-12-13 20:40:06 +053081
Ratan Gupta70b85272017-01-05 20:52:18 +053082 if (bind(fd, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0)
Ratan Gupta309ac442016-12-13 20:40:06 +053083 {
84 r = -errno;
85 goto finish;
86 }
87
88 r = sd_event_add_io(eventPtr.get(), nullptr, fd, EPOLLIN, this->callme,
89 nullptr);
90 if (r < 0)
91 {
92 goto finish;
93 }
94
95 r = sd_event_loop(eventPtr.get());
96
97finish:
98
99 if (fd >= 0)
100 {
Patrick Venture537ff142018-11-01 16:37:09 -0700101 (void)close(fd);
Ratan Gupta309ac442016-12-13 20:40:06 +0530102 }
103
104 if (r < 0)
105 {
106 fprintf(stderr, "Failure: %s\n", strerror(-r));
107 }
108
109 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
110}