f23740b39cba4df5887a490778c2ec5e823778fa
[sip-router] / modules / ims_qos / rx_aar.c
1 /*
2  * $Id$
3  *
4  * Copyright (C) 2012 Smile Communications, jason.penton@smilecoms.com
5  * Copyright (C) 2012 Smile Communications, richard.good@smilecoms.com
6  *
7  * The initial version of this code was written by Dragos Vingarzan
8  * (dragos(dot)vingarzan(at)fokus(dot)fraunhofer(dot)de and the
9  * Fruanhofer Institute. It was and still is maintained in a separate
10  * branch of the original SER. We are therefore migrating it to
11  * Kamailio/SR and look forward to maintaining it from here on out.
12  * 2011/2012 Smile Communications, Pty. Ltd.
13  * ported/maintained/improved by
14  * Jason Penton (jason(dot)penton(at)smilecoms.com and
15  * Richard Good (richard(dot)good(at)smilecoms.com) as part of an
16  * effort to add full IMS support to Kamailio/SR using a new and
17  * improved architecture
18  *
19  * NB: Alot of this code was originally part of OpenIMSCore,
20  * FhG Fokus.
21  * Copyright (C) 2004-2006 FhG Fokus
22  * Thanks for great work! This is an effort to
23  * break apart the various CSCF functions into logically separate
24  * components. We hope this will drive wider use. We also feel
25  * that in this way the architecture is more complete and thereby easier
26  * to manage in the Kamailio/SR environment
27  *
28  * This file is part of Kamailio, a free SIP server.
29  *
30  * Kamailio is free software; you can redistribute it and/or modify
31  * it under the terms of the GNU General Public License as published by
32  * the Free Software Foundation; either version 2 of the License, or
33  * (at your option) any later version
34  *
35  * Kamailio is distributed in the hope that it will be useful,
36  * but WITHOUT ANY WARRANTY; without even the implied warranty of
37  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
38  * GNU General Public License for more details.
39  *
40  * You should have received a copy of the GNU General Public License
41  * along with this program; if not, write to the Free Software
42  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
43  *
44  *
45  *
46  * History:
47  * --------
48  *  2011-02-02  initial version (jason.penton)
49  */
50
51 #include "../../mem/shm_mem.h"
52 #include "../../parser/sdp/sdp.h"
53 #include "../cdp_avp/mod_export.h"
54
55 #include "../../modules/ims_dialog/dlg_load.h"
56 #include "../../modules/tm/tm_load.h"
57 #include "../ims_usrloc_pcscf/usrloc.h"
58 #include "rx_authdata.h"
59
60 #include "rx_aar.h"
61 #include "rx_avp.h"
62
63 #include "../../lib/ims/ims_getters.h"
64
65 #include "mod.h"
66
67 #include "../../lib/ims/useful_defs.h"
68 #include "ims_qos_stats.h"
69
70
71 #define macro_name(_rc) #_rc
72
73 //extern struct tm_binds tmb;
74 usrloc_api_t ul;
75
76 extern struct ims_qos_counters_h ims_qos_cnts_h;
77
78 extern int authorize_video_flow;
79
80 extern str af_signaling_ip;
81
82 str IMS_Serv_AVP_val = {"IMS Services", 12};
83 str IMS_Em_Serv_AVP_val = {"Emergency IMS Call", 18};
84 str IMS_Reg_AVP_val = {"IMS Registration", 16};
85
86 static void free_dialog_data(void *data) {
87     str *rx_session_id = (str*) data;
88     if (rx_session_id) {
89         if (rx_session_id->s) {
90             shm_free(rx_session_id->s);
91             rx_session_id->s = 0;
92         }
93         shm_free(rx_session_id);
94         rx_session_id = 0;
95     }
96
97 }
98
99 void async_aar_callback(int is_timeout, void *param, AAAMessage *aaa, long elapsed_msecs) {
100     struct cell *t = 0;
101     unsigned int cdp_result;
102     int result = CSCF_RETURN_ERROR;
103     rx_authsessiondata_t* p_session_data = 0;
104     AAASession *auth = 0;
105
106     LM_DBG("Received AAR callback\n");
107     saved_transaction_t* data = (saved_transaction_t*) param;
108
109     LM_DBG("received AAA answer");
110
111     if (tmb.t_lookup_ident(&t, data->tindex, data->tlabel) < 0) {
112         LM_ERR("t_continue: transaction not found\n");
113         goto error;
114     } else {
115         LM_DBG("t_continue: transaction found\n");
116     }
117     //we have T, lets restore our state (esp. for AVPs)
118     set_avp_list(AVP_TRACK_FROM | AVP_CLASS_URI, &t->uri_avps_from);
119     set_avp_list(AVP_TRACK_TO | AVP_CLASS_URI, &t->uri_avps_to);
120     set_avp_list(AVP_TRACK_FROM | AVP_CLASS_USER, &t->user_avps_from);
121     set_avp_list(AVP_TRACK_TO | AVP_CLASS_USER, &t->user_avps_to);
122     set_avp_list(AVP_TRACK_FROM | AVP_CLASS_DOMAIN, &t->domain_avps_from);
123     set_avp_list(AVP_TRACK_TO | AVP_CLASS_DOMAIN, &t->domain_avps_to);
124
125     if (is_timeout != 0) {
126         LM_ERR("Error timeout when sending AAR message via CDP\n");
127         counter_inc(ims_qos_cnts_h.media_aar_timeouts);
128         goto error;
129     }
130     if (!aaa) {
131         LM_ERR("Error sending message via CDP\n");
132         goto error;
133     }
134
135     counter_inc(ims_qos_cnts_h.media_aars);
136     counter_add(ims_qos_cnts_h.media_aar_response_time, elapsed_msecs);
137     counter_inc(ims_qos_cnts_h.media_aar_replies_received);
138
139     /* Process the response to AAR, retrieving result code and associated Rx session ID */
140     if (rx_process_aaa(aaa, &cdp_result) < 0) {
141         LM_ERR("Failed to process AAA from PCRF\n"); //puri.host.len, puri.host.s);
142         goto error;
143     }
144
145     if (cdp_result >= 2000 && cdp_result < 3000) {
146         LM_DBG("Success, received code: [%i] from PCRF for AAR request\n", cdp_result);
147         counter_inc(ims_qos_cnts_h.successful_media_aars);
148
149         LM_DBG("Auth session ID [%.*s]", aaa->sessionId->data.len, aaa->sessionId->data.s);
150
151         if(!data->aar_update) {
152             LM_DBG("This is an AAA response to an initial AAR");
153             //need to set Rx auth data to say this session has been successfully opened
154             //This is used elsewhere to prevent acting on termination events when the session has not been opened
155             //getting auth session
156             auth = cdpb.AAAGetAuthSession(aaa->sessionId->data);
157             if (!auth) {
158                 LM_DBG("Could not get Auth Session for session id: [%.*s]\n", aaa->sessionId->data.len, aaa->sessionId->data.s);
159                 goto error;
160             }
161             //getting session data
162             p_session_data = (rx_authsessiondata_t*) auth->u.auth.generic_data;
163             if (!p_session_data) {
164                 LM_DBG("Could not get session data on Auth Session for session id: [%.*s]\n", aaa->sessionId->data.len, aaa->sessionId->data.s);
165                 if (auth) cdpb.AAASessionsUnlock(auth->hash);
166                 goto error;
167             }
168             p_session_data->session_has_been_opened = 1;
169             counter_inc(ims_qos_cnts_h.active_media_rx_sessions);
170                         counter_inc(ims_qos_cnts_h.media_rx_sessions);
171
172             if (auth) cdpb.AAASessionsUnlock(auth->hash);
173
174             str * passed_rx_session_id = shm_malloc(sizeof (struct _str));
175             passed_rx_session_id->s = 0;
176             passed_rx_session_id->len = 0;
177             STR_SHM_DUP(*passed_rx_session_id, aaa->sessionId->data, "cb_passed_rx_session_id");
178             LM_DBG("passed rx session id [%.*s]", passed_rx_session_id->len, passed_rx_session_id->s);
179
180             dlgb.register_dlgcb_nodlg(&data->callid, &data->ftag, &data->ttag, DLGCB_TERMINATED | DLGCB_DESTROY | DLGCB_EXPIRED | DLGCB_RESPONSE_WITHIN | DLGCB_CONFIRMED | DLGCB_FAILED, callback_dialog, (void*) (passed_rx_session_id), free_dialog_data);
181         }
182         result = CSCF_RETURN_TRUE;
183     } else {
184         LM_DBG("Received negative reply from PCRF for AAR Request\n");
185         counter_inc(ims_qos_cnts_h.failed_media_aars);
186         //we don't free rx_authdata_p here - it is free-ed when the CDP session expires
187         goto error; // if its not a success then that means i want to reject this call!
188     }
189
190     //set success response code AVP
191     create_return_code(result);
192     goto done;
193
194 out_of_memory:
195     error :
196             //set failure response code
197             create_return_code(result);
198
199 done:
200     if (t) tmb.unref_cell(t);
201     //free memory
202     if (aaa)
203         cdpb.AAAFreeMessage(&aaa);
204
205     tmb.t_continue(data->tindex, data->tlabel, data->act);
206     free_saved_transaction_global_data(data);
207 }
208
209 void async_aar_reg_callback(int is_timeout, void *param, AAAMessage *aaa, long elapsed_msecs) {
210     struct cell *t = 0;
211     pcontact_t* pcontact;
212     unsigned int cdp_result;
213     struct pcontact_info ci;
214     udomain_t* domain_t;
215     int finalReply = 0;
216     AAASession *auth = 0;
217     rx_authsessiondata_t* p_session_data = 0;
218     int result = CSCF_RETURN_ERROR;
219     pcontact_info_t contact_info;
220
221     LM_DBG("Received AAR callback\n");
222     saved_transaction_local_t* local_data = (saved_transaction_local_t*) param;
223     saved_transaction_t* data = local_data->global_data;
224     domain_t = data->domain;
225
226     int is_rereg = local_data->is_rereg;
227
228     //before we do anything else, lets decrement the reference counter on replies
229     lock_get(data->lock);
230     data->answers_not_received--;
231     if (data->answers_not_received <= 0) {
232         finalReply = 1;
233     }
234     if (data->ignore_replies) { //there was obv. a subsequent error AFTER we had sent one/more AAR's - so we can ignore these replies and just free memory
235         free_saved_transaction_data(local_data);
236         if (finalReply) {
237             free_saved_transaction_global_data(data);
238         }
239         return;
240     }
241     lock_release(data->lock);
242
243     LM_DBG("received answer and we are waiting for [%d] answers so far failures flag is [%d]\n", data->answers_not_received, data->failed);
244
245     if (tmb.t_lookup_ident(&t, data->tindex, data->tlabel) < 0) {
246         LM_ERR("t_continue: transaction not found\n");
247         goto error;
248     }
249     //we have T, lets restore our state (esp. for AVPs)
250     set_avp_list(AVP_TRACK_FROM | AVP_CLASS_URI, &t->uri_avps_from);
251     set_avp_list(AVP_TRACK_TO | AVP_CLASS_URI, &t->uri_avps_to);
252     set_avp_list(AVP_TRACK_FROM | AVP_CLASS_USER, &t->user_avps_from);
253     set_avp_list(AVP_TRACK_TO | AVP_CLASS_USER, &t->user_avps_to);
254     set_avp_list(AVP_TRACK_FROM | AVP_CLASS_DOMAIN, &t->domain_avps_from);
255     set_avp_list(AVP_TRACK_TO | AVP_CLASS_DOMAIN, &t->domain_avps_to);
256
257     if (is_timeout != 0) {
258         LM_ERR("Error timeout when sending AAR message via CDP\n");
259         counter_inc(ims_qos_cnts_h.registration_aar_timeouts);
260         goto error;
261     }
262     if (!aaa) {
263         LM_ERR("Error sending message via CDP\n");
264         goto error;
265     }
266
267     counter_inc(ims_qos_cnts_h.registration_aars);
268     counter_add(ims_qos_cnts_h.registration_aar_response_time, elapsed_msecs);
269     counter_inc(ims_qos_cnts_h.registration_aar_replies_received);
270
271     /* Process the response to AAR, retrieving result code and associated Rx session ID */
272     if (rx_process_aaa(aaa, &cdp_result) < 0) {
273         LM_ERR("Failed to process AAA from PCRF\n"); //puri.host.len, puri.host.s);
274         goto error;
275     }
276
277     if (cdp_result >= 2000 && cdp_result < 3000) {
278         counter_inc(ims_qos_cnts_h.successful_registration_aars);
279         if (is_rereg) {
280             LM_DBG("this is a re-registration, therefore we don't need to do anything except know that the the subscription was successful\n");
281             result = CSCF_RETURN_TRUE;
282             create_return_code(result);
283             goto done;
284         }
285         //need to set Rx auth data to say this session has been successfully opened
286         //This is used elsewhere to prevent acting on termination events when the session has not been opened
287         //getting auth session
288         auth = cdpb.AAAGetAuthSession(aaa->sessionId->data);
289         if (!auth) {
290             LM_DBG("Could not get Auth Session for session id: [%.*s]\n", aaa->sessionId->data.len, aaa->sessionId->data.s);
291             goto error;
292         }
293         //getting session data
294         p_session_data = (rx_authsessiondata_t*) auth->u.auth.generic_data;
295         if (!p_session_data) {
296             LM_DBG("Could not get session data on Auth Session for session id: [%.*s]\n", aaa->sessionId->data.len, aaa->sessionId->data.s);
297             if (auth) cdpb.AAASessionsUnlock(auth->hash);
298             goto error;
299         }
300         p_session_data->session_has_been_opened = 1;
301         counter_inc(ims_qos_cnts_h.active_registration_rx_sessions);
302
303         if (auth) cdpb.AAASessionsUnlock(auth->hash);
304
305
306         LM_DBG("Success, received code: [%i] from PCRF for AAR request (contact: [%.*s]), (auth session id: %.*s)\n",
307                 cdp_result, local_data->contact.len, local_data->contact.s,
308                 local_data->auth_session_id.len, local_data->auth_session_id.s);
309         LM_DBG("Registering for Usrloc callbacks on DELETE\n");
310
311         ul.lock_udomain(domain_t, &local_data->via_host, local_data->via_port, local_data->via_proto);
312                 memset(&contact_info, 0, sizeof(struct pcontact_info));
313         contact_info.received_host = local_data->recv_host;
314         contact_info.received_port = local_data->recv_port;
315         contact_info.received_proto = local_data->recv_proto;
316         contact_info.searchflag = (1 << SEARCH_RECEIVED);
317
318
319         contact_info.aor = local_data->contact;
320         contact_info.via_host = local_data->via_host;
321         contact_info.via_port = local_data->via_port;
322         contact_info.via_prot = local_data->via_proto;
323         contact_info.reg_state = PCONTACT_ANY;
324
325         if (ul.get_pcontact(domain_t, &contact_info, &pcontact) != 0) {
326             LM_ERR("Shouldn't get here, can't find contact....\n");
327             ul.unlock_udomain(domain_t, &local_data->via_host, local_data->via_port, local_data->via_proto);
328             goto error;
329         }
330
331         //at this point we have the contact
332         /*set the contact state to say we have succesfully done ARR for register and that we dont need to do it again
333          * for the duration of the registration.
334          * */
335         if (ul.update_rx_regsession(domain_t, &local_data->auth_session_id, pcontact) != 0) {
336             LM_ERR("unable to update pcontact......\n");
337             ul.unlock_udomain(domain_t, &local_data->via_host, local_data->via_port, local_data->via_proto);
338             goto error;
339         }
340         memset(&ci, 0, sizeof (struct pcontact_info));
341         ci.reg_state = PCONTACT_REG_PENDING_AAR;
342         ci.num_service_routes = 0;
343         ci.num_public_ids = 0;
344         LM_DBG("impu: [%.*s] updating status to PCONTACT_REG_PENDING\n", pcontact->aor.len, pcontact->aor.s);
345         ul.update_pcontact(domain_t, &ci, pcontact);
346         //register for callbacks on contact
347         ul.register_ulcb(pcontact, PCSCF_CONTACT_DELETE | PCSCF_CONTACT_EXPIRE,
348                 callback_pcscf_contact_cb, NULL);
349         ul.unlock_udomain(domain_t, &local_data->via_host, local_data->via_port, local_data->via_proto);
350         result = CSCF_RETURN_TRUE;
351     } else {
352         LM_DBG("Received negative reply from PCRF for AAR Request\n");
353         counter_inc(ims_qos_cnts_h.failed_registration_aars);
354         result = CSCF_RETURN_FALSE;
355         goto error;
356     }
357
358     //set success response code AVP
359     create_return_code(result);
360     goto done;
361
362 error:
363     //set failure response code
364     create_return_code(result);
365
366 done:
367     if (t) tmb.unref_cell(t);
368     //free memory
369     if (aaa)
370         cdpb.AAAFreeMessage(&aaa);
371
372     if (finalReply) {
373         tmb.t_continue(data->tindex, data->tlabel, data->act);
374         free_saved_transaction_global_data(data);
375     }
376     free_saved_transaction_data(local_data);
377 }
378
379 /* handle an AAA response to an AAR for resource reservation for a successful registration or initiated/updated dialog
380  * @param aaa - the diameter reply
381  * @return -  1 if result code found and processing ok, -1 if error
382  */
383 int rx_process_aaa(AAAMessage *aaa, unsigned int * rc) {
384     int ret = 1;
385
386     ret = rx_get_result_code(aaa, rc);
387
388     if (ret == 0) {
389         LM_DBG("AAA message without result code\n");
390         return ret;
391     }
392
393     return ret;
394 }
395
396 /** Helper function for adding media component AVPs - uses previously stored flow descriptions not SDP from messages*/
397 int add_media_components_using_current_flow_description(AAAMessage* aar, rx_authsessiondata_t *p_session_data) {
398
399     flow_description_t *flow_description;
400     int add_flow = 1;
401
402     flow_description = p_session_data->first_current_flow_description;
403     if(!flow_description) {
404         return -1;
405     }
406     while (flow_description) {
407
408         if(!authorize_video_flow) {
409             if (strncmp(flow_description->media.s, "video", 5) == 0) {
410                 add_flow = 0;
411             }
412         }
413
414         if(add_flow) {
415             rx_add_media_component_description_avp(aar, flow_description->stream_num,
416                     &flow_description->media, &flow_description->req_sdp_ip_addr,
417                     &flow_description->req_sdp_port, &flow_description->rpl_sdp_ip_addr,
418                     &flow_description->rpl_sdp_port, &flow_description->rpl_sdp_transport,
419                     &flow_description->req_sdp_raw_stream,
420                     &flow_description->rpl_sdp_raw_stream, flow_description->direction, AVP_EPC_Flow_Usage_No_Information);
421         }
422
423         flow_description = flow_description->next;
424         add_flow = 1;
425     }
426     return 0;
427 }
428
429
430
431 /** Helper function for adding media component AVPs for each SDP stream*/
432 int add_media_components(AAAMessage* aar, struct sip_msg *req,
433         struct sip_msg *rpl, enum dialog_direction direction, AAASession* auth) {
434     int sdp_session_num;
435     int sdp_stream_num;
436     sdp_session_cell_t* req_sdp_session, *rpl_sdp_session;
437     sdp_stream_cell_t* req_sdp_stream, *rpl_sdp_stream;
438     int add_flow = 1;
439         str ttag = {0, 0};
440         str ftag = {0, 0};
441         int request_originated_from_callee = 0;  
442         str ipA, ipB;
443         
444         rx_authsessiondata_t* p_session_data = 0;
445     p_session_data = (rx_authsessiondata_t*) auth->u.auth.generic_data;
446         
447         if (!req || !rpl) {
448                         goto error;
449     }
450
451     if (parse_sdp(req) < 0) {
452         LM_ERR("Unable to parse req SDP\n");
453         goto error;
454     }
455
456     if (parse_sdp(rpl) < 0) {
457         LM_ERR("Unable to parse res SDP\n");
458         goto error;
459     }
460
461     sdp_session_num = 0;
462
463     //Loop through req sessions and streams and get corresponding rpl sessions and streams and populate avps
464     for (;;) {
465         //we only cater for one session at the moment: TDOD: extend
466         if (sdp_session_num > 0) {
467             break;
468         }
469
470         req_sdp_session = get_sdp_session(req, sdp_session_num);
471         rpl_sdp_session = get_sdp_session(rpl, sdp_session_num);
472         if (!req_sdp_session || !rpl_sdp_session) {
473             if (!req_sdp_session)
474                 LM_ERR("Missing SDP session information from req\n");
475
476             if (!rpl_sdp_session)
477                 LM_ERR("Missing SDP session information from rpl\n");
478
479                         goto error;
480         }
481
482         sdp_stream_num = 0;
483         for (;;) {
484             req_sdp_stream = get_sdp_stream(req, sdp_session_num,
485                     sdp_stream_num);
486             rpl_sdp_stream = get_sdp_stream(rpl, sdp_session_num,
487                     sdp_stream_num);
488             if (!req_sdp_stream || !rpl_sdp_stream) {
489                 //LM_ERR("Missing SDP stream information\n");
490                 break;
491             }
492             //is this a stream to add to AAR.
493             if (req_sdp_stream->is_rtp) {
494
495                 //check if the src or dst port is 0 and if so then don't add to rx
496                 int intportA = atoi(req_sdp_stream->port.s);
497                 int intportB = atoi(rpl_sdp_stream->port.s);
498                 if(intportA != 0 && intportB != 0){
499                         if(!authorize_video_flow) {
500                         if (strncmp(req_sdp_stream->media.s, "video", 5) == 0) {
501                             add_flow = 0;
502                         }
503                     }
504
505                         if(add_flow) {
506
507                                         
508                                                 if (cscf_get_to_tag(rpl, &ttag) && cscf_get_from_tag(rpl, &ftag)) {
509                                                                 LM_DBG("Original ftag [%.*s] ttag [%.*s].  Current ftag [%.*s] ttag [%.*s]\n", 
510                                                                                 p_session_data->ftag.len, p_session_data->ftag.s, p_session_data->ttag.len, p_session_data->ttag.s,
511                                                                                 ftag.len, ftag.s, ttag.len, ttag.s);
512                                                         if (!(strncmp(p_session_data->ttag.s, ttag.s, p_session_data->ttag.len) == 0 && strncmp(p_session_data->ftag.s, ftag.s, p_session_data->ftag.len) == 0)) {
513                                                                 LM_DBG("ftag and ttag of this response do not match initial response so this request came from callee\n");
514                                                                 request_originated_from_callee = 1;
515                                                         }
516                                                 } else {
517                                                         LM_ERR("Couldn't retrieve ftag so assume this request originated from caller\n");
518                                                 }
519                                         
520                                                 if (request_originated_from_callee) {
521                                                         LM_DBG("Request originated from callee so IPs are reversed\n"); 
522                                                         ipA = rpl_sdp_session->ip_addr;
523                                                         ipB = req_sdp_session->ip_addr;
524                                                 } else {
525                                                         ipA = req_sdp_session->ip_addr;
526                                                         ipB = rpl_sdp_session->ip_addr;
527                                                 }
528                                                 
529
530                                                 if (ipA.len <= 0) {
531                                                                 LM_DBG("Request SDP connection IP could not be retrieved, so we use SDP 1st stream IP\n");
532                                                                 if (request_originated_from_callee) {
533                                                                         LM_DBG("Request originated from callee so IPs are reversed\n"); 
534                                                                         ipA = rpl_sdp_stream->ip_addr;
535                                                                 } else {
536                                                                         ipA = req_sdp_stream->ip_addr;
537                                                                 }
538                                                                 
539                                                                 
540                                                                 if (ipA.len <= 0) {
541                                                                                 LM_ERR("Requested SDP IP information could not be retrieved\n");
542                                                                                 goto error;
543                                                                 }
544                                                 }
545
546                                                 if (ipB.len <= 0) {
547                                                                 LM_DBG("Reply SDP connection IP could not be retrieved, so we use SDP 1st stream IP\n");
548                                                                 if (request_originated_from_callee) {
549                                                                         LM_DBG("Request originated from callee so IPs are reversed\n"); 
550                                                                         ipB = req_sdp_stream->ip_addr;
551                                                                 } else {
552                                                                         ipB = rpl_sdp_stream->ip_addr;
553                                                                 }
554                                                                 
555                                                                 
556                                                                 if (ipB.len <= 0) {
557                                                                                 LM_ERR("Request SDP IP information could not be retrieved\n");
558                                                                                 goto error;
559                                                                 }
560                                                 }
561
562                                                 //add this to auth session data
563                         add_flow_description((rx_authsessiondata_t*) auth->u.auth.generic_data, sdp_stream_num + 1,
564                                 &req_sdp_stream->media, &ipA,
565                                 &req_sdp_stream->port, &ipB,
566                                 &rpl_sdp_stream->port, &rpl_sdp_stream->transport,
567                                 &req_sdp_stream->raw_stream,
568                                 &rpl_sdp_stream->raw_stream, direction, 0 /*This is a new mcd, we are not setting it as active*/);
569
570                         rx_add_media_component_description_avp(aar, sdp_stream_num + 1,
571                                 &req_sdp_stream->media, &ipA,
572                                 &req_sdp_stream->port, &ipB,
573                                 &rpl_sdp_stream->port, &rpl_sdp_stream->transport,
574                                 &req_sdp_stream->raw_stream,
575                                 &rpl_sdp_stream->raw_stream, direction, AVP_EPC_Flow_Usage_No_Information);
576                     }
577                     add_flow = 1;
578                 }
579             }
580             sdp_stream_num++;
581         }
582         sdp_session_num++;
583     }
584
585     free_sdp((sdp_info_t**) (void*) &req->body);
586     free_sdp((sdp_info_t**) (void*) &rpl->body);
587
588         return 1;
589
590         error:
591
592     return 0;
593 }
594
595 /**
596  * Sends the Authorization Authentication Request - specifically this is an asynchronous AAR sent if another update adding video has failed so we need to remove video
597  */
598
599 int rx_send_aar_update_no_video(AAASession* auth) {
600
601     AAAMessage* aar = 0;
602
603     str identifier;
604     int identifier_type;
605
606
607     AAA_AVP* avp = 0;
608     char x[4];
609     int ret = 0;
610
611     str recv_ip;
612     uint16_t ip_version;
613
614     //we get ip and identifier for the auth session data
615     rx_authsessiondata_t* p_session_data = 0;
616     p_session_data = (rx_authsessiondata_t*) auth->u.auth.generic_data;
617     identifier = p_session_data->identifier;
618     identifier_type = p_session_data->identifier_type;
619     recv_ip = p_session_data->ip;
620     ip_version = p_session_data->ip_version;
621
622     aar = cdpb.AAACreateRequest(IMS_Rx, IMS_AAR, Flag_Proxyable, auth);
623
624     LM_DBG("Sending AAR update to remove a video bearer\n");
625     show_callsessiondata(p_session_data);
626
627     if (!aar)
628         goto error;
629
630     /*Adding AVPs*/
631
632     LM_DBG("Adding auth app id AVP...\n");
633     /* Add Auth-Application-Id AVP */
634     if (!rx_add_auth_application_id_avp(aar, IMS_Rx))
635         goto error;
636     if (!rx_add_vendor_specific_application_id_group(aar, IMS_vendor_id_3GPP,
637             IMS_Rx))
638         goto error;
639
640     LM_DBG("Adding dest realm if not there already...\n");
641     /* Add Destination-Realm AVP, if not already there */
642     avp = cdpb.AAAFindMatchingAVP(aar, aar->avpList.head, AVP_Destination_Realm,
643             0, AAA_FORWARD_SEARCH);
644     if (!avp) {
645         str realm = rx_dest_realm;
646         if (realm.len && !rx_add_destination_realm_avp(aar, realm))
647             goto error;
648     }
649
650     LM_DBG("Adding AF App identifier...\n");
651     /* Add AF-Application-Identifier AVP */
652     str af_id = {0, 0};
653     af_id = IMS_Serv_AVP_val;
654     if (!rx_add_avp(aar, af_id.s, af_id.len, AVP_IMS_AF_Application_Identifier,
655             AAA_AVP_FLAG_MANDATORY, IMS_vendor_id_3GPP, AVP_DUPLICATE_DATA,
656             __FUNCTION__))
657         goto error;
658
659     LM_DBG("Adding service info status...\n");
660     /* Add Service-Info-Status AVP, if prelimiary
661      * by default(when absent): final status is considered*/
662
663     set_4bytes(x,
664             AVP_EPC_Service_Info_Status_Preliminary_Service_Information);
665     if (!rx_add_avp(aar, x, 4, AVP_IMS_Service_Info_Status,
666             AAA_AVP_FLAG_MANDATORY, IMS_vendor_id_3GPP, AVP_DUPLICATE_DATA,
667             __FUNCTION__))
668         goto error;
669
670     /* Add Auth lifetime AVP */LM_DBG("auth_lifetime %u\n", rx_auth_expiry); //TODO check why this is 0 all the time
671     if (rx_auth_expiry) {
672         set_4bytes(x, rx_auth_expiry);
673         if (!rx_add_avp(aar, x, 4, AVP_Authorization_Lifetime,
674                 AAA_AVP_FLAG_MANDATORY, 0, AVP_DUPLICATE_DATA, __FUNCTION__))
675             goto error;
676     }
677
678     LM_DBG("Adding subscription id...\n");
679
680     rx_add_subscription_id_avp(aar, identifier, identifier_type);
681
682
683     LM_DBG("Adding reservation priority...\n");
684     /* Add Reservation Priority AVP*/
685     set_4bytes(x, 0);
686     if (!rx_add_avp(aar, x, 4, AVP_ETSI_Reservation_Priority,
687             AAA_AVP_FLAG_VENDOR_SPECIFIC, IMS_vendor_id_ETSI,
688             AVP_DUPLICATE_DATA, __FUNCTION__))
689         goto error;
690
691     LM_DBG("Adding media component...\n");
692     //Note we add this AVP first as it gets the IP address which we need to create the auth session
693     //Could and maybe should have a separate method that retrieves the IP from SDP - TODO
694
695     /*---------- 2. Create and add Media-Component-Description AVP ----------*/
696
697     /*
698      *  See 3GPP TS29214
699      *
700      *  <Media-Component-Description> = {Media-Component-Number}
701      *                                                                  [Media-Sub-Component]
702      *                                                                  [AF-Application-Identifier]
703      *                                                                  [Media-Type]
704      *                                                                  [Max-Requested-Bandwidth-UL]
705      *                                                                  [Max-Requested-Bandwidth-DL]
706      *                                                                  [Flow-Status]
707      *                                                                  [Reservation-Priority] (Not used yet)
708      *                                                                  [RS-Bandwidth]
709      *                                                                  [RR-Bandwidth]
710      *                                                                  *[Codec-Data]
711      */
712
713     add_media_components_using_current_flow_description(aar, p_session_data);
714
715     LM_DBG("Adding framed ip address [%.*s]\n", recv_ip.len, recv_ip.s);
716     /* Add Framed IP address AVP*/
717     if (!rx_add_framed_ip_avp(&aar->avpList, recv_ip, ip_version)) {
718         LM_ERR("Unable to add framed IP AVP\n");
719         goto error;
720     }
721     LM_DBG("Unlocking AAA session...\n");
722
723     if (auth)
724         cdpb.AAASessionsUnlock(auth->hash);
725
726     LM_DBG("sending AAR to PCRF\n");
727     if (rx_forced_peer.len)
728         ret = cdpb.AAASendMessageToPeer(aar, &rx_forced_peer,
729             NULL, NULL);
730     else
731         ret = cdpb.AAASendMessage(aar, NULL,
732             NULL);
733
734     return ret;
735
736 error:
737     LM_ERR("unexpected error\n");
738     if (aar)
739         cdpb.AAAFreeMessage(&aar);
740     if (auth) {
741         cdpb.AAASessionsUnlock(auth->hash);
742         cdpb.AAADropAuthSession(auth);
743         auth = 0;
744     }
745     return ret;
746 }
747
748
749
750 /**
751  * Sends the Authorization Authentication Request.
752  * @param req - SIP request
753  * @param res - SIP response
754  * @param direction - 0/o/orig for originating side, 1/t/term for terminating side
755  * @param rx_auth_data - the returned rx auth data
756  * @returns AAA message or NULL on error
757  */
758
759 int rx_send_aar(struct sip_msg *req, struct sip_msg *res,
760         AAASession* auth, char* direction, saved_transaction_t* saved_t_data) {
761
762     AAAMessage* aar = 0;
763
764     str identifier;
765     int identifier_type;
766
767
768     AAA_AVP* avp = 0;
769     char x[4];
770     int ret = 0;
771
772     str ip;
773     uint16_t ip_version;
774
775     //we get ip and identifier for the auth session data
776     rx_authsessiondata_t* p_session_data = 0;
777     p_session_data = (rx_authsessiondata_t*) auth->u.auth.generic_data;
778     identifier = p_session_data->identifier;
779     identifier_type = p_session_data->identifier_type;
780     ip = p_session_data->ip;
781     ip_version = p_session_data->ip_version;
782
783     /* find direction for AAR (orig/term) */
784     //need this to add the media component details
785     enum dialog_direction dlg_direction = get_dialog_direction(direction);
786     if (dlg_direction == DLG_MOBILE_UNKNOWN) {
787         LM_DBG("Asked to send AAR for unknown direction.....Aborting...\n");
788         goto error;
789     }
790
791     aar = cdpb.AAACreateRequest(IMS_Rx, IMS_AAR, Flag_Proxyable, auth);
792
793     LM_DBG("Created aar request...\n");
794
795     if (!aar)
796         goto error;
797
798     /*Adding AVPs*/
799
800     LM_DBG("Adding auth app id AVP...\n");
801     /* Add Auth-Application-Id AVP */
802     if (!rx_add_auth_application_id_avp(aar, IMS_Rx))
803         goto error;
804     if (!rx_add_vendor_specific_application_id_group(aar, IMS_vendor_id_3GPP,
805             IMS_Rx))
806         goto error;
807
808     LM_DBG("Adding dest realm if not there already...\n");
809     /* Add Destination-Realm AVP, if not already there */
810     avp = cdpb.AAAFindMatchingAVP(aar, aar->avpList.head, AVP_Destination_Realm,
811             0, AAA_FORWARD_SEARCH);
812     if (!avp) {
813         str realm = rx_dest_realm;
814         if (realm.len && !rx_add_destination_realm_avp(aar, realm))
815             goto error;
816     }
817
818     LM_DBG("Adding AF App identifier...\n");
819     /* Add AF-Application-Identifier AVP */
820     str af_id = {0, 0};
821     af_id = IMS_Serv_AVP_val;
822     if (!rx_add_avp(aar, af_id.s, af_id.len, AVP_IMS_AF_Application_Identifier,
823             AAA_AVP_FLAG_MANDATORY, IMS_vendor_id_3GPP, AVP_DUPLICATE_DATA,
824             __FUNCTION__))
825         goto error;
826
827     LM_DBG("Adding service info status...\n");
828     /* Add Service-Info-Status AVP, if prelimiary
829      * by default(when absent): final status is considered*/
830     if (!res) {
831         set_4bytes(x,
832                 AVP_EPC_Service_Info_Status_Preliminary_Service_Information);
833         if (!rx_add_avp(aar, x, 4, AVP_IMS_Service_Info_Status,
834                 AAA_AVP_FLAG_MANDATORY, IMS_vendor_id_3GPP, AVP_DUPLICATE_DATA,
835                 __FUNCTION__))
836             goto error;
837     }
838
839     /* Add Auth lifetime AVP */LM_DBG("auth_lifetime %u\n", rx_auth_expiry); //TODO check why this is 0 all the time
840     if (rx_auth_expiry) {
841         set_4bytes(x, rx_auth_expiry);
842         if (!rx_add_avp(aar, x, 4, AVP_Authorization_Lifetime,
843                 AAA_AVP_FLAG_MANDATORY, 0, AVP_DUPLICATE_DATA, __FUNCTION__))
844             goto error;
845     }
846
847     LM_DBG("Adding subscription id...\n");
848
849     rx_add_subscription_id_avp(aar, identifier, identifier_type);
850
851
852     LM_DBG("Adding reservation priority...\n");
853     /* Add Reservation Priority AVP*/
854     set_4bytes(x, 0);
855     if (!rx_add_avp(aar, x, 4, AVP_ETSI_Reservation_Priority,
856             AAA_AVP_FLAG_VENDOR_SPECIFIC, IMS_vendor_id_ETSI,
857             AVP_DUPLICATE_DATA, __FUNCTION__))
858         goto error;
859
860     LM_DBG("Adding media component...\n");
861     //Note we add this AVP first as it gets the IP address which we need to create the auth session
862     //Could and maybe should have a separate method that retrieves the IP from SDP - TODO
863
864     /*---------- 2. Create and add Media-Component-Description AVP ----------*/
865
866     /*
867      *  See 3GPP TS29214
868      *
869      *  <Media-Component-Description> = {Media-Component-Number}
870      *                                                                  [Media-Sub-Component]
871      *                                                                  [AF-Application-Identifier]
872      *                                                                  [Media-Type]
873      *                                                                  [Max-Requested-Bandwidth-UL]
874      *                                                                  [Max-Requested-Bandwidth-DL]
875      *                                                                  [Flow-Status]
876      *                                                                  [Reservation-Priority] (Not used yet)
877      *                                                                  [RS-Bandwidth]
878      *                                                                  [RR-Bandwidth]
879      *                                                                  *[Codec-Data]
880      */
881
882     add_media_components(aar, req, res, dlg_direction, auth);
883
884     LM_DBG("Adding framed ip address [%.*s]\n", ip.len, ip.s);
885     /* Add Framed IP address AVP*/
886     if (!rx_add_framed_ip_avp(&aar->avpList, ip, ip_version)) {
887         LM_ERR("Unable to add framed IP AVP\n");
888         goto error;
889     }
890
891     /* Add specific action AVP's */
892     rx_add_specific_action_avp(aar, 1); // CHARGING_CORRELATION_EXCHANGE
893     rx_add_specific_action_avp(aar, 2); // INDICATION_OF_LOSS_OF_BEARER
894     rx_add_specific_action_avp(aar, 3); // INDICATION_RECOVERY_OF_BEARER
895     rx_add_specific_action_avp(aar, 4); // INDICATION_RELEASE_OF_BEARER
896     rx_add_specific_action_avp(aar, 5); // INDICATION_ESTABLISHMENT_OF_BEARER (now void)
897     rx_add_specific_action_avp(aar, 6); // IP-CAN_CHANGE
898     rx_add_specific_action_avp(aar, 12); // ACCESS_NETWORK_INFO_REPORT
899
900     show_callsessiondata(p_session_data);
901
902     LM_DBG("Unlocking AAA session...\n");
903
904     if (auth)
905         cdpb.AAASessionsUnlock(auth->hash);
906
907     LM_DBG("sending AAR to PCRF\n");
908     if (rx_forced_peer.len)
909         ret = cdpb.AAASendMessageToPeer(aar, &rx_forced_peer,
910             (void*) async_aar_callback, (void*) saved_t_data);
911     else
912         ret = cdpb.AAASendMessage(aar, (void*) async_aar_callback,
913             (void*) saved_t_data);
914
915     return ret;
916
917 error:
918     LM_ERR("unexpected error\n");
919     if (aar)
920         cdpb.AAAFreeMessage(&aar);
921     if (auth) {
922         cdpb.AAASessionsUnlock(auth->hash);
923         cdpb.AAADropAuthSession(auth);
924         auth = 0;
925     }
926     return ret;
927 }
928
929 /**
930  * Sends the Authorization Authentication Request for Register messages
931  * @param req - SIP Register msg
932  * @param rx_auth_data - the returned rx auth data
933  * @param ip - ip address extracted from contact to register
934  * @param ip_version - AF_INET or AF_INET6
935  * @returns int >0 if sent AAR successfully, otherwise 0
936  */
937
938 int rx_send_aar_register(struct sip_msg *msg, AAASession* auth, saved_transaction_local_t* saved_t_data) {
939     AAAMessage* aar = 0;
940     int ret = 0;
941     AAA_AVP* avp = 0;
942     char x[4];
943     str identifier;
944     str media;
945
946     str ip;
947     uint16_t ip_version;
948
949     //we get ip and identifier for the auth session data
950     rx_authsessiondata_t* p_session_data = 0;
951     p_session_data = (rx_authsessiondata_t*) auth->u.auth.generic_data;
952     identifier = p_session_data->identifier;
953     ip = p_session_data->ip;
954     ip_version = p_session_data->ip_version;
955
956     LM_DBG("Send AAR register\n");
957
958     aar = cdpb.AAACreateRequest(IMS_Rx, IMS_AAR, Flag_Proxyable, auth);
959
960     if (!aar)
961         goto error;
962
963     /*Add AVPs*/
964
965     /* Add Auth-Application-Id AVP */
966     if (!rx_add_auth_application_id_avp(aar, IMS_Rx))
967         goto error;
968     if (!rx_add_vendor_specific_application_id_group(aar, IMS_vendor_id_3GPP,
969             IMS_Rx))
970         goto error;
971
972     /* Add Destination-Realm AVP, if not already there */
973     avp = cdpb.AAAFindMatchingAVP(aar, aar->avpList.head, AVP_Destination_Realm,
974             0, AAA_FORWARD_SEARCH);
975     if (!avp) {
976         str realm = rx_dest_realm;
977         if (realm.len && !rx_add_destination_realm_avp(aar, realm))
978             goto error;
979     }
980
981     /* Add Subscription ID AVP*/
982
983     identifier = cscf_get_public_identity(msg);
984
985     int identifier_type = AVP_Subscription_Id_Type_SIP_URI; //we only do IMPU now
986     rx_add_subscription_id_avp(aar, identifier, identifier_type);
987
988     /* Create flow description for AF-Signaling */
989     //add this to auth session data
990     media.s = "control";
991     media.len = strlen("control");
992     str raw_stream;
993     raw_stream.s = 0;
994     raw_stream.len = 0;
995
996     char c_port_from[5];
997     str port_from;
998     port_from.len = sprintf(c_port_from, "%u", saved_t_data->via_port);
999     port_from.s = c_port_from;
1000
1001     char c_port_to[5];
1002     str port_to;
1003     port_to.len = sprintf(c_port_to, "%u", saved_t_data->recv_port);
1004     port_to.s = c_port_to;
1005
1006     str protocol;
1007     protocol.s = "IP";
1008     protocol.len = strlen("IP");
1009
1010     //rx_add_media_component_description_avp_register(aar);
1011     /* Add media component description avp for register*/
1012     rx_add_media_component_description_avp(aar, 1,
1013                &media, &saved_t_data->via_host,
1014                &port_from, &af_signaling_ip,
1015                &port_to, &protocol,
1016                &raw_stream,
1017                &raw_stream, DLG_MOBILE_REGISTER, AVP_EPC_Flow_Usage_AF_Signaling);
1018
1019     /* Add specific action AVP's */
1020     rx_add_specific_action_avp(aar, 1); // CHARGING_CORRELATION_EXCHANGE
1021     rx_add_specific_action_avp(aar, 2); // INDICATION_OF_LOSS_OF_BEARER
1022     rx_add_specific_action_avp(aar, 3); // INDICATION_RECOVERY_OF_BEARER
1023     rx_add_specific_action_avp(aar, 4); // INDICATION_RELEASE_OF_BEARER
1024     rx_add_specific_action_avp(aar, 5); // INDICATION_ESTABLISHMENT_OF_BEARER (now void)
1025     rx_add_specific_action_avp(aar, 6); // IP-CAN_CHANGE
1026     rx_add_specific_action_avp(aar, 12); // ACCESS_NETWORK_INFO_REPORT
1027
1028     /* Add Framed IP address AVP*/
1029     if (!rx_add_framed_ip_avp(&aar->avpList, ip, ip_version)) {
1030         LM_ERR("Unable to add framed IP AVP\n");
1031         goto error;
1032     }
1033
1034     /* Add Auth lifetime AVP */LM_DBG("auth_lifetime %u\n", rx_auth_expiry); //TODO check why this is 0 all the time
1035     if (rx_auth_expiry) {
1036         set_4bytes(x, rx_auth_expiry);
1037         if (!rx_add_avp(aar, x, 4, AVP_Authorization_Lifetime,
1038                 AAA_AVP_FLAG_MANDATORY, 0, AVP_DUPLICATE_DATA, __FUNCTION__))
1039             goto error;
1040     }
1041
1042     if (auth)
1043         cdpb.AAASessionsUnlock(auth->hash);
1044
1045     LM_DBG("sending AAR to PCRF\n");
1046     if (rx_forced_peer.len)
1047         ret = cdpb.AAASendMessageToPeer(aar, &rx_forced_peer,
1048             (void*) async_aar_reg_callback, (void*) saved_t_data);
1049     else
1050         ret = cdpb.AAASendMessage(aar, (void*) async_aar_reg_callback,
1051             (void*) saved_t_data);
1052
1053     return ret;
1054
1055 error:
1056     LM_ERR("unexpected error\n");
1057     if (aar)
1058         cdpb.AAAFreeMessage(&aar);
1059     if (auth) {
1060         cdpb.AAASessionsUnlock(auth->hash);
1061         cdpb.AAADropAuthSession(auth);
1062         auth = 0;
1063     }
1064     return ret;
1065 }
1066
1067 enum dialog_direction get_dialog_direction(char *direction) {
1068     if (!direction) {
1069         LM_CRIT("Unknown direction NULL");
1070         return DLG_MOBILE_UNKNOWN;
1071     }
1072     switch (direction[0]) {
1073         case 'o':
1074         case 'O':
1075         case '0':
1076             return DLG_MOBILE_ORIGINATING;
1077         case 't':
1078         case 'T':
1079         case '1':
1080             return DLG_MOBILE_TERMINATING;
1081         default:
1082             LM_CRIT("Unknown direction %s", direction);
1083             return DLG_MOBILE_UNKNOWN;
1084     }
1085 }
1086
1087 void free_saved_transaction_global_data(saved_transaction_t* data) {
1088     if (!data)
1089         return;
1090     if (data->callid.s && data->callid.len) {
1091         shm_free(data->callid.s);
1092         data->callid.len = 0;
1093     }
1094     if (data->ftag.s && data->ftag.len) {
1095         shm_free(data->ftag.s);
1096         data->ftag.len = 0;
1097     }
1098     if (data->ttag.s && data->ttag.len) {
1099         shm_free(data->ttag.s);
1100         data->ttag.len = 0;
1101     }
1102     if (data->lock) {
1103         lock_dealloc(data->lock);
1104         lock_destroy(data->lock);
1105     }
1106     shm_free(data);
1107 }
1108
1109 void free_saved_transaction_data(saved_transaction_local_t* data) {
1110     if (!data)
1111         return;
1112     shm_free(data);
1113 }