862ae72168572a923e11d8c46ee1aa1f17f0b57c
[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 static int idle_sched_cb(const void *data)
105 {
106         struct monitored_transport *keepalive = (struct monitored_transport *) data;
107         int sip_received = ast_atomic_fetchadd_int(&keepalive->sip_received, 0);
108
109         if (!sip_received) {
110                 ast_log(LOG_NOTICE, "Shutting down transport '%s' since no request was received in %d seconds\n",
111                                 keepalive->transport->info, IDLE_TIMEOUT);
112                 pjsip_transport_shutdown(keepalive->transport);
113         }
114
115         ao2_ref(keepalive, -1);
116         return 0;
117 }
118
119 /*! \brief Destructor for keepalive transport */
120 static void monitored_transport_destroy(void *obj)
121 {
122         struct monitored_transport *keepalive = obj;
123
124         pjsip_transport_dec_ref(keepalive->transport);
125 }
126
127 /*! \brief Callback invoked when transport changes occur */
128 static void monitored_transport_state_callback(pjsip_transport *transport, pjsip_transport_state state,
129         const pjsip_transport_state_info *info)
130 {
131         /* We only care about reliable transports */
132         if (PJSIP_TRANSPORT_IS_RELIABLE(transport) &&
133                         (transport->dir == PJSIP_TP_DIR_INCOMING || keepalive_interval)) {
134                 struct monitored_transport *monitored;
135
136                 switch (state) {
137                 case PJSIP_TP_STATE_CONNECTED:
138                         monitored = ao2_alloc(sizeof(*monitored), monitored_transport_destroy);
139                         if (!monitored) {
140                                 break;
141                         }
142                         monitored->transport = transport;
143                         pjsip_transport_add_ref(monitored->transport);
144                         ao2_link(transports, monitored);
145                         if (transport->dir == PJSIP_TP_DIR_INCOMING) {
146                                 /* Let the scheduler inherit the reference from allocation */
147                                 if (ast_sched_add_variable(sched, IDLE_TIMEOUT, idle_sched_cb, monitored, 1) < 0) {
148                                         ao2_unlink(transports, monitored);
149                                         ao2_ref(monitored, -1);
150                                         pjsip_transport_shutdown(transport);
151                                 }
152                         } else {
153                                 /* No scheduled task, so get rid of the allocation reference */
154                                 ao2_ref(monitored, -1);
155                         }
156                         break;
157                 case PJSIP_TP_STATE_SHUTDOWN:
158                 case PJSIP_TP_STATE_DISCONNECTED:
159                         ao2_find(transports, transport->obj_name, OBJ_SEARCH_KEY | OBJ_NODATA | OBJ_UNLINK);
160                         break;
161                 default:
162                         break;
163                 }
164         }
165
166         /* Forward to the old state callback if present */
167         if (tpmgr_state_callback) {
168                 tpmgr_state_callback(transport, state, info);
169         }
170 }
171
172 /*! \brief Hashing function for monitored transport */
173 static int monitored_transport_hash_fn(const void *obj, int flags)
174 {
175         const struct monitored_transport *object;
176         const char *key;
177
178         switch (flags & OBJ_SEARCH_MASK) {
179         case OBJ_SEARCH_KEY:
180                 key = obj;
181                 break;
182         case OBJ_SEARCH_OBJECT:
183                 object = obj;
184                 key = object->transport->obj_name;
185                 break;
186         default:
187                 /* Hash can only work on something with a full key. */
188                 ast_assert(0);
189                 return 0;
190         }
191         return ast_str_hash(key);
192 }
193
194 /*! \brief Comparison function for monitored transport */
195 static int monitored_transport_cmp_fn(void *obj, void *arg, int flags)
196 {
197         const struct monitored_transport *object_left = obj;
198         const struct monitored_transport *object_right = arg;
199         const char *right_key = arg;
200         int cmp;
201
202         switch (flags & OBJ_SEARCH_MASK) {
203         case OBJ_SEARCH_OBJECT:
204                 right_key = object_right->transport->obj_name;
205                 /* Fall through */
206         case OBJ_SEARCH_KEY:
207                 cmp = strcmp(object_left->transport->obj_name, right_key);
208                 break;
209         case OBJ_SEARCH_PARTIAL_KEY:
210                 /*
211                  * We could also use a partial key struct containing a length
212                  * so strlen() does not get called for every comparison instead.
213                  */
214                 cmp = strncmp(object_left->transport->obj_name, right_key, strlen(right_key));
215                 break;
216         default:
217                 /*
218                  * What arg points to is specific to this traversal callback
219                  * and has no special meaning to astobj2.
220                  */
221                 cmp = 0;
222                 break;
223         }
224
225         return !cmp ? CMP_MATCH | CMP_STOP : 0;
226 }
227
228 static void keepalive_global_loaded(const char *object_type)
229 {
230         unsigned int new_interval = ast_sip_get_keep_alive_interval();
231
232         if (new_interval) {
233                 keepalive_interval = new_interval;
234         } else if (keepalive_interval) {
235                 ast_log(LOG_NOTICE, "Keepalive support can not be disabled once activated.\n");
236                 return;
237         } else {
238                 /* This will occur if no keepalive interval has been specified at initial start */
239                 return;
240         }
241
242         if (keepalive_thread != AST_PTHREADT_NULL) {
243                 return;
244         }
245
246         if (ast_pthread_create(&keepalive_thread, NULL, keepalive_transport_thread, NULL)) {
247                 ast_log(LOG_ERROR, "Could not create thread for sending keepalive messages.\n");
248                 ao2_ref(transports, -1);
249                 return;
250         }
251 }
252
253 /*! \brief Observer which is used to update our interval when the global setting changes */
254 static struct ast_sorcery_observer keepalive_global_observer = {
255         .loaded = keepalive_global_loaded,
256 };
257
258 /*!
259  * \brief
260  * On incoming TCP connections, when we receive a SIP request, we mark that we have
261  * received a valid SIP request. This way, we will not shut the transport down for
262  * idleness
263  */
264 static pj_bool_t idle_monitor_on_rx_request(pjsip_rx_data *rdata)
265 {
266         struct monitored_transport *idle_trans;
267
268         idle_trans = ao2_find(transports, rdata->tp_info.transport->obj_name, OBJ_SEARCH_KEY);
269         if (!idle_trans) {
270                 return PJ_FALSE;
271         }
272
273         ast_atomic_fetchadd_int(&idle_trans->sip_received, +1);
274         ao2_ref(idle_trans, -1);
275
276         return PJ_FALSE;
277 }
278
279 static pjsip_module idle_monitor_module = {
280         .name = {"idle monitor module", 19},
281         .priority = PJSIP_MOD_PRIORITY_TRANSPORT_LAYER + 3,
282         .on_rx_request = idle_monitor_on_rx_request,
283 };
284
285 static int load_module(void)
286 {
287         pjsip_tpmgr *tpmgr;
288
289         CHECK_PJSIP_MODULE_LOADED();
290
291         transports = ao2_container_alloc(TRANSPORTS_BUCKETS, monitored_transport_hash_fn,
292                 monitored_transport_cmp_fn);
293         if (!transports) {
294                 ast_log(LOG_ERROR, "Could not create container for transports to perform keepalive on.\n");
295                 return AST_MODULE_LOAD_DECLINE;
296         }
297
298         tpmgr = pjsip_endpt_get_tpmgr(ast_sip_get_pjsip_endpoint());
299         if (!tpmgr) {
300                 ast_log(LOG_ERROR, "No transport manager to attach keepalive functionality to.\n");
301                 ao2_ref(transports, -1);
302                 return AST_MODULE_LOAD_DECLINE;
303         }
304
305         sched = ast_sched_context_create();
306         if (!sched) {
307                 ast_log(LOG_ERROR, "Failed to create keepalive scheduler context.\n");
308                 ao2_ref(transports, -1);
309                 return AST_MODULE_LOAD_DECLINE;
310         }
311
312         if (ast_sched_start_thread(sched)) {
313                 ast_log(LOG_ERROR, "Failed to start keepalive scheduler thread\n");
314                 ast_sched_context_destroy(sched);
315                 ao2_ref(transports, -1);
316                 return AST_MODULE_LOAD_DECLINE;
317         }
318
319         ast_sip_register_service(&idle_monitor_module);
320
321         tpmgr_state_callback = pjsip_tpmgr_get_state_cb(tpmgr);
322         pjsip_tpmgr_set_state_cb(tpmgr, &monitored_transport_state_callback);
323
324         ast_sorcery_observer_add(ast_sip_get_sorcery(), "global", &keepalive_global_observer);
325         ast_sorcery_reload_object(ast_sip_get_sorcery(), "global");
326         ast_module_shutdown_ref(ast_module_info->self);
327         return AST_MODULE_LOAD_SUCCESS;
328 }
329
330 static int unload_module(void)
331 {
332         /* This will never get called */
333         return 0;
334 }
335
336 static int reload_module(void)
337 {
338         ast_sorcery_reload_object(ast_sip_get_sorcery(), "global");
339         return 0;
340 }
341
342 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP Reliable Transport Management",
343         .support_level = AST_MODULE_SUPPORT_CORE,
344         .load = load_module,
345         .reload = reload_module,
346         .unload = unload_module,
347         .load_pri = AST_MODPRI_CHANNEL_DEPEND - 4,
348 );