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