webrtc nice: Let libnice handle STUN/TURN DNS resolution
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-bad / gst-libs / gst / webrtc / nice / nice.c
1 /* GStreamer
2  * Copyright (C) 2017 Matthew Waters <matthew@centricular.com>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
17  * Boston, MA 02110-1301, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 # include "config.h"
22 #endif
23
24 #include "nice.h"
25 #include "nicestream.h"
26 /* libnice */
27 #include <agent.h>
28
29 #define HTTP_PROXY_PORT_DEFAULT 3128
30
31 /* XXX:
32  *
33  * - are locally generated remote candidates meant to be readded to libnice?
34  */
35
36 static GstUri *_validate_turn_server (GstWebRTCNice * ice, const gchar * s);
37
38 #define GST_CAT_DEFAULT gst_webrtc_nice_debug
39 GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
40
41 enum
42 {
43   PROP_0,
44   PROP_AGENT,
45   PROP_ICE_TCP,
46   PROP_ICE_UDP,
47   PROP_MIN_RTP_PORT,
48   PROP_MAX_RTP_PORT,
49 };
50
51 struct _GstWebRTCNicePrivate
52 {
53   NiceAgent *nice_agent;
54
55   GArray *nice_stream_map;
56
57   GThread *thread;
58   GMainContext *main_context;
59   GMainLoop *loop;
60   GMutex lock;
61   GCond cond;
62
63   GstWebRTCICEOnCandidateFunc on_candidate;
64   gpointer on_candidate_data;
65   GDestroyNotify on_candidate_notify;
66
67   GstUri *stun_server;
68   GstUri *turn_server;
69
70   GHashTable *turn_servers;
71
72   GstUri *http_proxy;
73 };
74
75 #define gst_webrtc_nice_parent_class parent_class
76 G_DEFINE_TYPE_WITH_CODE (GstWebRTCNice, gst_webrtc_nice,
77     GST_TYPE_WEBRTC_ICE, G_ADD_PRIVATE (GstWebRTCNice)
78     GST_DEBUG_CATEGORY_INIT (gst_webrtc_nice_debug, "webrtcnice", 0,
79         "webrtcnice"););
80
81 static gboolean
82 _unlock_pc_thread (GMutex * lock)
83 {
84   g_mutex_unlock (lock);
85   return G_SOURCE_REMOVE;
86 }
87
88 static gpointer
89 _gst_nice_thread (GstWebRTCNice * ice)
90 {
91   g_mutex_lock (&ice->priv->lock);
92   ice->priv->main_context = g_main_context_new ();
93   ice->priv->loop = g_main_loop_new (ice->priv->main_context, FALSE);
94
95   g_cond_broadcast (&ice->priv->cond);
96   g_main_context_invoke (ice->priv->main_context,
97       (GSourceFunc) _unlock_pc_thread, &ice->priv->lock);
98
99   g_main_loop_run (ice->priv->loop);
100
101   g_mutex_lock (&ice->priv->lock);
102   g_main_context_unref (ice->priv->main_context);
103   ice->priv->main_context = NULL;
104   g_main_loop_unref (ice->priv->loop);
105   ice->priv->loop = NULL;
106   g_cond_broadcast (&ice->priv->cond);
107   g_mutex_unlock (&ice->priv->lock);
108
109   return NULL;
110 }
111
112 static void
113 _start_thread (GstWebRTCNice * ice)
114 {
115   g_mutex_lock (&ice->priv->lock);
116   ice->priv->thread = g_thread_new (GST_OBJECT_NAME (ice),
117       (GThreadFunc) _gst_nice_thread, ice);
118
119   while (!ice->priv->loop)
120     g_cond_wait (&ice->priv->cond, &ice->priv->lock);
121   g_mutex_unlock (&ice->priv->lock);
122 }
123
124 static void
125 _stop_thread (GstWebRTCNice * ice)
126 {
127   g_mutex_lock (&ice->priv->lock);
128   g_main_loop_quit (ice->priv->loop);
129   while (ice->priv->loop)
130     g_cond_wait (&ice->priv->cond, &ice->priv->lock);
131   g_mutex_unlock (&ice->priv->lock);
132
133   g_thread_unref (ice->priv->thread);
134 }
135
136 struct NiceStreamItem
137 {
138   guint session_id;
139   guint nice_stream_id;
140   GstWebRTCICEStream *stream;
141 };
142
143 /* TRUE to continue, FALSE to stop */
144 typedef gboolean (*NiceStreamItemForeachFunc) (struct NiceStreamItem * item,
145     gpointer user_data);
146
147 static void
148 _nice_stream_item_foreach (GstWebRTCNice * ice, NiceStreamItemForeachFunc func,
149     gpointer data)
150 {
151   int i, len;
152
153   len = ice->priv->nice_stream_map->len;
154   for (i = 0; i < len; i++) {
155     struct NiceStreamItem *item =
156         &g_array_index (ice->priv->nice_stream_map, struct NiceStreamItem,
157         i);
158
159     if (!func (item, data))
160       break;
161   }
162 }
163
164 /* TRUE for match, FALSE otherwise */
165 typedef gboolean (*NiceStreamItemFindFunc) (struct NiceStreamItem * item,
166     gpointer user_data);
167
168 struct nice_find
169 {
170   NiceStreamItemFindFunc func;
171   gpointer data;
172   struct NiceStreamItem *ret;
173 };
174
175 static gboolean
176 _find_nice_item (struct NiceStreamItem *item, gpointer user_data)
177 {
178   struct nice_find *f = user_data;
179   if (f->func (item, f->data)) {
180     f->ret = item;
181     return FALSE;
182   }
183   return TRUE;
184 }
185
186 static struct NiceStreamItem *
187 _nice_stream_item_find (GstWebRTCNice * ice, NiceStreamItemFindFunc func,
188     gpointer data)
189 {
190   struct nice_find f;
191
192   f.func = func;
193   f.data = data;
194   f.ret = NULL;
195
196   _nice_stream_item_foreach (ice, _find_nice_item, &f);
197
198   return f.ret;
199 }
200
201 #define NICE_MATCH_INIT { -1, -1, NULL }
202
203 static gboolean
204 _match (struct NiceStreamItem *item, struct NiceStreamItem *m)
205 {
206   if (m->session_id != -1 && m->session_id != item->session_id)
207     return FALSE;
208   if (m->nice_stream_id != -1 && m->nice_stream_id != item->nice_stream_id)
209     return FALSE;
210   if (m->stream != NULL && m->stream != item->stream)
211     return FALSE;
212
213   return TRUE;
214 }
215
216 static struct NiceStreamItem *
217 _find_item (GstWebRTCNice * ice, guint session_id, guint nice_stream_id,
218     GstWebRTCICEStream * stream)
219 {
220   struct NiceStreamItem m = NICE_MATCH_INIT;
221
222   m.session_id = session_id;
223   m.nice_stream_id = nice_stream_id;
224   m.stream = stream;
225
226   return _nice_stream_item_find (ice, (NiceStreamItemFindFunc) _match, &m);
227 }
228
229 static struct NiceStreamItem *
230 _create_nice_stream_item (GstWebRTCNice * ice, guint session_id)
231 {
232   struct NiceStreamItem item;
233
234   item.session_id = session_id;
235   item.nice_stream_id = nice_agent_add_stream (ice->priv->nice_agent, 1);
236   item.stream =
237       GST_WEBRTC_ICE_STREAM (gst_webrtc_nice_stream_new (GST_WEBRTC_ICE (ice),
238           item.nice_stream_id)
239       );
240
241   g_array_append_val (ice->priv->nice_stream_map, item);
242
243   return _find_item (ice, item.session_id, item.nice_stream_id, item.stream);
244 }
245
246 static void
247 _parse_userinfo (const gchar * userinfo, gchar ** user, gchar ** pass)
248 {
249   const gchar *colon;
250
251   if (!userinfo) {
252     *user = NULL;
253     *pass = NULL;
254     return;
255   }
256
257   colon = g_strstr_len (userinfo, -1, ":");
258   if (!colon) {
259     *user = g_uri_unescape_string (userinfo, NULL);
260     *pass = NULL;
261     return;
262   }
263
264   /* Check that the first occurence is also the last occurence */
265   if (colon != g_strrstr (userinfo, ":"))
266     GST_WARNING ("userinfo %s contains more than one ':', will assume that the "
267         "first ':' delineates user:pass. You should escape the user and pass "
268         "before adding to the URI.", userinfo);
269
270   *user = g_uri_unescape_segment (userinfo, colon, NULL);
271   *pass = g_uri_unescape_string (&colon[1], NULL);
272 }
273
274 struct resolve_host_data
275 {
276   GstWebRTCNice *ice;
277   char *host;
278   gboolean main_context_handled;
279   gpointer user_data;
280   GDestroyNotify notify;
281 };
282
283 static void
284 on_resolve_host (GResolver * resolver, GAsyncResult * res, gpointer user_data)
285 {
286   GTask *task = user_data;
287   struct resolve_host_data *rh;
288   GError *error = NULL;
289   GList *addresses;
290
291   rh = g_task_get_task_data (task);
292
293   if (!(addresses = g_resolver_lookup_by_name_finish (resolver, res, &error))) {
294     GST_ERROR ("failed to resolve: %s", error->message);
295     g_task_return_error (task, error);
296     g_object_unref (task);
297     return;
298   }
299
300   GST_DEBUG_OBJECT (rh->ice, "Resolved %d addresses for host %s with data %p",
301       g_list_length (addresses), rh->host, rh);
302
303   g_task_return_pointer (task, addresses,
304       (GDestroyNotify) g_resolver_free_addresses);
305   g_object_unref (task);
306 }
307
308 static void
309 free_resolve_host_data (struct resolve_host_data *rh)
310 {
311   GST_TRACE_OBJECT (rh->ice, "Freeing data %p for resolving host %s", rh,
312       rh->host);
313
314   if (rh->notify)
315     rh->notify (rh->user_data);
316
317   g_free (rh->host);
318   g_free (rh);
319 }
320
321 static struct resolve_host_data *
322 resolve_host_data_new (GstWebRTCNice * ice, const char *host)
323 {
324   struct resolve_host_data *rh = g_new0 (struct resolve_host_data, 1);
325
326   rh->ice = ice;
327   rh->host = g_strdup (host);
328
329   return rh;
330 }
331
332 static gboolean
333 resolve_host_main_cb (gpointer user_data)
334 {
335   GResolver *resolver = g_resolver_get_default ();
336   GTask *task = user_data;
337   struct resolve_host_data *rh;
338
339   rh = g_task_get_task_data (task);
340   /* no need to error anymore if the main context disappears and this task is
341    * not run */
342   rh->main_context_handled = TRUE;
343
344   GST_DEBUG_OBJECT (rh->ice, "Resolving host %s", rh->host);
345   g_resolver_lookup_by_name_async (resolver, rh->host, NULL,
346       (GAsyncReadyCallback) on_resolve_host, g_object_ref (task));
347
348   return G_SOURCE_REMOVE;
349 }
350
351 static void
352 error_task_if_unhandled (GTask * task)
353 {
354   struct resolve_host_data *rh;
355
356   rh = g_task_get_task_data (task);
357
358   if (!rh->main_context_handled) {
359     GST_DEBUG_OBJECT (rh->ice, "host resolve for %s with data %p was never "
360         "executed, main context quit?", rh->host, rh);
361     g_task_return_new_error (task, G_IO_ERROR, G_IO_ERROR_CANCELLED, "%s",
362         "Cancelled");
363   }
364
365   g_object_unref (task);
366 }
367
368 static void
369 resolve_host_async (GstWebRTCNice * ice, const gchar * host,
370     GAsyncReadyCallback cb, gpointer user_data, GDestroyNotify notify)
371 {
372   struct resolve_host_data *rh = resolve_host_data_new (ice, host);
373   GTask *task;
374
375   rh->user_data = user_data;
376   rh->notify = notify;
377   task = g_task_new (rh->ice, NULL, cb, user_data);
378
379   g_task_set_task_data (task, rh, (GDestroyNotify) free_resolve_host_data);
380
381   GST_TRACE_OBJECT (rh->ice, "invoking main context for resolving host %s "
382       "with data %p", host, rh);
383   g_main_context_invoke_full (ice->priv->main_context, G_PRIORITY_DEFAULT,
384       resolve_host_main_cb, task, (GDestroyNotify) error_task_if_unhandled);
385 }
386
387 static GList *
388 resolve_host_finish (GstWebRTCNice * ice, GAsyncResult * res, GError ** error)
389 {
390   g_return_val_if_fail (g_task_is_valid (res, ice), NULL);
391
392   return g_task_propagate_pointer (G_TASK (res), error);
393 }
394
395 static void
396 _add_turn_server (GstWebRTCNice * ice, struct NiceStreamItem *item,
397     GstUri * turn_server)
398 {
399   GstWebRTCNice *nice = GST_WEBRTC_NICE (ice);
400   const gchar *host;
401   NiceRelayType relays[4] = { 0, };
402   gchar *user, *pass;
403   const gchar *userinfo, *transport, *scheme;
404   int i, relay_n = 0;
405
406   host = gst_uri_get_host (turn_server);
407   if (!host) {
408     GST_ERROR_OBJECT (ice, "Turn server has no host");
409     return;
410   }
411
412   scheme = gst_uri_get_scheme (turn_server);
413   transport = gst_uri_get_query_value (turn_server, "transport");
414   userinfo = gst_uri_get_userinfo (turn_server);
415   _parse_userinfo (userinfo, &user, &pass);
416
417   if (g_strcmp0 (scheme, "turns") == 0) {
418     relays[relay_n++] = NICE_RELAY_TYPE_TURN_TLS;
419   } else if (g_strcmp0 (scheme, "turn") == 0) {
420     if (!transport || g_strcmp0 (transport, "udp") == 0)
421       relays[relay_n++] = NICE_RELAY_TYPE_TURN_UDP;
422     if (!transport || g_strcmp0 (transport, "tcp") == 0)
423       relays[relay_n++] = NICE_RELAY_TYPE_TURN_TCP;
424   }
425   g_assert (relay_n < G_N_ELEMENTS (relays));
426
427   for (i = 0; i < relay_n; i++) {
428     if (!nice_agent_set_relay_info (nice->priv->nice_agent,
429             item->nice_stream_id, NICE_COMPONENT_TYPE_RTP,
430             gst_uri_get_host (turn_server), gst_uri_get_port (turn_server),
431             user, pass, relays[i])) {
432       gchar *uri_str = gst_uri_to_string (turn_server);
433       GST_ERROR_OBJECT (ice, "Could not set TURN server %s on libnice",
434           uri_str);
435       g_free (uri_str);
436     }
437   }
438
439   g_free (user);
440   g_free (pass);
441
442 }
443
444 typedef struct
445 {
446   GstWebRTCNice *ice;
447   struct NiceStreamItem *item;
448 } AddTurnServerData;
449
450 static void
451 _add_turn_server_func (const gchar * uri, GstUri * turn_server,
452     AddTurnServerData * data)
453 {
454   _add_turn_server (data->ice, data->item, turn_server);
455 }
456
457 static void
458 _add_stun_server (GstWebRTCNice * ice, GstUri * stun_server)
459 {
460   const gchar *msg = "must be of the form stun://<host>:<port>";
461   const gchar *host;
462   gchar *s = NULL;
463   guint port;
464
465   s = gst_uri_to_string (stun_server);
466   GST_DEBUG_OBJECT (ice, "adding stun server, %s", s);
467
468   host = gst_uri_get_host (stun_server);
469   if (!host) {
470     GST_ERROR_OBJECT (ice, "Stun server '%s' has no host, %s", s, msg);
471     goto out;
472   }
473
474   port = gst_uri_get_port (stun_server);
475   if (port == GST_URI_NO_PORT) {
476     GST_INFO_OBJECT (ice, "Stun server '%s' has no port, assuming 3478", s);
477     port = 3478;
478     gst_uri_set_port (stun_server, port);
479   }
480
481   g_object_set (ice->priv->nice_agent, "stun-server", host,
482       "stun-server-port", port, NULL);
483
484 out:
485   g_free (s);
486 }
487
488 static GstWebRTCICEStream *
489 gst_webrtc_nice_add_stream (GstWebRTCICE * ice, guint session_id)
490 {
491   struct NiceStreamItem m = NICE_MATCH_INIT;
492   struct NiceStreamItem *item;
493   AddTurnServerData add_data;
494   GstWebRTCNice *nice = GST_WEBRTC_NICE (ice);
495
496   m.session_id = session_id;
497   item = _nice_stream_item_find (nice, (NiceStreamItemFindFunc) _match, &m);
498   if (item) {
499     GST_ERROR_OBJECT (nice, "stream already added with session_id=%u",
500         session_id);
501     return 0;
502   }
503
504   if (nice->priv->stun_server) {
505     _add_stun_server (nice, nice->priv->stun_server);
506   }
507
508   item = _create_nice_stream_item (nice, session_id);
509
510   if (nice->priv->turn_server) {
511     _add_turn_server (nice, item, nice->priv->turn_server);
512   }
513
514   add_data.ice = nice;
515   add_data.item = item;
516
517   g_hash_table_foreach (nice->priv->turn_servers,
518       (GHFunc) _add_turn_server_func, &add_data);
519
520   return item->stream;
521 }
522
523 static void
524 _on_new_candidate (NiceAgent * agent, NiceCandidate * candidate,
525     GstWebRTCNice * ice)
526 {
527   struct NiceStreamItem *item;
528   gchar *attr;
529
530   item = _find_item (ice, -1, candidate->stream_id, NULL);
531   if (!item) {
532     GST_WARNING_OBJECT (ice, "received signal for non-existent stream %u",
533         candidate->stream_id);
534     return;
535   }
536
537   if (!candidate->username || !candidate->password) {
538     gboolean got_credentials;
539     gchar *ufrag, *password;
540
541     got_credentials = nice_agent_get_local_credentials (ice->priv->nice_agent,
542         candidate->stream_id, &ufrag, &password);
543     g_warn_if_fail (got_credentials);
544
545     if (!candidate->username)
546       candidate->username = ufrag;
547     else
548       g_free (ufrag);
549
550     if (!candidate->password)
551       candidate->password = password;
552     else
553       g_free (password);
554   }
555
556   attr = nice_agent_generate_local_candidate_sdp (agent, candidate);
557
558   if (ice->priv->on_candidate)
559     ice->priv->on_candidate (GST_WEBRTC_ICE (ice), item->session_id, attr,
560         ice->priv->on_candidate_data);
561
562   g_free (attr);
563 }
564
565 static GstWebRTCICETransport *
566 gst_webrtc_nice_find_transport (GstWebRTCICE * ice, GstWebRTCICEStream * stream,
567     GstWebRTCICEComponent component)
568 {
569   struct NiceStreamItem *item;
570   GstWebRTCNice *nice = GST_WEBRTC_NICE (ice);
571
572   item = _find_item (nice, -1, -1, stream);
573   g_return_val_if_fail (item != NULL, NULL);
574
575   return gst_webrtc_ice_stream_find_transport (item->stream, component);
576 }
577
578 #if 0
579 /* TODO don't rely on libnice to (de)serialize candidates */
580 static NiceCandidateType
581 _candidate_type_from_string (const gchar * s)
582 {
583   if (g_strcmp0 (s, "host") == 0) {
584     return NICE_CANDIDATE_TYPE_HOST;
585   } else if (g_strcmp0 (s, "srflx") == 0) {
586     return NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE;
587   } else if (g_strcmp0 (s, "prflx") == 0) {     /* FIXME: is the right string? */
588     return NICE_CANDIDATE_TYPE_PEER_REFLEXIVE;
589   } else if (g_strcmp0 (s, "relay") == 0) {
590     return NICE_CANDIDATE_TYPE_RELAY;
591   } else {
592     g_assert_not_reached ();
593     return 0;
594   }
595 }
596
597 static const gchar *
598 _candidate_type_to_string (NiceCandidateType type)
599 {
600   switch (type) {
601     case NICE_CANDIDATE_TYPE_HOST:
602       return "host";
603     case NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE:
604       return "srflx";
605     case NICE_CANDIDATE_TYPE_PEER_REFLEXIVE:
606       return "prflx";
607     case NICE_CANDIDATE_TYPE_RELAY:
608       return "relay";
609     default:
610       g_assert_not_reached ();
611       return NULL;
612   }
613 }
614
615 static NiceCandidateTransport
616 _candidate_transport_from_string (const gchar * s)
617 {
618   if (g_strcmp0 (s, "UDP") == 0) {
619     return NICE_CANDIDATE_TRANSPORT_UDP;
620   } else if (g_strcmp0 (s, "TCP tcptype") == 0) {
621     return NICE_CANDIDATE_TRANSPORT_TCP_ACTIVE;
622   } else if (g_strcmp0 (s, "tcp-passive") == 0) {       /* FIXME: is the right string? */
623     return NICE_CANDIDATE_TRANSPORT_TCP_PASSIVE;
624   } else if (g_strcmp0 (s, "tcp-so") == 0) {
625     return NICE_CANDIDATE_TRANSPORT_TCP_SO;
626   } else {
627     g_assert_not_reached ();
628     return 0;
629   }
630 }
631
632 static const gchar *
633 _candidate_type_to_string (NiceCandidateType type)
634 {
635   switch (type) {
636     case NICE_CANDIDATE_TYPE_HOST:
637       return "host";
638     case NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE:
639       return "srflx";
640     case NICE_CANDIDATE_TYPE_PEER_REFLEXIVE:
641       return "prflx";
642     case NICE_CANDIDATE_TYPE_RELAY:
643       return "relay";
644     default:
645       g_assert_not_reached ();
646       return NULL;
647   }
648 }
649 #endif
650
651 /* parse the address for possible resolution */
652 static gboolean
653 get_candidate_address (const gchar * candidate, gchar ** prefix,
654     gchar ** address, gchar ** postfix)
655 {
656   char **tokens = NULL;
657   char *tmp_address = NULL;
658
659   if (!g_str_has_prefix (candidate, "a=candidate:")) {
660     GST_ERROR ("candidate \"%s\" does not start with \"a=candidate:\"",
661         candidate);
662     goto failure;
663   }
664
665   if (!(tokens = g_strsplit (candidate, " ", 6))) {
666     GST_ERROR ("candidate \"%s\" could not be tokenized", candidate);
667     goto failure;
668   }
669
670   if (g_strv_length (tokens) < 6) {
671     GST_ERROR ("candidate \"%s\" tokenization resulted in not enough tokens",
672         candidate);
673     goto failure;
674   }
675
676   tmp_address = tokens[4];
677   if (address)
678     *address = g_strdup (tmp_address);
679   tokens[4] = NULL;
680
681   if (prefix)
682     *prefix = g_strjoinv (" ", tokens);
683   if (postfix)
684     *postfix = g_strdup (tokens[5]);
685
686   tokens[4] = tmp_address;
687
688   g_strfreev (tokens);
689   return TRUE;
690
691 failure:
692   if (tokens)
693     g_strfreev (tokens);
694   return FALSE;
695 }
696
697 struct resolve_candidate_data
698 {
699   guint nice_stream_id;
700   char *prefix;
701   char *postfix;
702 };
703
704 static void
705 free_resolve_candidate_data (struct resolve_candidate_data *rc)
706 {
707   g_free (rc->prefix);
708   g_free (rc->postfix);
709   g_free (rc);
710 }
711
712 static void
713 add_ice_candidate_to_libnice (GstWebRTCICE * ice, guint nice_stream_id,
714     NiceCandidate * cand)
715 {
716   GSList *candidates = NULL;
717   GstWebRTCNice *nice = GST_WEBRTC_NICE (ice);
718
719   if (cand->component_id == 2) {
720     /* we only support rtcp-mux so rtcp candidates are useless for us */
721     GST_INFO_OBJECT (ice, "Dropping RTCP candidate");
722     return;
723   }
724
725   candidates = g_slist_append (candidates, cand);
726
727   nice_agent_set_remote_candidates (nice->priv->nice_agent, nice_stream_id,
728       cand->component_id, candidates);
729
730   g_slist_free (candidates);
731 }
732
733 static void
734 on_candidate_resolved (GstWebRTCICE * ice, GAsyncResult * res,
735     gpointer user_data)
736 {
737   struct resolve_candidate_data *rc = user_data;
738   GError *error = NULL;
739   GList *addresses;
740   char *new_candv[4] = { NULL, };
741   char *new_addr, *new_candidate;
742   NiceCandidate *cand;
743   GstWebRTCNice *nice = GST_WEBRTC_NICE (ice);
744
745   if (!(addresses = resolve_host_finish (nice, res, &error))) {
746     GST_WARNING_OBJECT (ice, "Could not resolve candidate address: %s",
747         error->message);
748     g_clear_error (&error);
749     return;
750   }
751
752   new_addr = g_inet_address_to_string (addresses->data);
753
754   new_candv[0] = rc->prefix;
755   new_candv[1] = new_addr;
756   new_candv[2] = rc->postfix;
757   new_candv[3] = NULL;
758   new_candidate = g_strjoinv (" ", new_candv);
759
760   GST_DEBUG_OBJECT (ice, "resolved to candidate %s", new_candidate);
761
762   cand =
763       nice_agent_parse_remote_candidate_sdp (nice->priv->nice_agent,
764       rc->nice_stream_id, new_candidate);
765   g_free (new_candidate);
766   if (!cand) {
767     GST_WARNING_OBJECT (ice, "Could not parse candidate \'%s\'", new_candidate);
768     return;
769   }
770
771   g_free (new_addr);
772
773   add_ice_candidate_to_libnice (ice, rc->nice_stream_id, cand);
774   nice_candidate_free (cand);
775 }
776
777 /* candidate must start with "a=candidate:" or be NULL*/
778 static void
779 gst_webrtc_nice_add_candidate (GstWebRTCICE * ice, GstWebRTCICEStream * stream,
780     const gchar * candidate)
781 {
782   struct NiceStreamItem *item;
783   NiceCandidate *cand;
784   GstWebRTCNice *nice = GST_WEBRTC_NICE (ice);
785
786   item = _find_item (nice, -1, -1, stream);
787   g_return_if_fail (item != NULL);
788
789   if (candidate == NULL) {
790     nice_agent_peer_candidate_gathering_done (nice->priv->nice_agent,
791         item->nice_stream_id);
792     return;
793   }
794
795   cand =
796       nice_agent_parse_remote_candidate_sdp (nice->priv->nice_agent,
797       item->nice_stream_id, candidate);
798   if (!cand) {
799     /* might be a .local candidate */
800     char *prefix = NULL, *address = NULL, *postfix = NULL;
801     struct resolve_candidate_data *rc;
802
803     if (!get_candidate_address (candidate, &prefix, &address, &postfix)) {
804       GST_WARNING_OBJECT (nice, "Failed to retrieve address from candidate %s",
805           candidate);
806       goto done;
807     }
808
809     if (!g_str_has_suffix (address, ".local")) {
810       GST_WARNING_OBJECT (nice, "candidate address \'%s\' does not end "
811           "with \'.local\'", address);
812       goto done;
813     }
814
815     rc = g_new0 (struct resolve_candidate_data, 1);
816     rc->nice_stream_id = item->nice_stream_id;
817     rc->prefix = prefix;
818     rc->postfix = postfix;
819     resolve_host_async (nice, address,
820         (GAsyncReadyCallback) on_candidate_resolved, rc,
821         (GDestroyNotify) free_resolve_candidate_data);
822
823     prefix = NULL;
824     postfix = NULL;
825
826   done:
827     g_clear_pointer (&address, g_free);
828     g_clear_pointer (&prefix, g_free);
829     g_clear_pointer (&postfix, g_free);
830
831     return;
832   }
833
834   add_ice_candidate_to_libnice (ice, item->nice_stream_id, cand);
835   nice_candidate_free (cand);
836 }
837
838 static gboolean
839 gst_webrtc_nice_set_remote_credentials (GstWebRTCICE * ice,
840     GstWebRTCICEStream * stream, const gchar * ufrag, const gchar * pwd)
841 {
842   struct NiceStreamItem *item;
843   GstWebRTCNice *nice = GST_WEBRTC_NICE (ice);
844
845   g_return_val_if_fail (ufrag != NULL, FALSE);
846   g_return_val_if_fail (pwd != NULL, FALSE);
847   item = _find_item (nice, -1, -1, stream);
848   g_return_val_if_fail (item != NULL, FALSE);
849
850   GST_DEBUG_OBJECT (nice, "Setting remote ICE credentials on "
851       "ICE stream %u ufrag:%s pwd:%s", item->nice_stream_id, ufrag, pwd);
852
853   nice_agent_set_remote_credentials (nice->priv->nice_agent,
854       item->nice_stream_id, ufrag, pwd);
855
856   return TRUE;
857 }
858
859 typedef struct
860 {
861   GstWebRTCNice *ice;
862   GstUri *turn_server;
863 } AddTurnServerToStreamData;
864
865 static gboolean
866 _add_turn_server_foreach_stream_func (struct NiceStreamItem *item,
867     gpointer data)
868 {
869   AddTurnServerToStreamData *add_data = (AddTurnServerToStreamData *) data;
870   _add_turn_server (add_data->ice, item, add_data->turn_server);
871   return TRUE;
872 }
873
874 static gboolean
875 gst_webrtc_nice_add_turn_server (GstWebRTCICE * ice, const gchar * uri)
876 {
877   gboolean ret = FALSE;
878   GstUri *valid_uri;
879   GstWebRTCNice *nice = GST_WEBRTC_NICE (ice);
880   gboolean inserted;
881   AddTurnServerToStreamData add_data;
882
883   if (!(valid_uri = _validate_turn_server (nice, uri)))
884     goto done;
885
886   inserted =
887       g_hash_table_insert (nice->priv->turn_servers, g_strdup (uri), valid_uri);
888
889   /* add the turn server to any streams that were already created */
890   if (inserted) {
891     add_data.ice = nice;
892     add_data.turn_server = valid_uri;
893     _nice_stream_item_foreach (nice, _add_turn_server_foreach_stream_func,
894         &add_data);
895   }
896
897   ret = TRUE;
898
899 done:
900   return ret;
901 }
902
903 static gboolean
904 gst_webrtc_nice_add_local_ip_address (GstWebRTCNice * ice,
905     const gchar * address)
906 {
907   gboolean ret = FALSE;
908   NiceAddress nice_addr;
909
910   nice_address_init (&nice_addr);
911
912   ret = nice_address_set_from_string (&nice_addr, address);
913
914   if (ret) {
915     ret = nice_agent_add_local_address (ice->priv->nice_agent, &nice_addr);
916     if (!ret) {
917       GST_ERROR_OBJECT (ice, "Failed to add local address to NiceAgent");
918     }
919   } else {
920     GST_ERROR_OBJECT (ice, "Failed to initialize NiceAddress [%s]", address);
921   }
922
923   return ret;
924 }
925
926 static gboolean
927 gst_webrtc_nice_set_local_credentials (GstWebRTCICE * ice,
928     GstWebRTCICEStream * stream, const gchar * ufrag, const gchar * pwd)
929 {
930   struct NiceStreamItem *item;
931   GstWebRTCNice *nice = GST_WEBRTC_NICE (ice);
932
933   g_return_val_if_fail (ufrag != NULL, FALSE);
934   g_return_val_if_fail (pwd != NULL, FALSE);
935   item = _find_item (nice, -1, -1, stream);
936   g_return_val_if_fail (item != NULL, FALSE);
937
938   GST_DEBUG_OBJECT (nice, "Setting local ICE credentials on "
939       "ICE stream %u ufrag:%s pwd:%s", item->nice_stream_id, ufrag, pwd);
940
941   nice_agent_set_local_credentials (nice->priv->nice_agent,
942       item->nice_stream_id, ufrag, pwd);
943
944   return TRUE;
945 }
946
947 static gboolean
948 gst_webrtc_nice_gather_candidates (GstWebRTCICE * ice,
949     GstWebRTCICEStream * stream)
950 {
951   struct NiceStreamItem *item;
952   GstWebRTCNice *nice = GST_WEBRTC_NICE (ice);
953
954   item = _find_item (nice, -1, -1, stream);
955   g_return_val_if_fail (item != NULL, FALSE);
956
957   GST_DEBUG_OBJECT (nice, "gather candidates for stream %u",
958       item->nice_stream_id);
959
960   return gst_webrtc_ice_stream_gather_candidates (stream);
961 }
962
963 static void
964 gst_webrtc_nice_set_is_controller (GstWebRTCICE * ice, gboolean controller)
965 {
966   GstWebRTCNice *nice = GST_WEBRTC_NICE (ice);
967   g_object_set (G_OBJECT (nice->priv->nice_agent), "controlling-mode",
968       controller, NULL);
969 }
970
971 static gboolean
972 gst_webrtc_nice_get_is_controller (GstWebRTCICE * ice)
973 {
974   gboolean ret;
975   GstWebRTCNice *nice = GST_WEBRTC_NICE (ice);
976   g_object_get (G_OBJECT (nice->priv->nice_agent), "controlling-mode",
977       &ret, NULL);
978   return ret;
979 }
980
981 static void
982 gst_webrtc_nice_set_force_relay (GstWebRTCICE * ice, gboolean force_relay)
983 {
984   GstWebRTCNice *nice = GST_WEBRTC_NICE (ice);
985   g_object_set (G_OBJECT (nice->priv->nice_agent), "force-relay", force_relay,
986       NULL);
987 }
988
989 static void
990 gst_webrtc_nice_set_on_ice_candidate (GstWebRTCICE * ice,
991     GstWebRTCICEOnCandidateFunc func, gpointer user_data, GDestroyNotify notify)
992 {
993   GstWebRTCNice *nice = GST_WEBRTC_NICE (ice);
994   if (nice->priv->on_candidate_notify)
995     nice->priv->on_candidate_notify (nice->priv->on_candidate_data);
996   nice->priv->on_candidate = NULL;
997
998   nice->priv->on_candidate = func;
999   nice->priv->on_candidate_data = user_data;
1000   nice->priv->on_candidate_notify = notify;
1001 }
1002
1003 static void
1004 gst_webrtc_nice_set_tos (GstWebRTCICE * ice, GstWebRTCICEStream * stream,
1005     guint tos)
1006 {
1007   struct NiceStreamItem *item;
1008   GstWebRTCNice *nice = GST_WEBRTC_NICE (ice);
1009
1010   item = _find_item (nice, -1, -1, stream);
1011   g_return_if_fail (item != NULL);
1012
1013   nice_agent_set_stream_tos (nice->priv->nice_agent, item->nice_stream_id, tos);
1014 }
1015
1016 static const gchar *
1017 _relay_type_to_string (GstUri * turn_server)
1018 {
1019   const gchar *scheme;
1020   const gchar *transport;
1021
1022   if (!turn_server)
1023     return "none";
1024
1025   scheme = gst_uri_get_scheme (turn_server);
1026   transport = gst_uri_get_query_value (turn_server, "transport");
1027
1028   if (g_strcmp0 (scheme, "turns") == 0) {
1029     return "tls";
1030   } else if (g_strcmp0 (scheme, "turn") == 0) {
1031     if (!transport || g_strcmp0 (transport, "udp") == 0)
1032       return "udp";
1033     if (!transport || g_strcmp0 (transport, "tcp") == 0)
1034       return "tcp";
1035   }
1036
1037   return "none";
1038 }
1039
1040 static gchar *
1041 _get_server_url (GstWebRTCNice * ice, NiceCandidate * cand)
1042 {
1043   switch (cand->type) {
1044     case NICE_CANDIDATE_TYPE_RELAYED:{
1045       NiceAddress addr;
1046       gchar ipaddr[NICE_ADDRESS_STRING_LEN];
1047       nice_candidate_relay_address (cand, &addr);
1048       nice_address_to_string (&addr, ipaddr);
1049       return g_strdup (ipaddr);
1050     }
1051     case NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE:{
1052       NiceAddress addr;
1053       gchar ipaddr[NICE_ADDRESS_STRING_LEN];
1054       if (nice_candidate_stun_server_address (cand, &addr)) {
1055         nice_address_to_string (&addr, ipaddr);
1056         return g_strdup (ipaddr);
1057       } else {
1058         return g_strdup (gst_uri_get_host (ice->priv->stun_server));
1059       }
1060       return g_strdup (gst_uri_get_host (ice->priv->stun_server));
1061     }
1062     default:
1063       return g_strdup ("");
1064   }
1065 }
1066
1067 /* TODO: replace it with nice_candidate_type_to_string()
1068  * when it's ready for use
1069  * https://libnice.freedesktop.org/libnice/NiceCandidate.html#nice-candidate-type-to-string
1070  */
1071 static const gchar *
1072 _candidate_type_to_string (NiceCandidateType type)
1073 {
1074   switch (type) {
1075     case NICE_CANDIDATE_TYPE_HOST:
1076       return "host";
1077     case NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE:
1078       return "srflx";
1079     case NICE_CANDIDATE_TYPE_PEER_REFLEXIVE:
1080       return "prflx";
1081     case NICE_CANDIDATE_TYPE_RELAYED:
1082       return "relay";
1083     default:
1084       g_assert_not_reached ();
1085       return NULL;
1086   }
1087 }
1088
1089 static void
1090 _populate_candidate_stats (GstWebRTCNice * ice, NiceCandidate * cand,
1091     GstWebRTCICEStream * stream, GstWebRTCICECandidateStats * stats,
1092     gboolean is_local)
1093 {
1094   gchar ipaddr[INET6_ADDRSTRLEN];
1095
1096   g_assert (cand != NULL);
1097
1098   nice_address_to_string (&cand->addr, ipaddr);
1099   stats->port = nice_address_get_port (&cand->addr);
1100   stats->ipaddr = g_strdup (ipaddr);
1101   stats->stream_id = stream->stream_id;
1102   stats->type = _candidate_type_to_string (cand->type);
1103   stats->prio = cand->priority;
1104   stats->proto =
1105       cand->transport == NICE_CANDIDATE_TRANSPORT_UDP ? "udp" : "tcp";
1106   if (is_local) {
1107     if (cand->type == NICE_CANDIDATE_TYPE_RELAYED)
1108       stats->relay_proto = _relay_type_to_string (ice->priv->turn_server);
1109     stats->url = _get_server_url (ice, cand);
1110   }
1111 }
1112
1113 static void
1114 _populate_candidate_list_stats (GstWebRTCNice * ice, GSList * cands,
1115     GstWebRTCICEStream * stream, GPtrArray * result, gboolean is_local)
1116 {
1117   GSList *item;
1118
1119   for (item = cands; item != NULL; item = item->next) {
1120     GstWebRTCICECandidateStats *stats =
1121         g_malloc0 (sizeof (GstWebRTCICECandidateStats));
1122     NiceCandidate *c = item->data;
1123     _populate_candidate_stats (ice, c, stream, stats, is_local);
1124     g_ptr_array_add (result, stats);
1125   }
1126
1127   g_ptr_array_add (result, NULL);
1128 }
1129
1130 static GstWebRTCICECandidateStats **
1131 gst_webrtc_nice_get_local_candidates (GstWebRTCICE * ice,
1132     GstWebRTCICEStream * stream)
1133 {
1134   GstWebRTCNice *nice = GST_WEBRTC_NICE (ice);
1135   GSList *cands = NULL;
1136
1137   /* TODO: Use a g_ptr_array_new_null_terminated once when we depend on GLib 2.74 */
1138   GPtrArray *result = g_ptr_array_new ();
1139
1140   cands = nice_agent_get_local_candidates (nice->priv->nice_agent,
1141       stream->stream_id, NICE_COMPONENT_TYPE_RTP);
1142
1143   _populate_candidate_list_stats (nice, cands, stream, result, TRUE);
1144   g_slist_free_full (cands, (GDestroyNotify) nice_candidate_free);
1145
1146   return (GstWebRTCICECandidateStats **) g_ptr_array_free (result, FALSE);
1147 }
1148
1149 static GstWebRTCICECandidateStats **
1150 gst_webrtc_nice_get_remote_candidates (GstWebRTCICE * ice,
1151     GstWebRTCICEStream * stream)
1152 {
1153   GstWebRTCNice *nice = GST_WEBRTC_NICE (ice);
1154   GSList *cands = NULL;
1155
1156   /* TODO: Use a g_ptr_array_new_null_terminated once when we depend on GLib 2.74 */
1157   GPtrArray *result = g_ptr_array_new ();
1158
1159   cands = nice_agent_get_remote_candidates (nice->priv->nice_agent,
1160       stream->stream_id, NICE_COMPONENT_TYPE_RTP);
1161
1162   _populate_candidate_list_stats (nice, cands, stream, result, FALSE);
1163   g_slist_free_full (cands, (GDestroyNotify) nice_candidate_free);
1164
1165   return (GstWebRTCICECandidateStats **) g_ptr_array_free (result, FALSE);
1166 }
1167
1168 static gboolean
1169 gst_webrtc_nice_get_selected_pair (GstWebRTCICE * ice,
1170     GstWebRTCICEStream * stream, GstWebRTCICECandidateStats ** local_stats,
1171     GstWebRTCICECandidateStats ** remote_stats)
1172 {
1173   GstWebRTCNice *nice = GST_WEBRTC_NICE (ice);
1174   NiceCandidate *local_cand = NULL;
1175   NiceCandidate *remote_cand = NULL;
1176
1177
1178   if (stream) {
1179     if (nice_agent_get_selected_pair (nice->priv->nice_agent, stream->stream_id,
1180             NICE_COMPONENT_TYPE_RTP, &local_cand, &remote_cand)) {
1181       *local_stats = g_new0 (GstWebRTCICECandidateStats, 1);
1182       _populate_candidate_stats (nice, local_cand, stream, *local_stats, TRUE);
1183
1184       *remote_stats = g_new0 (GstWebRTCICECandidateStats, 1);
1185       _populate_candidate_stats (nice, remote_cand, stream, *remote_stats,
1186           FALSE);
1187
1188       return TRUE;
1189     }
1190   }
1191
1192   return FALSE;
1193 }
1194
1195 static void
1196 _clear_ice_stream (struct NiceStreamItem *item)
1197 {
1198   GstWebRTCNice *ice = NULL;
1199
1200   if (!item)
1201     return;
1202
1203   if (item->stream) {
1204     g_object_get (item->stream, "ice", &ice, NULL);
1205
1206     if (ice != NULL) {
1207       g_signal_handlers_disconnect_by_data (ice->priv->nice_agent,
1208           item->stream);
1209       gst_object_unref (ice);
1210     }
1211     gst_object_unref (item->stream);
1212   }
1213 }
1214
1215 static GstUri *
1216 _validate_turn_server (GstWebRTCNice * ice, const gchar * s)
1217 {
1218   GstUri *uri = gst_uri_from_string_escaped (s);
1219   const gchar *userinfo, *scheme;
1220   GList *keys = NULL, *l;
1221   gchar *user = NULL, *pass = NULL;
1222   gboolean turn_tls = FALSE;
1223   guint port;
1224
1225   GST_DEBUG_OBJECT (ice, "validating turn server, %s", s);
1226
1227   if (!uri) {
1228     GST_ERROR_OBJECT (ice, "Could not parse turn server '%s'", s);
1229     return NULL;
1230   }
1231
1232   scheme = gst_uri_get_scheme (uri);
1233   if (g_strcmp0 (scheme, "turn") == 0) {
1234   } else if (g_strcmp0 (scheme, "turns") == 0) {
1235     turn_tls = TRUE;
1236   } else {
1237     GST_ERROR_OBJECT (ice, "unknown scheme '%s'", scheme);
1238     goto out;
1239   }
1240
1241   keys = gst_uri_get_query_keys (uri);
1242   for (l = keys; l; l = l->next) {
1243     gchar *key = l->data;
1244
1245     if (g_strcmp0 (key, "transport") == 0) {
1246       const gchar *transport = gst_uri_get_query_value (uri, "transport");
1247       if (!transport) {
1248       } else if (g_strcmp0 (transport, "udp") == 0) {
1249       } else if (g_strcmp0 (transport, "tcp") == 0) {
1250       } else {
1251         GST_ERROR_OBJECT (ice, "unknown transport value, '%s'", transport);
1252         goto out;
1253       }
1254     } else {
1255       GST_ERROR_OBJECT (ice, "unknown query key, '%s'", key);
1256       goto out;
1257     }
1258   }
1259
1260   /* TODO: Implement error checking similar to the stun server below */
1261   userinfo = gst_uri_get_userinfo (uri);
1262   _parse_userinfo (userinfo, &user, &pass);
1263   if (!user) {
1264     GST_ERROR_OBJECT (ice, "No username specified in '%s'", s);
1265     goto out;
1266   }
1267   if (!pass) {
1268     GST_ERROR_OBJECT (ice, "No password specified in '%s'", s);
1269     goto out;
1270   }
1271
1272   port = gst_uri_get_port (uri);
1273
1274   if (port == GST_URI_NO_PORT) {
1275     if (turn_tls) {
1276       gst_uri_set_port (uri, 5349);
1277     } else {
1278       gst_uri_set_port (uri, 3478);
1279     }
1280   }
1281
1282   g_list_free (keys);
1283   g_free (user);
1284   g_free (pass);
1285
1286   return uri;
1287
1288 out:
1289   g_list_free (keys);
1290   g_free (user);
1291   g_free (pass);
1292   gst_uri_unref (uri);
1293
1294   return NULL;
1295 }
1296
1297 static void
1298 on_http_proxy_resolved (GstWebRTCICE * ice, GAsyncResult * res,
1299     gpointer user_data)
1300 {
1301   GstWebRTCNice *nice = GST_WEBRTC_NICE (ice);
1302   GstUri *uri = user_data;
1303   GList *addresses;
1304   GError *error = NULL;
1305   const gchar *userinfo;
1306   gchar *user = NULL;
1307   gchar *pass = NULL;
1308   gchar *ip = NULL;
1309   guint port = GST_URI_NO_PORT;
1310
1311   if (!(addresses = resolve_host_finish (nice, res, &error))) {
1312     GST_WARNING_OBJECT (ice, "Failed to resolve http proxy: %s",
1313         error->message);
1314     g_clear_error (&error);
1315     return;
1316   }
1317
1318   /* XXX: only the first IP is used */
1319   ip = g_inet_address_to_string (addresses->data);
1320
1321   if (!ip) {
1322     GST_ERROR_OBJECT (ice, "failed to resolve host for proxy");
1323     gst_uri_unref (uri);
1324     return;
1325   }
1326
1327   port = gst_uri_get_port (uri);
1328   if (port == GST_URI_NO_PORT) {
1329     port = HTTP_PROXY_PORT_DEFAULT;
1330     GST_DEBUG_OBJECT (ice, "Proxy server has no port, assuming %u",
1331         HTTP_PROXY_PORT_DEFAULT);
1332   }
1333
1334   userinfo = gst_uri_get_userinfo (uri);
1335   _parse_userinfo (userinfo, &user, &pass);
1336
1337   g_object_set (nice->priv->nice_agent,
1338       "proxy-ip", ip, "proxy-port", port, "proxy-type", NICE_PROXY_TYPE_HTTP,
1339       "proxy-username", user, "proxy-password", pass, NULL);
1340
1341   g_free (ip);
1342   g_free (user);
1343   g_free (pass);
1344 }
1345
1346 static GstUri *
1347 _set_http_proxy (GstWebRTCICE * ice, const gchar * s)
1348 {
1349   GstWebRTCNice *nice = GST_WEBRTC_NICE (ice);
1350   GstUri *uri = gst_uri_from_string_escaped (s);
1351   const gchar *msg =
1352       "must be of the form http://[username:password@]<host>[:<port>]";
1353   const gchar *host = NULL;
1354   const gchar *userinfo;
1355   gchar *user = NULL, *pass = NULL;
1356
1357   GST_DEBUG_OBJECT (ice, "setting http proxy %s", s);
1358
1359   if (!uri) {
1360     GST_ERROR_OBJECT (ice, "Couldn't parse http proxy uri '%s', %s", s, msg);
1361     return NULL;
1362   }
1363
1364   if (g_strcmp0 (gst_uri_get_scheme (uri), "http") != 0) {
1365     GST_ERROR_OBJECT (ice,
1366         "Couldn't parse uri scheme for http proxy server '%s', %s", s, msg);
1367     gst_uri_unref (uri);
1368     return NULL;
1369   }
1370
1371   host = gst_uri_get_host (uri);
1372   if (!host) {
1373     GST_ERROR_OBJECT (ice, "http proxy server '%s' has no host, %s", s, msg);
1374     gst_uri_unref (uri);
1375     return NULL;
1376   }
1377
1378   userinfo = gst_uri_get_userinfo (uri);
1379   _parse_userinfo (userinfo, &user, &pass);
1380   if ((pass && pass[0] != '\0') && (!user || user[0] == '\0')) {
1381     GST_ERROR_OBJECT (ice,
1382         "Password specified without user for http proxy '%s', %s", s, msg);
1383     uri = NULL;
1384     goto out;
1385   }
1386
1387   resolve_host_async (nice, host, (GAsyncReadyCallback) on_http_proxy_resolved,
1388       gst_uri_ref (uri), (GDestroyNotify) gst_uri_unref);
1389
1390 out:
1391   g_free (user);
1392   g_free (pass);
1393
1394   return uri;
1395 }
1396
1397 static void
1398 gst_webrtc_nice_set_stun_server (GstWebRTCICE * ice, const gchar * uri_s)
1399 {
1400   GstUri *uri = gst_uri_from_string_escaped (uri_s);
1401   const gchar *msg = "must be of the form stun://<host>:<port>";
1402   GstWebRTCNice *nice = GST_WEBRTC_NICE (ice);
1403
1404   GST_DEBUG_OBJECT (nice, "setting stun server, %s", uri_s);
1405
1406   if (!uri) {
1407     GST_ERROR_OBJECT (nice, "Couldn't parse stun server '%s', %s", uri_s, msg);
1408     return;
1409   }
1410
1411   if (nice->priv->stun_server)
1412     gst_uri_unref (nice->priv->stun_server);
1413   nice->priv->stun_server = uri;
1414 }
1415
1416 static gchar *
1417 gst_webrtc_nice_get_stun_server (GstWebRTCICE * ice)
1418 {
1419   GstWebRTCNice *nice = GST_WEBRTC_NICE (ice);
1420   if (nice->priv->stun_server)
1421     return gst_uri_to_string (nice->priv->stun_server);
1422   else
1423     return NULL;
1424 }
1425
1426 static void
1427 gst_webrtc_nice_set_turn_server (GstWebRTCICE * ice, const gchar * uri_s)
1428 {
1429   GstUri *uri;
1430   GstWebRTCNice *nice = GST_WEBRTC_NICE (ice);
1431   uri = _validate_turn_server (nice, uri_s);
1432
1433   if (uri) {
1434     if (nice->priv->turn_server)
1435       gst_uri_unref (nice->priv->turn_server);
1436     nice->priv->turn_server = uri;
1437   }
1438 }
1439
1440 static gchar *
1441 gst_webrtc_nice_get_turn_server (GstWebRTCICE * ice)
1442 {
1443   GstWebRTCNice *nice = GST_WEBRTC_NICE (ice);
1444   if (nice->priv->turn_server)
1445     return gst_uri_to_string (nice->priv->turn_server);
1446   else
1447     return NULL;
1448 }
1449
1450 static void
1451 gst_webrtc_nice_set_http_proxy (GstWebRTCICE * ice, const gchar * http_proxy)
1452 {
1453   GstWebRTCNice *nice = GST_WEBRTC_NICE (ice);
1454   GstUri *uri = _set_http_proxy (ice, http_proxy);
1455
1456   if (uri) {
1457     if (nice->priv->http_proxy)
1458       gst_uri_unref (nice->priv->http_proxy);
1459     nice->priv->http_proxy = uri;
1460   }
1461 }
1462
1463 static gchar *
1464 gst_webrtc_nice_get_http_proxy (GstWebRTCICE * ice)
1465 {
1466   GstWebRTCNice *nice = GST_WEBRTC_NICE (ice);
1467
1468   if (nice->priv->http_proxy)
1469     return gst_uri_to_string (nice->priv->http_proxy);
1470   else
1471     return NULL;
1472 }
1473
1474 static void
1475 gst_webrtc_nice_set_property (GObject * object, guint prop_id,
1476     const GValue * value, GParamSpec * pspec)
1477 {
1478   GstWebRTCICE *ice = GST_WEBRTC_ICE (object);
1479   GstWebRTCNice *nice = GST_WEBRTC_NICE (object);
1480
1481   switch (prop_id) {
1482     case PROP_ICE_TCP:
1483       g_object_set_property (G_OBJECT (nice->priv->nice_agent),
1484           "ice-tcp", value);
1485       break;
1486     case PROP_ICE_UDP:
1487       g_object_set_property (G_OBJECT (nice->priv->nice_agent),
1488           "ice-udp", value);
1489       break;
1490     case PROP_MIN_RTP_PORT:
1491       ice->min_rtp_port = g_value_get_uint (value);
1492       if (ice->min_rtp_port > ice->max_rtp_port)
1493         g_warning ("Set min-rtp-port to %u which is larger than"
1494             " max-rtp-port %u", ice->min_rtp_port, ice->max_rtp_port);
1495       break;
1496     case PROP_MAX_RTP_PORT:
1497       ice->max_rtp_port = g_value_get_uint (value);
1498       if (ice->min_rtp_port > ice->max_rtp_port)
1499         g_warning ("Set max-rtp-port to %u which is smaller than"
1500             " min-rtp-port %u", ice->max_rtp_port, ice->min_rtp_port);
1501       break;
1502     default:
1503       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1504       break;
1505   }
1506 }
1507
1508 static void
1509 gst_webrtc_nice_get_property (GObject * object, guint prop_id,
1510     GValue * value, GParamSpec * pspec)
1511 {
1512   GstWebRTCICE *ice = GST_WEBRTC_ICE (object);
1513   GstWebRTCNice *nice = GST_WEBRTC_NICE (object);
1514
1515   switch (prop_id) {
1516     case PROP_AGENT:
1517       g_value_set_object (value, nice->priv->nice_agent);
1518       break;
1519     case PROP_ICE_TCP:
1520       g_object_get_property (G_OBJECT (nice->priv->nice_agent),
1521           "ice-tcp", value);
1522       break;
1523     case PROP_ICE_UDP:
1524       g_object_get_property (G_OBJECT (nice->priv->nice_agent),
1525           "ice-udp", value);
1526       break;
1527     case PROP_MIN_RTP_PORT:
1528       g_value_set_uint (value, ice->min_rtp_port);
1529       break;
1530     case PROP_MAX_RTP_PORT:
1531       g_value_set_uint (value, ice->max_rtp_port);
1532       break;
1533     default:
1534       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1535       break;
1536   }
1537 }
1538
1539 static void
1540 gst_webrtc_nice_finalize (GObject * object)
1541 {
1542   GstWebRTCNice *ice = GST_WEBRTC_NICE (object);
1543
1544   g_signal_handlers_disconnect_by_data (ice->priv->nice_agent, ice);
1545
1546   _stop_thread (ice);
1547
1548   if (ice->priv->on_candidate_notify)
1549     ice->priv->on_candidate_notify (ice->priv->on_candidate_data);
1550   ice->priv->on_candidate = NULL;
1551   ice->priv->on_candidate_notify = NULL;
1552
1553   if (ice->priv->turn_server)
1554     gst_uri_unref (ice->priv->turn_server);
1555   if (ice->priv->stun_server)
1556     gst_uri_unref (ice->priv->stun_server);
1557   if (ice->priv->http_proxy)
1558     gst_uri_unref (ice->priv->http_proxy);
1559
1560   g_mutex_clear (&ice->priv->lock);
1561   g_cond_clear (&ice->priv->cond);
1562
1563   g_array_free (ice->priv->nice_stream_map, TRUE);
1564
1565   g_object_unref (ice->priv->nice_agent);
1566
1567   g_hash_table_unref (ice->priv->turn_servers);
1568
1569   G_OBJECT_CLASS (parent_class)->finalize (object);
1570 }
1571
1572 static void
1573 gst_webrtc_nice_constructed (GObject * object)
1574 {
1575   GstWebRTCNice *ice = GST_WEBRTC_NICE (object);
1576   NiceAgentOption options = 0;
1577
1578   _start_thread (ice);
1579
1580   options |= NICE_AGENT_OPTION_ICE_TRICKLE;
1581   options |= NICE_AGENT_OPTION_REGULAR_NOMINATION;
1582
1583   ice->priv->nice_agent = nice_agent_new_full (ice->priv->main_context,
1584       NICE_COMPATIBILITY_RFC5245, options);
1585   g_signal_connect (ice->priv->nice_agent, "new-candidate-full",
1586       G_CALLBACK (_on_new_candidate), ice);
1587
1588   G_OBJECT_CLASS (parent_class)->constructed (object);
1589 }
1590
1591 static void
1592 gst_webrtc_nice_class_init (GstWebRTCNiceClass * klass)
1593 {
1594   GstWebRTCICEClass *gst_webrtc_ice_class = GST_WEBRTC_ICE_CLASS (klass);
1595   GObjectClass *gobject_class = (GObjectClass *) klass;
1596
1597   // override virtual functions
1598   gst_webrtc_ice_class->add_candidate = gst_webrtc_nice_add_candidate;
1599   gst_webrtc_ice_class->add_stream = gst_webrtc_nice_add_stream;
1600   gst_webrtc_ice_class->add_turn_server = gst_webrtc_nice_add_turn_server;
1601   gst_webrtc_ice_class->find_transport = gst_webrtc_nice_find_transport;
1602   gst_webrtc_ice_class->gather_candidates = gst_webrtc_nice_gather_candidates;
1603   gst_webrtc_ice_class->get_is_controller = gst_webrtc_nice_get_is_controller;
1604   gst_webrtc_ice_class->get_stun_server = gst_webrtc_nice_get_stun_server;
1605   gst_webrtc_ice_class->get_turn_server = gst_webrtc_nice_get_turn_server;
1606   gst_webrtc_ice_class->get_http_proxy = gst_webrtc_nice_get_http_proxy;
1607   gst_webrtc_ice_class->set_force_relay = gst_webrtc_nice_set_force_relay;
1608   gst_webrtc_ice_class->set_is_controller = gst_webrtc_nice_set_is_controller;
1609   gst_webrtc_ice_class->set_local_credentials =
1610       gst_webrtc_nice_set_local_credentials;
1611   gst_webrtc_ice_class->set_remote_credentials =
1612       gst_webrtc_nice_set_remote_credentials;
1613   gst_webrtc_ice_class->set_stun_server = gst_webrtc_nice_set_stun_server;
1614   gst_webrtc_ice_class->set_tos = gst_webrtc_nice_set_tos;
1615   gst_webrtc_ice_class->set_turn_server = gst_webrtc_nice_set_turn_server;
1616   gst_webrtc_ice_class->set_http_proxy = gst_webrtc_nice_set_http_proxy;
1617   gst_webrtc_ice_class->set_on_ice_candidate =
1618       gst_webrtc_nice_set_on_ice_candidate;
1619   gst_webrtc_ice_class->get_local_candidates =
1620       gst_webrtc_nice_get_local_candidates;
1621   gst_webrtc_ice_class->get_remote_candidates =
1622       gst_webrtc_nice_get_remote_candidates;
1623   gst_webrtc_ice_class->get_selected_pair = gst_webrtc_nice_get_selected_pair;
1624
1625   gobject_class->constructed = gst_webrtc_nice_constructed;
1626   gobject_class->get_property = gst_webrtc_nice_get_property;
1627   gobject_class->set_property = gst_webrtc_nice_set_property;
1628   gobject_class->finalize = gst_webrtc_nice_finalize;
1629
1630   g_object_class_install_property (gobject_class,
1631       PROP_AGENT,
1632       g_param_spec_object ("agent", "ICE agent",
1633           "ICE agent in use by this object. WARNING! Accessing this property "
1634           "may have disastrous consequences for the operation of webrtcbin. "
1635           "Other ICE implementations may not have the same interface.",
1636           NICE_TYPE_AGENT, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
1637
1638   g_object_class_install_property (gobject_class,
1639       PROP_ICE_TCP,
1640       g_param_spec_boolean ("ice-tcp", "ICE TCP",
1641           "Whether the agent should use ICE-TCP when gathering candidates",
1642           TRUE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1643
1644   g_object_class_install_property (gobject_class,
1645       PROP_ICE_UDP,
1646       g_param_spec_boolean ("ice-udp", "ICE UDP",
1647           "Whether the agent should use ICE-UDP when gathering candidates",
1648           TRUE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1649
1650   g_signal_override_class_handler ("add-local-ip-address",
1651       G_TYPE_FROM_CLASS (klass),
1652       G_CALLBACK (gst_webrtc_nice_add_local_ip_address));
1653 }
1654
1655 static void
1656 gst_webrtc_nice_init (GstWebRTCNice * ice)
1657 {
1658   ice->priv = gst_webrtc_nice_get_instance_private (ice);
1659
1660   g_mutex_init (&ice->priv->lock);
1661   g_cond_init (&ice->priv->cond);
1662
1663   ice->priv->turn_servers =
1664       g_hash_table_new_full (g_str_hash, g_str_equal, g_free,
1665       (GDestroyNotify) gst_uri_unref);
1666
1667   ice->priv->nice_stream_map =
1668       g_array_new (FALSE, TRUE, sizeof (struct NiceStreamItem));
1669   g_array_set_clear_func (ice->priv->nice_stream_map,
1670       (GDestroyNotify) _clear_ice_stream);
1671 }
1672
1673 GstWebRTCNice *
1674 gst_webrtc_nice_new (const gchar * name)
1675 {
1676   return g_object_new (GST_TYPE_WEBRTC_NICE, "name", name, NULL);
1677 }