source: flair-src/trunk/lib/FlairCore/src/UdpSocket_impl.cpp@ 465

Last change on this file since 465 was 387, checked in by Sanahuja Guillaume, 3 years ago

resolve bug with udp broadcast

File size: 11.5 KB
Line 
1// %flair:license{
2// This file is part of the Flair framework distributed under the
3// CECILL-C License, Version 1.0.
4// %flair:license}
5// created: 2013/11/17
6// filename: Socket_impl.cpp
7//
8// author: Guillaume Sanahuja
9// Copyright Heudiasyc UMR UTC/CNRS 7253
10//
11// version: $Id: $
12//
13// purpose: classe pour une Socket_impl
14//
15//
16/*********************************************************************/
17#include "UdpSocket_impl.h"
18#include "UdpSocket.h"
19#include "FrameworkManager.h"
20#include <fcntl.h>
21#include <cstdlib>
22#include <unistd.h>
23#include <string.h>
24#ifdef __XENO__
25#include "config.h"
26#endif
27
28using std::string;
29using namespace flair::core;
30
31UdpSocket_impl::UdpSocket_impl(const UdpSocket *self, string name, uint16_t port) {
32 this->self = self;
33 this->port = port;
34 this->address = "";
35 this->broadcast = false;
36 Init();
37}
38
39UdpSocket_impl::UdpSocket_impl(const UdpSocket *self, string name, string address,
40 bool broadcast) {
41 this->self = self;
42 int pos = address.find(":");
43 this->address = address.substr(0, pos);
44 port = atoi(address.substr(pos + 1).c_str());
45 this->broadcast = broadcast;
46
47 if (pos == 0 || address == "") {
48 self->Err("address %s is not correct\n", address.c_str());
49 }
50 Init();
51}
52
53void UdpSocket_impl::Init(void) {
54 int yes = 1;
55 sock_in_size=0;
56 sock_in=NULL;
57
58 fd = socket(AF_INET, SOCK_DGRAM, 0); // UDP
59
60 if (broadcast == true) {
61 if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &yes, sizeof(int)) != 0)
62 self->Err("Setsockopt error\n");
63 }
64
65 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) != 0)
66 self->Err("Setsockopt error\n");
67
68 if (address == "" || broadcast == true) {
69 sockaddr_in sin = {0};
70
71 if (broadcast == true) {
72 struct hostent *hostinfo;
73
74 hostinfo = gethostbyname(this->address.c_str());
75 if (hostinfo == NULL) {
76 self->Err("hostinfo error\n");
77 }
78 sin.sin_addr = *(in_addr *)hostinfo->h_addr;
79 } else {
80 sin.sin_addr.s_addr = INADDR_ANY;
81 }
82
83 sin.sin_port = htons(port);
84 sin.sin_family = AF_INET;
85 if (bind(fd, (sockaddr *)&sin, sizeof sin) == -1) {
86 self->Err("bind error\n");
87 }
88 }
89
90#ifdef __XENO__
91 string tmp_name;
92 int status;
93 is_running = true;
94
95 // pipe
96 tmp_name =
97 getFrameworkManager()->ObjectName() + "-" + self->ObjectName() + "-pipe";
98 // xenomai limitation
99 if (tmp_name.size() > 31)
100 self->Err("rt_pipe_create error (%s is too long)\n", tmp_name.c_str());
101#ifdef RT_PIPE_SIZE
102 status = rt_pipe_create(&pipe, tmp_name.c_str(), P_MINOR_AUTO, RT_PIPE_SIZE);
103#else
104 status = rt_pipe_create(&pipe, tmp_name.c_str(), P_MINOR_AUTO, 0);
105#endif
106 if (status != 0) {
107 char errorMsg[256];
108 self->Err("rt_pipe_create error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
109 }
110
111// start user side thread
112#ifdef NRT_STACK_SIZE
113 // Initialize thread creation attributes
114 pthread_attr_t attr;
115 if (pthread_attr_init(&attr) != 0) {
116 self->Err("pthread_attr_init error\n");
117 }
118 if (pthread_attr_setstacksize(&attr, NRT_STACK_SIZE) != 0) {
119 self->Err("pthread_attr_setstacksize error\n");
120 }
121 if (pthread_create(&user_thread, &attr, user, (void *)this) < 0) {
122 self->Err("pthread_create error\n");
123 }
124 if (pthread_attr_destroy(&attr) != 0) {
125 self->Err("pthread_attr_destroy error\n");
126 }
127#else // NRT_STACK_SIZE
128 if (pthread_create(&user_thread, NULL, user, (void *)this) < 0) {
129 self->Err("pthread_create error\n");
130 }
131#endif // NRT_STACK_SIZE
132#endif //__XENO__
133
134 if (address != "") {
135 struct hostent *hostinfo;
136 hostinfo = gethostbyname(address.c_str());
137 if (hostinfo == NULL) {
138 self->Err("gethostbyname\n");
139 }
140 sock_in=(struct sockaddr_in*)malloc(sizeof(struct sockaddr_in));
141 sock_in[0].sin_addr = *(in_addr *)hostinfo->h_addr;
142 sock_in[0].sin_port = htons(port);
143 sock_in[0].sin_family = AF_INET;
144 sock_in_size++;
145 }
146}
147
148UdpSocket_impl::~UdpSocket_impl() {
149#ifdef __XENO__
150 is_running = false;
151
152 pthread_join(user_thread, NULL);
153 int status = rt_pipe_delete(&pipe);
154 if (status != 0) {
155 char errorMsg[256];
156 self->Err("rt_pipe_delete error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
157 }
158#endif
159 close(fd);
160 free(sock_in);
161}
162
163void UdpSocket_impl::SendMessage(const char *msg, size_t msg_len,int dst_id) {
164 ssize_t written;
165 string to_send;
166
167 if (broadcast == true) {
168 to_send = getFrameworkManager()->ObjectName() + ":" + string(msg, msg_len);
169 msg_len = to_send.size();
170 msg = (char *)to_send.c_str();
171 }
172
173#ifdef __XENO__
174 // Printf("send pipe %s\n",src);
175 written = rt_pipe_write(&pipe, msg, msg_len, P_NORMAL);
176
177 if (written < 0) {
178 char errorMsg[256];
179 self->Err("rt_pipe_write error (%s)\n", strerror_r(-written, errorMsg, sizeof(errorMsg)));
180 } else if (written != (ssize_t)msg_len) {
181 self->Err("rt_pipe_write error %i/%i\n", written, to_send.size());
182 }
183#else
184 written = sendto(fd, msg, msg_len, 0, (struct sockaddr *)&(sock_in[dst_id]), sizeof(struct sockaddr_in));
185 if(written==-1) {
186 char errorMsg[256];
187 self->Err("sendto error (%s)\n",strerror_r(errno, errorMsg, sizeof(errorMsg)));
188 } else if (written != (ssize_t)msg_len) {
189 self->Err("sendto error %i/%i\n",written,msg_len);
190 }
191#endif
192}
193
194void UdpSocket_impl::SendMessage(string message,int dst_id) {
195 ssize_t written;
196
197 if (broadcast == true)
198 message = self->Parent()->ObjectName() + ":" + message;
199// Printf("SendMessage %s\n",message.c_str());
200#ifdef __XENO__
201 written = rt_pipe_write(&pipe, message.c_str(), message.size(), P_NORMAL);
202
203 if (written < 0) {
204 char errorMsg[256];
205 self->Err("rt_pipe_write error (%s)\n", strerror_r(-written, errorMsg, sizeof(errorMsg)));
206 } else if (written != (ssize_t)message.size()) {
207 self->Err("rt_pipe_write error %i/%i\n", written, message.size());
208 }
209#else
210 written = sendto(fd, message.c_str(), message.size(), 0,(struct sockaddr *)&(sock_in[dst_id]), sizeof(struct sockaddr_in));
211 if (written != (ssize_t)message.size()) {
212 self->Err("sendto error %i/%i\n",written,(ssize_t)message.size());
213 }
214
215#endif
216}
217
218ssize_t UdpSocket_impl::RecvMessage(char *msg, size_t msg_len, Time timeout,
219 char *src, size_t *src_len,int* src_id) {
220 ssize_t nb_read;
221 char buffer[128];
222#ifdef __XENO__
223 nb_read = rt_pipe_read(&pipe, &buffer, sizeof(buffer), timeout);
224#else
225
226 if (timeout != TIME_NONBLOCK) {
227 struct timeval tv;
228 int attr = fcntl(fd, F_GETFL, 0);
229 fcntl(fd, F_SETFL, attr & (~O_NONBLOCK));
230
231 tv.tv_sec = timeout / 1000000000;
232 timeout = timeout - (timeout / 1000000000) * 1000000000;
233 tv.tv_usec = timeout / 1000;
234 if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) {
235 self->Err("setsockopt SO_RCVTIMEO failed\n");
236 }
237 } else {
238 fcntl(fd, F_SETFL, O_NONBLOCK);
239 }
240
241 struct sockaddr_in sock_in_tmp;
242 if (broadcast == false) {
243 socklen_t sinsize = sizeof(struct sockaddr_in);
244 nb_read = recvfrom(fd, buffer, sizeof(buffer), 0, (sockaddr *)&sock_in_tmp, &sinsize);
245 } else {
246 nb_read = recvfrom(fd, buffer, sizeof(buffer), 0, NULL, NULL);
247 }
248
249 if(broadcast==false && nb_read>0) {
250 int i;
251 for(i=0;i<sock_in_size;i++) {
252 if(sock_in[i].sin_port==sock_in_tmp.sin_port) {
253 //Printf("match found in former adress\n");
254 if(src_id!=NULL) *src_id=i;
255 break;
256 }
257 }
258 if(i==sock_in_size) {
259 //Printf("no match found in former adress\n");
260 sock_in_size++;
261 sock_in=(sockaddr_in*)realloc(sock_in,sock_in_size*sizeof(sockaddr_in));
262 sock_in[sock_in_size-1]=sock_in_tmp;
263 if(src_id!=NULL) *src_id=sock_in_size-1;
264 }
265 }
266#endif
267 if (nb_read <= 0) {
268 return nb_read;
269 } else {
270 // printf("%s\n",buffer);
271 if (broadcast == true) {
272 int index = -1;
273 for (int i = 0; i < nb_read; i++) {
274 if (buffer[i] == ':') {
275 index = i;
276 break;
277 }
278 }
279 if (index < 0) {
280 self->Warn("Malformed message\n");
281 return -1;
282 } else if (src_len != NULL && src != NULL) {
283 if (index + 1 > (int)(*src_len) && src != NULL) { //+1 pour inserer un 0)
284 self->Warn("insufficent src size\n");
285 return -1;
286 }
287 } else if (nb_read - index - 1 + 1 > (int)msg_len) { //+1 pour inserer un 0
288 self->Warn("insufficent msg size (%i/%i)\n", nb_read - index - 1 + 1, msg_len);
289 return -1;
290 }
291 if (src != NULL) {
292 memcpy(src, buffer, index);
293 src[index] = 0;
294 }
295 memcpy(msg, &buffer[index + 1], nb_read - index - 1);
296 msg[nb_read - index - 1] = 0;
297 return nb_read - index;
298 } else {
299 if (nb_read > (int)msg_len) {
300 self->Warn("insufficent msg size (%i/%i)\n", nb_read, msg_len);
301 return -1;
302 }
303 memcpy(msg, buffer, nb_read);
304 return nb_read;
305 }
306 }
307}
308
309#ifdef __XENO__
310void *UdpSocket_impl::user(void *arg) {
311 UdpSocket_impl *caller = (UdpSocket_impl *)arg;
312 int pipe_fd = -1;
313 string devname;
314
315 devname = NRT_PIPE_PATH + getFrameworkManager()->ObjectName() + "-" +
316 caller->self->ObjectName() + "-pipe";
317 while (pipe_fd < 0) {
318 pipe_fd = open(devname.c_str(), O_RDWR);
319 if (pipe_fd < 0 && errno != ENOENT) {
320 char errorMsg[256];
321 caller->self->Err("open pipe_fd error (%s)\n", strerror_r(errno, errorMsg, sizeof(errorMsg)));
322 }
323 usleep(1000);
324 }
325
326 while (caller->is_running == true) {
327 fd_set set;
328 struct timeval timeout;
329 int rv;
330
331 FD_ZERO(&set); // clear the set
332 FD_SET(caller->fd, &set); // add our file descriptor to the set
333 FD_SET(pipe_fd, &set); // add our file descriptor to the set
334
335 timeout.tv_sec = 0;
336 timeout.tv_usec = SELECT_TIMEOUT_MS * 1000;
337 rv = select(FD_SETSIZE, &set, NULL, NULL, &timeout);
338
339 if (rv == -1) {
340 caller->self->Err("select error\n"); // an error occured
341 } else if (rv == 0) {
342 // printf("timeout\n");
343 } else {
344 ssize_t nb_read, nb_write;
345 char buffer[1024];
346
347 if (FD_ISSET(caller->fd, &set)) {
348 socklen_t sinsize = sizeof(struct sockaddr_in);
349 if (caller->broadcast == false) {
350 nb_read = recvfrom(caller->fd, buffer, sizeof(buffer), 0,
351 (sockaddr *)&(caller->sock_in), &sinsize);
352 } else {
353 nb_read = recvfrom(caller->fd, buffer, sizeof(buffer), 0, NULL, NULL);
354 }
355 if (nb_read < 0) {
356 caller->self->Err("recvfrom error\n");
357 }
358 // printf("user %s\n",buffer);
359 // on ne garde que les messages venant pas de soi meme
360 if (caller->broadcast == false ||
361 (caller->broadcast == true &&
362 getFrameworkManager()->ObjectName().compare(
363 0, getFrameworkManager()->ObjectName().size(), buffer,
364 getFrameworkManager()->ObjectName().size()) != 0)) {
365 nb_write = write(pipe_fd, buffer, nb_read);
366 if (nb_write != nb_read) {
367 caller->self->Err("write error\n");
368 }
369 } else {
370 // printf("self %s\n",buffer);
371 }
372 }
373 if (FD_ISSET(pipe_fd, &set)) {
374 nb_read = read(pipe_fd, buffer, sizeof(buffer));
375 // printf("read pipe %i %s\n",nb_read,buffer);
376 if (nb_read > 0) {
377 // printf("send %s\n",buffer);
378 nb_write = sendto(caller->fd, buffer, nb_read, 0,
379 (struct sockaddr *)&(caller->sock_in),
380 sizeof(struct sockaddr_in));
381 if (nb_write != nb_read) {
382 caller->self->Err("sendto error\n");
383 }
384 }
385 }
386 }
387 }
388
389 close(pipe_fd);
390 pthread_exit(0);
391}
392#endif
Note: See TracBrowser for help on using the repository browser.