blob: 028569a8904a33ae9b912b2a0fece00fe4abf4c8 [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 Williams7f70ddf2024-12-18 11:23:06 -050019 struct sockaddr_in6 serverAddr{};
Ratan Gupta309ac442016-12-13 20:40:06 +053020
21 sd_event* event = nullptr;
22
Patrick Venture537ff142018-11-01 16:37:09 -070023 slp::deleted_unique_ptr<sd_event> eventPtr(event, [](sd_event* event) {
Ratan Gupta309ac442016-12-13 20:40:06 +053024 if (!event)
25 {
26 event = sd_event_unref(event);
27 }
28 });
29
30 int fd = -1, r;
31 sigset_t ss;
32
33 r = sd_event_default(&event);
34 if (r < 0)
35 {
36 goto finish;
37 }
38
39 eventPtr.reset(event);
40 event = nullptr;
41
42 if (sigemptyset(&ss) < 0 || sigaddset(&ss, SIGTERM) < 0 ||
43 sigaddset(&ss, SIGINT) < 0)
44 {
45 r = -errno;
46 goto finish;
47 }
48 /* Block SIGTERM first, so that the event loop can handle it */
49 if (sigprocmask(SIG_BLOCK, &ss, NULL) < 0)
50 {
51 r = -errno;
52 goto finish;
53 }
54
55 /* Let's make use of the default handler and "floating"
56 reference features of sd_event_add_signal() */
57
58 r = sd_event_add_signal(eventPtr.get(), NULL, SIGTERM, NULL, NULL);
59 if (r < 0)
60 {
61 goto finish;
62 }
63
64 r = sd_event_add_signal(eventPtr.get(), NULL, SIGINT, NULL, NULL);
65 if (r < 0)
66 {
67 goto finish;
68 }
69
Ratan Gupta70b85272017-01-05 20:52:18 +053070 fd = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0);
Ratan Gupta309ac442016-12-13 20:40:06 +053071 if (fd < 0)
72 {
73 r = -errno;
74 goto finish;
75 }
76
Ratan Gupta70b85272017-01-05 20:52:18 +053077 serverAddr.sin6_family = AF_INET6;
78 serverAddr.sin6_port = htons(this->port);
Ratan Gupta309ac442016-12-13 20:40:06 +053079
Ratan Gupta70b85272017-01-05 20:52:18 +053080 if (bind(fd, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0)
Ratan Gupta309ac442016-12-13 20:40:06 +053081 {
82 r = -errno;
83 goto finish;
84 }
85
86 r = sd_event_add_io(eventPtr.get(), nullptr, fd, EPOLLIN, this->callme,
87 nullptr);
88 if (r < 0)
89 {
90 goto finish;
91 }
92
93 r = sd_event_loop(eventPtr.get());
94
95finish:
96
97 if (fd >= 0)
98 {
Patrick Venture537ff142018-11-01 16:37:09 -070099 (void)close(fd);
Ratan Gupta309ac442016-12-13 20:40:06 +0530100 }
101
102 if (r < 0)
103 {
104 fprintf(stderr, "Failure: %s\n", strerror(-r));
105 }
106
107 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
108}