Move files from gst-plugins-bad into the "subprojects/gst-plugins-bad/" subdir
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-bad / ext / sctp / usrsctp / usrsctplib / netinet / sctp_userspace.c
1 /*-
2  * Copyright (c) 2011-2012 Irene Ruengeler
3  * Copyright (c) 2011-2012 Michael Tuexen
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  */
28
29
30 #ifdef _WIN32
31 #include <netinet/sctp_pcb.h>
32 #include <sys/timeb.h>
33 #include <iphlpapi.h>
34 #if !defined(__MINGW32__)
35 #pragma comment(lib, "IPHLPAPI.lib")
36 #endif
37 #endif
38 #include <netinet/sctp_os_userspace.h>
39 #if defined(__FreeBSD__)
40 #include <pthread_np.h>
41 #endif
42
43 #if defined(__linux__)
44 #include <sys/prctl.h>
45 #endif
46
47 #if defined(_WIN32)
48 /* Adapter to translate Unix thread start routines to Windows thread start
49  * routines.
50  */
51 #if defined(__MINGW32__)
52 #pragma GCC diagnostic push
53 #pragma GCC diagnostic ignored "-Wpedantic"
54 #endif
55 static DWORD WINAPI
56 sctp_create_thread_adapter(void *arg) {
57         start_routine_t start_routine = (start_routine_t)arg;
58         return start_routine(NULL) == NULL;
59 }
60
61 int
62 sctp_userspace_thread_create(userland_thread_t *thread, start_routine_t start_routine)
63 {
64         *thread = CreateThread(NULL, 0, sctp_create_thread_adapter,
65                                (void *)start_routine, 0, NULL);
66         if (*thread == NULL)
67                 return GetLastError();
68         return 0;
69 }
70
71 #if defined(__MINGW32__)
72 #pragma GCC diagnostic pop
73 #endif
74
75 #else
76 int
77 sctp_userspace_thread_create(userland_thread_t *thread, start_routine_t start_routine)
78 {
79         return pthread_create(thread, NULL, start_routine, NULL);
80 }
81 #endif
82
83 void
84 sctp_userspace_set_threadname(const char *name)
85 {
86 #if defined(__APPLE__)
87         pthread_setname_np(name);
88 #endif
89 #if defined(__linux__)
90         prctl(PR_SET_NAME, name);
91 #endif
92 #if defined(__FreeBSD__)
93         pthread_set_name_np(pthread_self(), name);
94 #endif
95 }
96
97 #if !defined(_WIN32) && !defined(__native_client__)
98 int
99 sctp_userspace_get_mtu_from_ifn(uint32_t if_index, int af)
100 {
101         struct ifreq ifr;
102         int fd;
103
104         memset(&ifr, 0, sizeof(struct ifreq));
105         if (if_indextoname(if_index, ifr.ifr_name) != NULL) {
106                 /* TODO can I use the raw socket here and not have to open a new one with each query? */
107                 if ((fd = socket(af, SOCK_DGRAM, 0)) < 0)
108                         return (0);
109                 if (ioctl(fd, SIOCGIFMTU, &ifr) < 0) {
110                         close(fd);
111                         return (0);
112                 }
113                 close(fd);
114                 return ifr.ifr_mtu;
115         } else {
116                 return (0);
117         }
118 }
119 #endif
120
121 #if defined(__native_client__)
122 int
123 sctp_userspace_get_mtu_from_ifn(uint32_t if_index, int af)
124 {
125         return 1280;
126 }
127 #endif
128
129 #if defined(__APPLE__) || defined(__DragonFly__) || defined(__linux__) || defined(__native_client__) || defined(__NetBSD__) || defined(_WIN32) || defined(__Fuchsia__)
130 int
131 timingsafe_bcmp(const void *b1, const void *b2, size_t n)
132 {
133         const unsigned char *p1 = b1, *p2 = b2;
134         int ret = 0;
135
136         for (; n > 0; n--)
137                 ret |= *p1++ ^ *p2++;
138         return (ret != 0);
139 }
140 #endif
141
142 #ifdef _WIN32
143 int
144 sctp_userspace_get_mtu_from_ifn(uint32_t if_index, int af)
145 {
146         PIP_ADAPTER_ADDRESSES pAdapterAddrs, pAdapt;
147         DWORD AdapterAddrsSize, Err;
148         int ret;
149
150         ret = 0;
151         AdapterAddrsSize = 0;
152         pAdapterAddrs = NULL;
153         if ((Err = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, NULL, &AdapterAddrsSize)) != 0) {
154                 if ((Err != ERROR_BUFFER_OVERFLOW) && (Err != ERROR_INSUFFICIENT_BUFFER)) {
155                         SCTPDBG(SCTP_DEBUG_USR, "GetAdaptersAddresses() sizing failed with error code %d, AdapterAddrsSize = %d\n", Err, AdapterAddrsSize);
156                         ret = -1;
157                         goto cleanup;
158                 }
159         }
160         if ((pAdapterAddrs = (PIP_ADAPTER_ADDRESSES) GlobalAlloc(GPTR, AdapterAddrsSize)) == NULL) {
161                 SCTPDBG(SCTP_DEBUG_USR, "Memory allocation error!\n");
162                 ret = -1;
163                 goto cleanup;
164         }
165         if ((Err = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, pAdapterAddrs, &AdapterAddrsSize)) != ERROR_SUCCESS) {
166                 SCTPDBG(SCTP_DEBUG_USR, "GetAdaptersAddresses() failed with error code %d\n", Err);
167                 ret = -1;
168                 goto cleanup;
169         }
170         for (pAdapt = pAdapterAddrs; pAdapt; pAdapt = pAdapt->Next) {
171                 if (pAdapt->IfIndex == if_index) {
172                         ret = pAdapt->Mtu;
173                         break;
174                 }
175         }
176 cleanup:
177         if (pAdapterAddrs != NULL) {
178                 GlobalFree(pAdapterAddrs);
179         }
180         return (ret);
181 }
182
183 void
184 getwintimeofday(struct timeval *tv)
185 {
186         FILETIME filetime;
187         ULARGE_INTEGER ularge;
188
189         GetSystemTimeAsFileTime(&filetime);
190         ularge.LowPart = filetime.dwLowDateTime;
191         ularge.HighPart = filetime.dwHighDateTime;
192         /* Change base from Jan 1 1601 00:00:00 to Jan 1 1970 00:00:00 */
193 #if defined(__MINGW32__)
194         ularge.QuadPart -= 116444736000000000ULL;
195 #else
196         ularge.QuadPart -= 116444736000000000UI64;
197 #endif
198         /*
199          * ularge.QuadPart is now the number of 100-nanosecond intervals
200          * since Jan 1 1970 00:00:00.
201          */
202 #if defined(__MINGW32__)
203         tv->tv_sec = (long)(ularge.QuadPart / 10000000ULL);
204         tv->tv_usec = (long)((ularge.QuadPart % 10000000ULL) / 10ULL);
205 #else
206         tv->tv_sec = (long)(ularge.QuadPart / 10000000UI64);
207         tv->tv_usec = (long)((ularge.QuadPart % 10000000UI64) / 10UI64);
208 #endif
209 }
210
211 int
212 win_if_nametoindex(const char *ifname)
213 {
214         IP_ADAPTER_ADDRESSES *addresses, *addr;
215         ULONG status, size;
216         int index = 0;
217
218         if (!ifname) {
219                 return 0;
220         }
221
222         size = 0;
223         status = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, NULL, &size);
224         if (status != ERROR_BUFFER_OVERFLOW) {
225                 return 0;
226         }
227         addresses = malloc(size);
228         status = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, addresses, &size);
229         if (status == ERROR_SUCCESS) {
230                 for (addr = addresses; addr; addr = addr->Next) {
231                         if (addr->AdapterName && !strcmp(ifname, addr->AdapterName)) {
232                                 index = addr->IfIndex;
233                                 break;
234                         }
235                 }
236         }
237
238         free(addresses);
239         return index;
240 }
241
242 #if WINVER < 0x0600
243 /* These functions are written based on the code at
244  * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
245  * Therefore, for the rest of the file the following applies:
246  *
247  *
248  * Copyright and Licensing Information for ACE(TM), TAO(TM), CIAO(TM),
249  * DAnCE(TM), and CoSMIC(TM)
250  *
251  * [1]ACE(TM), [2]TAO(TM), [3]CIAO(TM), DAnCE(TM), and [4]CoSMIC(TM)
252  * (henceforth referred to as "DOC software") are copyrighted by
253  * [5]Douglas C. Schmidt and his [6]research group at [7]Washington
254  * University, [8]University of California, Irvine, and [9]Vanderbilt
255  * University, Copyright (c) 1993-2012, all rights reserved. Since DOC
256  * software is open-source, freely available software, you are free to
257  * use, modify, copy, and distribute--perpetually and irrevocably--the
258  * DOC software source code and object code produced from the source, as
259  * well as copy and distribute modified versions of this software. You
260  * must, however, include this copyright statement along with any code
261  * built using DOC software that you release. No copyright statement
262  * needs to be provided if you just ship binary executables of your
263  * software products.
264  *
265  * You can use DOC software in commercial and/or binary software releases
266  * and are under no obligation to redistribute any of your source code
267  * that is built using DOC software. Note, however, that you may not
268  * misappropriate the DOC software code, such as copyrighting it yourself
269  * or claiming authorship of the DOC software code, in a way that will
270  * prevent DOC software from being distributed freely using an
271  * open-source development model. You needn't inform anyone that you're
272  * using DOC software in your software, though we encourage you to let
273  * [10]us know so we can promote your project in the [11]DOC software
274  * success stories.
275  *
276  * The [12]ACE, [13]TAO, [14]CIAO, [15]DAnCE, and [16]CoSMIC web sites
277  * are maintained by the [17]DOC Group at the [18]Institute for Software
278  * Integrated Systems (ISIS) and the [19]Center for Distributed Object
279  * Computing of Washington University, St. Louis for the development of
280  * open-source software as part of the open-source software community.
281  * Submissions are provided by the submitter ``as is'' with no warranties
282  * whatsoever, including any warranty of merchantability, noninfringement
283  * of third party intellectual property, or fitness for any particular
284  * purpose. In no event shall the submitter be liable for any direct,
285  * indirect, special, exemplary, punitive, or consequential damages,
286  * including without limitation, lost profits, even if advised of the
287  * possibility of such damages. Likewise, DOC software is provided as is
288  * with no warranties of any kind, including the warranties of design,
289  * merchantability, and fitness for a particular purpose,
290  * noninfringement, or arising from a course of dealing, usage or trade
291  * practice. Washington University, UC Irvine, Vanderbilt University,
292  * their employees, and students shall have no liability with respect to
293  * the infringement of copyrights, trade secrets or any patents by DOC
294  * software or any part thereof. Moreover, in no event will Washington
295  * University, UC Irvine, or Vanderbilt University, their employees, or
296  * students be liable for any lost revenue or profits or other special,
297  * indirect and consequential damages.
298  *
299  * DOC software is provided with no support and without any obligation on
300  * the part of Washington University, UC Irvine, Vanderbilt University,
301  * their employees, or students to assist in its use, correction,
302  * modification, or enhancement. A [20]number of companies around the
303  * world provide commercial support for DOC software, however. DOC
304  * software is Y2K-compliant, as long as the underlying OS platform is
305  * Y2K-compliant. Likewise, DOC software is compliant with the new US
306  * daylight savings rule passed by Congress as "The Energy Policy Act of
307  * 2005," which established new daylight savings times (DST) rules for
308  * the United States that expand DST as of March 2007. Since DOC software
309  * obtains time/date and calendaring information from operating systems
310  * users will not be affected by the new DST rules as long as they
311  * upgrade their operating systems accordingly.
312  *
313  * The names ACE(TM), TAO(TM), CIAO(TM), DAnCE(TM), CoSMIC(TM),
314  * Washington University, UC Irvine, and Vanderbilt University, may not
315  * be used to endorse or promote products or services derived from this
316  * source without express written permission from Washington University,
317  * UC Irvine, or Vanderbilt University. This license grants no permission
318  * to call products or services derived from this source ACE(TM),
319  * TAO(TM), CIAO(TM), DAnCE(TM), or CoSMIC(TM), nor does it grant
320  * permission for the name Washington University, UC Irvine, or
321  * Vanderbilt University to appear in their names.
322  *
323  * If you have any suggestions, additions, comments, or questions, please
324  * let [21]me know.
325  *
326  * [22]Douglas C. Schmidt
327  *
328  * References
329  *
330  *  1. http://www.cs.wustl.edu/~schmidt/ACE.html
331  *  2. http://www.cs.wustl.edu/~schmidt/TAO.html
332  *  3. http://www.dre.vanderbilt.edu/CIAO/
333  *  4. http://www.dre.vanderbilt.edu/cosmic/
334  *  5. http://www.dre.vanderbilt.edu/~schmidt/
335  *  6. http://www.cs.wustl.edu/~schmidt/ACE-members.html
336  *  7. http://www.wustl.edu/
337  *  8. http://www.uci.edu/
338  *  9. http://www.vanderbilt.edu/
339  * 10. mailto:doc_group@cs.wustl.edu
340  * 11. http://www.cs.wustl.edu/~schmidt/ACE-users.html
341  * 12. http://www.cs.wustl.edu/~schmidt/ACE.html
342  * 13. http://www.cs.wustl.edu/~schmidt/TAO.html
343  * 14. http://www.dre.vanderbilt.edu/CIAO/
344  * 15. http://www.dre.vanderbilt.edu/~schmidt/DOC_ROOT/DAnCE/
345  * 16. http://www.dre.vanderbilt.edu/cosmic/
346  * 17. http://www.dre.vanderbilt.edu/
347  * 18. http://www.isis.vanderbilt.edu/
348  * 19. http://www.cs.wustl.edu/~schmidt/doc-center.html
349  * 20. http://www.cs.wustl.edu/~schmidt/commercial-support.html
350  * 21. mailto:d.schmidt@vanderbilt.edu
351  * 22. http://www.dre.vanderbilt.edu/~schmidt/
352  * 23. http://www.cs.wustl.edu/ACE.html
353  */
354
355 void
356 InitializeXPConditionVariable(userland_cond_t *cv)
357 {
358         cv->waiters_count = 0;
359         InitializeCriticalSection(&(cv->waiters_count_lock));
360         cv->events_[C_SIGNAL] = CreateEvent (NULL, FALSE, FALSE, NULL);
361         cv->events_[C_BROADCAST] = CreateEvent (NULL, TRUE, FALSE, NULL);
362 }
363
364 void
365 DeleteXPConditionVariable(userland_cond_t *cv)
366 {
367         CloseHandle(cv->events_[C_BROADCAST]);
368         CloseHandle(cv->events_[C_SIGNAL]);
369         DeleteCriticalSection(&(cv->waiters_count_lock));
370 }
371
372 int
373 SleepXPConditionVariable(userland_cond_t *cv, userland_mutex_t *mtx)
374 {
375         int result, last_waiter;
376
377         EnterCriticalSection(&cv->waiters_count_lock);
378         cv->waiters_count++;
379         LeaveCriticalSection(&cv->waiters_count_lock);
380         LeaveCriticalSection (mtx);
381         result = WaitForMultipleObjects(2, cv->events_, FALSE, INFINITE);
382         if (result==-1) {
383                 result = GetLastError();
384         }
385         EnterCriticalSection(&cv->waiters_count_lock);
386         cv->waiters_count--;
387         last_waiter = result == (C_SIGNAL + C_BROADCAST && (cv->waiters_count == 0));
388         LeaveCriticalSection(&cv->waiters_count_lock);
389         if (last_waiter)
390                 ResetEvent(cv->events_[C_BROADCAST]);
391         EnterCriticalSection (mtx);
392         return result;
393 }
394
395 void
396 WakeAllXPConditionVariable(userland_cond_t *cv)
397 {
398         int have_waiters;
399         EnterCriticalSection(&cv->waiters_count_lock);
400         have_waiters = cv->waiters_count > 0;
401         LeaveCriticalSection(&cv->waiters_count_lock);
402         if (have_waiters)
403                 SetEvent (cv->events_[C_BROADCAST]);
404 }
405 #endif
406 #endif