blob: e307dab17638a07eca82092448ca0306916a3af0 [file] [log] [blame]
Ratan Gupta309ac442016-12-13 20:40:06 +05301#include "slp_server.hpp"
2
3#include <memory>
4
5#include <stdio.h>
6#include <stdlib.h>
7#include <string.h>
8#include <unistd.h>
9
10#include "sock_channel.hpp"
11
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{
19 struct sockaddr_in in {};
20
21 sd_event* event = nullptr;
22
23 slp::deleted_unique_ptr<sd_event> eventPtr(event, [](sd_event * event)
24 {
25 if (!event)
26 {
27 event = sd_event_unref(event);
28 }
29 });
30
31 int fd = -1, r;
32 sigset_t ss;
33
34 r = sd_event_default(&event);
35 if (r < 0)
36 {
37 goto finish;
38 }
39
40 eventPtr.reset(event);
41 event = nullptr;
42
43 if (sigemptyset(&ss) < 0 || sigaddset(&ss, SIGTERM) < 0 ||
44 sigaddset(&ss, SIGINT) < 0)
45 {
46 r = -errno;
47 goto finish;
48 }
49 /* Block SIGTERM first, so that the event loop can handle it */
50 if (sigprocmask(SIG_BLOCK, &ss, NULL) < 0)
51 {
52 r = -errno;
53 goto finish;
54 }
55
56 /* Let's make use of the default handler and "floating"
57 reference features of sd_event_add_signal() */
58
59 r = sd_event_add_signal(eventPtr.get(), NULL, SIGTERM, NULL, NULL);
60 if (r < 0)
61 {
62 goto finish;
63 }
64
65 r = sd_event_add_signal(eventPtr.get(), NULL, SIGINT, NULL, NULL);
66 if (r < 0)
67 {
68 goto finish;
69 }
70
71 fd = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0);
72 if (fd < 0)
73 {
74 r = -errno;
75 goto finish;
76 }
77
78 in.sin_family = AF_INET;
79 in.sin_port = htons(this->port);
80 in.sin_addr.s_addr = INADDR_ANY;
81
82 if (bind(fd, (struct sockaddr*)&in, sizeof(in)) < 0)
83 {
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 {
101 (void) close(fd);
102 }
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}