139c799c0ae4484cd4b08dfcf9d50fdf7137f03b
[ardour.git] / libs / midi++2 / ipmidi_port.cc
1 /*
2     Copyright (C) 2012 Paul Davis
3
4     Using code from Rui Nuno Capela's qmidinet as inspiration.
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20     $Id: port.cc 12065 2012-04-23 16:23:48Z paul $
21 */
22 #include <iostream>
23 #include <cstdio>
24 #include <fcntl.h>
25 #include <errno.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #ifdef   COMPILER_MSVC
29 #undef   O_NONBLOCK
30 #define  O_NONBLOCK 0
31 #endif
32 #if defined(PLATFORM_WINDOWS)
33 #include <winsock2.h>
34 #include <ws2tcpip.h>
35 #else
36 #include <netdb.h>
37 #endif
38
39 #if defined(PLATFORM_WINDOWS)
40 typedef int socklen_t;
41 #else
42 #include <unistd.h>
43 #include <sys/ioctl.h>
44 inline void closesocket(int s) { ::close(s); }
45 #endif
46
47 #include "pbd/xml++.h"
48 #include "pbd/error.h"
49 #include "pbd/failed_constructor.h"
50 #include "pbd/convert.h"
51 #include "pbd/compose.h"
52
53 #include "midi++/types.h"
54 #include "midi++/ipmidi_port.h"
55 #include "midi++/channel.h"
56
57 using namespace MIDI;
58 using namespace std;
59 using namespace PBD;
60
61 IPMIDIPort::IPMIDIPort (int base_port, const string& iface)
62         : Port (string_compose ("IPmidi@%1", base_port), Port::Flags (Port::IsInput|Port::IsOutput))
63         , sockin (-1)
64         , sockout (-1)
65 {
66         if (!open_sockets (base_port, iface)) {
67                 throw (failed_constructor ());
68         }
69 }
70
71 IPMIDIPort::IPMIDIPort (const XMLNode& node)
72         : Port (node)
73 {
74         /* base class does not class set_state() */
75         set_state (node);
76 }
77
78 IPMIDIPort::~IPMIDIPort ()
79 {
80         close_sockets ();
81 }
82
83 int
84 IPMIDIPort::selectable () const
85 {
86         return sockin;
87 }
88
89 XMLNode&
90 IPMIDIPort::get_state () const
91 {
92         return Port::get_state ();
93 }
94
95 void
96 IPMIDIPort::set_state (const XMLNode& node)
97 {
98         Port::set_state (node);
99 }
100
101 void
102 IPMIDIPort::close_sockets ()
103 {
104         if (sockin >= 0) {
105                 ::closesocket (sockin);
106                 sockin = -1;
107         }
108
109         if (sockout >= 0) {
110                 ::closesocket (sockout);
111                 sockout = -1;
112         }
113 }
114
115 #ifndef PLATFORM_WINDOWS
116 static bool
117 get_address (int sock, struct in_addr *inaddr, const string& ifname )
118 {
119         // Get interface address from supplied name.
120
121         struct ifreq ifr;
122         ::strncpy(ifr.ifr_name, ifname.c_str(), sizeof(ifr.ifr_name));
123
124         if (::ioctl(sock, SIOCGIFFLAGS, (char *) &ifr)) {
125                 ::perror("ioctl(SIOCGIFFLAGS)");
126                 return false;
127         }
128
129         if ((ifr.ifr_flags & IFF_UP) == 0) {
130                 error << string_compose ("interface %1 is down", ifname) << endmsg;
131                 return false;
132         }
133
134         if (::ioctl(sock, SIOCGIFADDR, (char *) &ifr)) {
135                 ::perror("ioctl(SIOCGIFADDR)");
136                 return false;
137         }
138
139         struct sockaddr_in sa;
140         ::memcpy(&sa, &ifr.ifr_addr, sizeof(struct sockaddr_in));
141         inaddr->s_addr = sa.sin_addr.s_addr;
142
143         return true;
144 }
145 #endif
146
147 bool
148 IPMIDIPort::open_sockets (int base_port, const string& ifname)
149 {
150         int protonum = 0;
151         struct protoent *proto = ::getprotobyname("IP");
152
153         if (proto) {
154                 protonum = proto->p_proto;
155         }
156
157         sockin = ::socket (PF_INET, SOCK_DGRAM, protonum);
158         if (sockin < 0) {
159                 ::perror("socket(in)");
160                 return false;
161         }
162
163         struct sockaddr_in addrin;
164         ::memset(&addrin, 0, sizeof(addrin));
165         addrin.sin_family = AF_INET;
166         addrin.sin_addr.s_addr = htonl(INADDR_ANY);
167         addrin.sin_port = htons(base_port);
168
169         if (::bind(sockin, (struct sockaddr *) (&addrin), sizeof(addrin)) < 0) {
170                 ::perror("bind");
171                 return false;
172         }
173
174         // Will Hall, 2007
175         // INADDR_ANY will bind to default interface,
176         // specify alternate interface nameon which to bind...
177         struct in_addr if_addr_in;
178 #ifndef PLATFORM_WINDOWS
179         if (!ifname.empty()) {
180                 if (!get_address(sockin, &if_addr_in, ifname)) {
181                         error << string_compose ("socket(in): could not find interface address for %1", ifname) << endmsg;
182                         return false;
183                 }
184                 if (::setsockopt(sockin, IPPROTO_IP, IP_MULTICAST_IF,
185                                  (char *) &if_addr_in, sizeof(if_addr_in))) {
186                         ::perror("setsockopt(IP_MULTICAST_IF)");
187                         return false;
188                 }
189         } else {
190                 if_addr_in.s_addr = htonl (INADDR_ANY);
191         }
192 #else
193         if_addr_in.s_addr = htonl (INADDR_ANY);
194 #endif
195
196         struct ip_mreq mreq;
197         mreq.imr_multiaddr.s_addr = ::inet_addr("225.0.0.37"); /* ipMIDI group multicast address */
198         mreq.imr_interface.s_addr = if_addr_in.s_addr;
199         if(::setsockopt (sockin, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *) &mreq, sizeof(mreq)) < 0) {
200                 ::perror("setsockopt(IP_ADD_MEMBERSHIP)");
201                 fprintf(stderr, "socket(in): your kernel is probably missing multicast support.\n");
202                 return false;
203         }
204
205         // Output socket...
206
207         sockout = ::socket (AF_INET, SOCK_DGRAM, protonum);
208
209         if (sockout < 0) {
210                 ::perror("socket(out)");
211                 return false;
212         }
213
214         // Will Hall, Oct 2007
215 #ifndef PLATFORM_WINDOWS
216         if (!ifname.empty()) {
217                 struct in_addr if_addr_out;
218                 if (!get_address(sockout, &if_addr_out, ifname)) {
219                         error << string_compose ("socket(out): could not find interface address for %1", ifname) << endmsg;
220                         return false;
221                 }
222                 if (::setsockopt(sockout, IPPROTO_IP, IP_MULTICAST_IF, (char *) &if_addr_out, sizeof(if_addr_out))) {
223                         ::perror("setsockopt(IP_MULTICAST_IF)");
224                         return false;
225                 }
226         }
227 #endif
228
229         ::memset(&addrout, 0, sizeof(struct sockaddr_in));
230         addrout.sin_family = AF_INET;
231         addrout.sin_addr.s_addr = ::inet_addr("225.0.0.37");
232         addrout.sin_port = htons (base_port);
233
234         struct sockaddr_in any;
235         ::memset(&any, 0, sizeof(struct sockaddr_in));
236         addrout.sin_family = AF_INET;
237         addrout.sin_addr.s_addr = INADDR_ANY;
238         addrout.sin_port = htons (base_port);
239
240         if (::bind(sockout, (struct sockaddr *) (&any), sizeof(any)) < 0) {
241                 ::perror("bind");
242                 cout << "ipmidi bind error\n";
243                 return false;
244         }
245
246 #ifndef PLATFORM_WINDOWS
247         int loop;
248         socklen_t size;
249 #else
250         u_char loop;
251         int size;
252 #endif
253
254         if (::getsockopt (sockout, IPPROTO_IP, IP_MULTICAST_LOOP, (char *) &loop, &size)) {
255                 // ::perror ("getsockopt(IP_MULTICAST_LOOP)");
256                 cout << "Cannot get loopback status\n";
257         } else {
258                 cout << "********* 1. multicast loopback: " << loop << " size was " << size << endl;
259         }
260
261         // Turn off loopback...
262         loop = 0;
263         if (::setsockopt(sockout, IPPROTO_IP, IP_MULTICAST_LOOP, (char *) &loop, sizeof (loop)) < 0) {
264                 //::perror("setsockopt(IP_MULTICAST_LOOP)");
265                 cout << "Cannot set loopback status\n";
266                 return false;
267         }
268
269         if (::getsockopt (sockout, IPPROTO_IP, IP_MULTICAST_LOOP, (char *) &loop, &size)) {
270                 // ::perror ("getsockopt(IP_MULTICAST_LOOP)");
271                 cout << "Cannot Get loopback status 2\n";
272         } else {
273                 cout << "********* 2. multicast loopback: " << loop << " size was " << size << endl;
274         }
275
276 #ifndef PLATFORM_WINDOWS
277
278         if (fcntl (sockin, F_SETFL, O_NONBLOCK)) {
279                 error << "cannot set non-blocking mode for IP MIDI input socket (" << ::strerror (errno) << ')' << endmsg;
280                 return false;
281         }
282
283         if (fcntl (sockout, F_SETFL, O_NONBLOCK)) {
284                 error << "cannot set non-blocking mode for IP MIDI output socket (" << ::strerror (errno) << ')' << endmsg;
285                 return false;
286         }
287
288 #else
289         // If imode !=0, non-blocking mode is enabled.
290         u_long mode=1;
291         if (ioctlsocket(sockin,FIONBIO,&mode)) {
292                 error << "cannot set non-blocking mode for IP MIDI input socket (" << ::strerror (errno) << ')' << endmsg;
293                 return false;
294         }
295         mode = 1; /* just in case it was modified in the previous call */
296         if (ioctlsocket(sockout,FIONBIO,&mode)) {
297                 error << "cannot set non-blocking mode for IP MIDI output socket (" << ::strerror (errno) << ')' << endmsg;
298                 return false;
299         }
300 #endif
301         cout << "ipmidi ports setup!!!!!!!\n";
302         return true;
303 }
304
305 int
306 IPMIDIPort::write (const MIDI::byte* msg, size_t msglen, timestamp_t /* ignored */) {
307
308         if (sockout) {
309                 Glib::Threads::Mutex::Lock lm (write_lock);
310                 if (::sendto (sockout, (const char *) msg, msglen, 0, (struct sockaddr *) &addrout, sizeof(struct sockaddr_in)) < 0) {
311                         ::perror("sendto");
312                         return -1;
313                 }
314                 return msglen;
315         }
316         return 0;
317 }
318
319 int
320 IPMIDIPort::read (MIDI::byte* /*buf*/, size_t /*bufsize*/)
321 {
322         /* nothing to do here - all handled by parse() */
323         return 0;
324 }
325
326 void
327 IPMIDIPort::parse (framecnt_t timestamp)
328 {
329         /* input was detected on the socket, so go get it and hand it to the
330          * parser. This will emit appropriate signals that will be handled
331          * by anyone who cares.
332          */
333
334         unsigned char buf[1024];
335         struct sockaddr_in sender;
336         socklen_t slen = sizeof(sender);
337         int r = ::recvfrom (sockin, (char *) buf, sizeof(buf), 0, (struct sockaddr *) &sender, &slen);
338
339         if (r >= 0) {
340
341                 _parser->set_timestamp (timestamp);
342
343                 for (int i = 0; i < r; ++i) {
344                         _parser->scanner (buf[i]);
345                 }
346         } else {
347                 ::perror ("failed to recv from socket");
348         }
349 }