pjsip_scheduler.c: Fix some corner cases.
[asterisk/asterisk.git] / res / res_pjsip / pjsip_transport_management.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2014, Digium, Inc.
5  *
6  * Joshua Colp <jcolp@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 #include "asterisk.h"
20
21 #include <signal.h>
22
23 #include <pjsip.h>
24 #include <pjsip_ua.h>
25
26 #include "asterisk/res_pjsip.h"
27 #include "asterisk/module.h"
28 #include "asterisk/astobj2.h"
29 #include "include/res_pjsip_private.h"
30
31 /*! \brief Number of buckets for monitored transports */
32 #define TRANSPORTS_BUCKETS 127
33
34 #define IDLE_TIMEOUT (pjsip_cfg()->tsx.td)
35
36 /*! \brief The keep alive packet to send */
37 static const pj_str_t keepalive_packet = { "\r\n\r\n", 4 };
38
39 /*! \brief Global container of active transports */
40 static AO2_GLOBAL_OBJ_STATIC(monitored_transports);
41
42 /*! \brief Scheduler context for timing out connections with no data received */
43 static struct ast_sched_context *sched;
44
45 /*! \brief Thread keeping things alive */
46 static pthread_t keepalive_thread = AST_PTHREADT_NULL;
47
48 /*! \brief The global interval at which to send keepalives */
49 static unsigned int keepalive_interval;
50
51 /*! \brief Structure for transport to be monitored */
52 struct monitored_transport {
53         /*! \brief The underlying PJSIP transport */
54         pjsip_transport *transport;
55         /*! \brief Non-zero if a PJSIP request was received */
56         int sip_received;
57 };
58
59 /*! \brief Callback function to send keepalive */
60 static int keepalive_transport_cb(void *obj, void *arg, int flags)
61 {
62         struct monitored_transport *monitored = obj;
63         pjsip_tpselector selector = {
64                 .type = PJSIP_TPSELECTOR_TRANSPORT,
65                 .u.transport = monitored->transport,
66         };
67
68         pjsip_tpmgr_send_raw(pjsip_endpt_get_tpmgr(ast_sip_get_pjsip_endpoint()),
69                 monitored->transport->key.type, &selector, NULL, keepalive_packet.ptr, keepalive_packet.slen,
70                 &monitored->transport->key.rem_addr, pj_sockaddr_get_len(&monitored->transport->key.rem_addr),
71                 NULL, NULL);
72
73         return 0;
74 }
75
76 /*! \brief Thread which sends keepalives to all active connection-oriented transports */
77 static void *keepalive_transport_thread(void *data)
78 {
79         struct ao2_container *transports;
80         pj_thread_desc desc;
81         pj_thread_t *thread;
82
83         if (pj_thread_register("Asterisk Keepalive Thread", desc, &thread) != PJ_SUCCESS) {
84                 ast_log(LOG_ERROR, "Could not register keepalive thread with PJLIB, keepalives will not occur.\n");
85                 return NULL;
86         }
87
88         transports = ao2_global_obj_ref(monitored_transports);
89         if (!transports) {
90                 return NULL;
91         }
92
93         /* Once loaded this module just keeps on going as it is unsafe to stop and change the underlying
94          * callback for the transport manager.
95          */
96         while (keepalive_interval) {
97                 sleep(keepalive_interval);
98                 ao2_callback(transports, OBJ_NODATA, keepalive_transport_cb, NULL);
99         }
100
101         ao2_ref(transports, -1);
102         return NULL;
103 }
104
105 AST_THREADSTORAGE(desc_storage);
106
107 static int idle_sched_cb(const void *data)
108 {
109         struct monitored_transport *monitored = (struct monitored_transport *) data;
110
111         if (!pj_thread_is_registered()) {
112                 pj_thread_t *thread;
113                 pj_thread_desc *desc;
114
115                 desc = ast_threadstorage_get(&desc_storage, sizeof(pj_thread_desc));
116                 if (!desc) {
117                         ast_log(LOG_ERROR, "Could not get thread desc from thread-local storage.\n");
118                         ao2_ref(monitored, -1);
119                         return 0;
120                 }
121
122                 pj_bzero(*desc, sizeof(*desc));
123
124                 pj_thread_register("Transport Monitor", *desc, &thread);
125         }
126
127         if (!monitored->sip_received) {
128                 ast_log(LOG_NOTICE, "Shutting down transport '%s' since no request was received in %d seconds\n",
129                         monitored->transport->info, IDLE_TIMEOUT / 1000);
130                 pjsip_transport_shutdown(monitored->transport);
131         }
132
133         ao2_ref(monitored, -1);
134         return 0;
135 }
136
137 /*! \brief Destructor for keepalive transport */
138 static void monitored_transport_destroy(void *obj)
139 {
140         struct monitored_transport *monitored = obj;
141
142         pjsip_transport_dec_ref(monitored->transport);
143 }
144
145 /*! \brief Callback invoked when transport changes occur */
146 static void monitored_transport_state_callback(pjsip_transport *transport, pjsip_transport_state state,
147         const pjsip_transport_state_info *info)
148 {
149         struct ao2_container *transports;
150
151         /* We only care about reliable transports */
152         if (PJSIP_TRANSPORT_IS_RELIABLE(transport)
153                 && (transport->dir == PJSIP_TP_DIR_INCOMING || keepalive_interval)
154                 && (transports = ao2_global_obj_ref(monitored_transports))) {
155                 struct monitored_transport *monitored;
156
157                 switch (state) {
158                 case PJSIP_TP_STATE_CONNECTED:
159                         monitored = ao2_alloc_options(sizeof(*monitored),
160                                 monitored_transport_destroy, AO2_ALLOC_OPT_LOCK_NOLOCK);
161                         if (!monitored) {
162                                 break;
163                         }
164                         monitored->transport = transport;
165                         pjsip_transport_add_ref(monitored->transport);
166
167                         ao2_link(transports, monitored);
168
169                         if (transport->dir == PJSIP_TP_DIR_INCOMING) {
170                                 /* Let the scheduler inherit the reference from allocation */
171                                 if (ast_sched_add_variable(sched, IDLE_TIMEOUT, idle_sched_cb, monitored, 1) < 0) {
172                                         /* Uh Oh.  Could not schedule the idle check.  Kill the transport. */
173                                         pjsip_transport_shutdown(transport);
174                                 } else {
175                                         /* monitored ref successfully passed to idle_sched_cb() */
176                                         break;
177                                 }
178                         }
179                         ao2_ref(monitored, -1);
180                         break;
181                 case PJSIP_TP_STATE_SHUTDOWN:
182                 case PJSIP_TP_STATE_DISCONNECTED:
183                         ao2_find(transports, transport->obj_name, OBJ_SEARCH_KEY | OBJ_NODATA | OBJ_UNLINK);
184                         break;
185                 default:
186                         break;
187                 }
188
189                 ao2_ref(transports, -1);
190         }
191 }
192
193 struct ast_sip_tpmgr_state_callback monitored_transport_reg = {
194         monitored_transport_state_callback,
195 };
196
197 /*! \brief Hashing function for monitored transport */
198 static int monitored_transport_hash_fn(const void *obj, int flags)
199 {
200         const struct monitored_transport *object;
201         const char *key;
202
203         switch (flags & OBJ_SEARCH_MASK) {
204         case OBJ_SEARCH_KEY:
205                 key = obj;
206                 break;
207         case OBJ_SEARCH_OBJECT:
208                 object = obj;
209                 key = object->transport->obj_name;
210                 break;
211         default:
212                 /* Hash can only work on something with a full key. */
213                 ast_assert(0);
214                 return 0;
215         }
216         return ast_str_hash(key);
217 }
218
219 /*! \brief Comparison function for monitored transport */
220 static int monitored_transport_cmp_fn(void *obj, void *arg, int flags)
221 {
222         const struct monitored_transport *object_left = obj;
223         const struct monitored_transport *object_right = arg;
224         const char *right_key = arg;
225         int cmp;
226
227         switch (flags & OBJ_SEARCH_MASK) {
228         case OBJ_SEARCH_OBJECT:
229                 right_key = object_right->transport->obj_name;
230                 /* Fall through */
231         case OBJ_SEARCH_KEY:
232                 cmp = strcmp(object_left->transport->obj_name, right_key);
233                 break;
234         case OBJ_SEARCH_PARTIAL_KEY:
235                 /*
236                  * We could also use a partial key struct containing a length
237                  * so strlen() does not get called for every comparison instead.
238                  */
239                 cmp = strncmp(object_left->transport->obj_name, right_key, strlen(right_key));
240                 break;
241         default:
242                 /*
243                  * What arg points to is specific to this traversal callback
244                  * and has no special meaning to astobj2.
245                  */
246                 cmp = 0;
247                 break;
248         }
249
250         return !cmp ? CMP_MATCH : 0;
251 }
252
253 static void keepalive_global_loaded(const char *object_type)
254 {
255         unsigned int new_interval = ast_sip_get_keep_alive_interval();
256
257         if (new_interval) {
258                 keepalive_interval = new_interval;
259         } else if (keepalive_interval) {
260                 ast_log(LOG_NOTICE, "Keepalive support can not be disabled once activated.\n");
261                 return;
262         } else {
263                 /* This will occur if no keepalive interval has been specified at initial start */
264                 return;
265         }
266
267         if (keepalive_thread != AST_PTHREADT_NULL) {
268                 return;
269         }
270
271         if (ast_pthread_create(&keepalive_thread, NULL, keepalive_transport_thread, NULL)) {
272                 ast_log(LOG_ERROR, "Could not create thread for sending keepalive messages.\n");
273                 keepalive_thread = AST_PTHREADT_NULL;
274                 keepalive_interval = 0;
275         }
276 }
277
278 /*! \brief Observer which is used to update our interval when the global setting changes */
279 static struct ast_sorcery_observer keepalive_global_observer = {
280         .loaded = keepalive_global_loaded,
281 };
282
283 /*!
284  * \brief
285  * On incoming TCP connections, when we receive a SIP request, we mark that we have
286  * received a valid SIP request. This way, we will not shut the transport down for
287  * idleness
288  */
289 static pj_bool_t idle_monitor_on_rx_request(pjsip_rx_data *rdata)
290 {
291         struct ao2_container *transports;
292         struct monitored_transport *idle_trans;
293
294         transports = ao2_global_obj_ref(monitored_transports);
295         if (!transports) {
296                 return PJ_FALSE;
297         }
298
299         idle_trans = ao2_find(transports, rdata->tp_info.transport->obj_name, OBJ_SEARCH_KEY);
300         ao2_ref(transports, -1);
301         if (!idle_trans) {
302                 return PJ_FALSE;
303         }
304
305         idle_trans->sip_received = 1;
306         ao2_ref(idle_trans, -1);
307
308         return PJ_FALSE;
309 }
310
311 static pjsip_module idle_monitor_module = {
312         .name = {"idle monitor module", 19},
313         .priority = PJSIP_MOD_PRIORITY_TRANSPORT_LAYER + 3,
314         .on_rx_request = idle_monitor_on_rx_request,
315 };
316
317 int ast_sip_initialize_transport_management(void)
318 {
319         struct ao2_container *transports;
320
321         transports = ao2_container_alloc(TRANSPORTS_BUCKETS, monitored_transport_hash_fn,
322                 monitored_transport_cmp_fn);
323         if (!transports) {
324                 ast_log(LOG_ERROR, "Could not create container for transports to perform keepalive on.\n");
325                 return AST_MODULE_LOAD_DECLINE;
326         }
327         ao2_global_obj_replace_unref(monitored_transports, transports);
328         ao2_ref(transports, -1);
329
330         sched = ast_sched_context_create();
331         if (!sched) {
332                 ast_log(LOG_ERROR, "Failed to create keepalive scheduler context.\n");
333                 ao2_global_obj_release(monitored_transports);
334                 return AST_MODULE_LOAD_DECLINE;
335         }
336
337         if (ast_sched_start_thread(sched)) {
338                 ast_log(LOG_ERROR, "Failed to start keepalive scheduler thread\n");
339                 ast_sched_context_destroy(sched);
340                 sched = NULL;
341                 ao2_global_obj_release(monitored_transports);
342                 return AST_MODULE_LOAD_DECLINE;
343         }
344
345         ast_sip_register_service(&idle_monitor_module);
346
347         ast_sip_transport_state_register(&monitored_transport_reg);
348
349         ast_sorcery_observer_add(ast_sip_get_sorcery(), "global", &keepalive_global_observer);
350         ast_sorcery_reload_object(ast_sip_get_sorcery(), "global");
351
352         return AST_MODULE_LOAD_SUCCESS;
353 }
354
355 void ast_sip_destroy_transport_management(void)
356 {
357         if (keepalive_interval) {
358                 keepalive_interval = 0;
359                 if (keepalive_thread != AST_PTHREADT_NULL) {
360                         pthread_kill(keepalive_thread, SIGURG);
361                         pthread_join(keepalive_thread, NULL);
362                         keepalive_thread = AST_PTHREADT_NULL;
363                 }
364         }
365
366         ast_sorcery_observer_remove(ast_sip_get_sorcery(), "global", &keepalive_global_observer);
367
368         ast_sip_transport_state_unregister(&monitored_transport_reg);
369
370         ast_sip_unregister_service(&idle_monitor_module);
371
372         ast_sched_context_destroy(sched);
373         sched = NULL;
374
375         ao2_global_obj_release(monitored_transports);
376 }