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