47d5ffdc0743bbe7190fdba4e18e49e41a947653
[sip-router] / src / modules / rtp_media_server / rtp_media_server.c
1 /*
2  * Copyright (C) 2017-2018 Julien Chavanton jchavanton@gmail.com
3  *
4  * This file is part of Kamailio, a free SIP server.
5  *
6  * Kamailio is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version
10  *
11  * Kamailio is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA
19  */
20
21 #include "rtp_media_server.h"
22 #include "../../core/fmsg.h"
23
24 MODULE_VERSION
25
26 rms_dialog_info_t *rms_dialog_list;
27 static int mod_init(void);
28 static void mod_destroy(void);
29 static int child_init(int);
30 str playback_fn = {0, 0};
31 str log_fn = {0, 0};
32 static char *rms_bridge_default_route = "rms:bridged";
33 static char *rms_answer_default_route = "rms:start";
34
35 int in_rms_process;
36 rms_t *rms;
37
38 static rms_dialog_info_t *rms_dialog_create_leg(rms_dialog_info_t *di, struct sip_msg *msg);
39 static int fixup_rms_action_play(void **param, int param_no);
40 static int fixup_rms_bridge(void **param, int param_no);
41 static int fixup_rms_answer(void **param, int param_no);
42 static int rms_hangup_call(rms_dialog_info_t *di);
43 static int rms_bridging_call(rms_dialog_info_t *di, rms_action_t *a);
44 static int rms_bridged_call(rms_dialog_info_t *di, rms_action_t *a);
45
46 static int rms_answer_f(struct sip_msg *, char *);
47 static int rms_sip_request_f(struct sip_msg *);
48 static int rms_action_play_f(struct sip_msg *, str *, str *);
49 static int rms_dialog_check_f(struct sip_msg *);
50 static int rms_hangup_f(struct sip_msg *);
51 static int rms_bridge_f(struct sip_msg *, char *, char *);
52
53 static int rms_update_media_sockets(struct sip_msg *msg,
54                 rms_dialog_info_t *di, rms_sdp_info_t *sdp_info);
55
56 static cmd_export_t cmds[] = {
57                 {"rms_answer", (cmd_function)rms_answer_f, 1, fixup_rms_answer, 0, EVENT_ROUTE},
58                 {"rms_sip_request", (cmd_function)rms_sip_request_f, 0, 0, 0,
59                                 EVENT_ROUTE},
60                 {"rms_play", (cmd_function)rms_action_play_f, 2, fixup_rms_action_play,
61                                 0, ANY_ROUTE},
62                 {"rms_dialog_check", (cmd_function)rms_dialog_check_f, 0, 0, 0,
63                                 REQUEST_ROUTE | FAILURE_ROUTE | ONREPLY_ROUTE},
64                 {"rms_hangup", (cmd_function)rms_hangup_f, 0, 0, 0, EVENT_ROUTE},
65                 {"rms_bridge", (cmd_function)rms_bridge_f, 2, fixup_rms_bridge, 0,
66                                 ANY_ROUTE},
67                 {"rms_dialogs_dump", (cmd_function)rms_dialogs_dump_f, 0, 0, 0,
68                                 ANY_ROUTE},
69                 {0, 0, 0, 0, 0, 0}};
70
71 static param_export_t mod_params[] = {
72                 {"log_file_name", PARAM_STR, &log_fn}, {0, 0, 0}};
73
74 struct module_exports exports = {
75                 "rtp_media_server", DEFAULT_DLFLAGS, /* dlopen flags */
76                 cmds, mod_params, 0,                             /* RPC export */
77                 0, 0, mod_init, child_init, mod_destroy,
78 };
79
80 static void run_action_route(rms_dialog_info_t *di, char *route)
81 {
82         int rt, backup_rt;
83         struct run_act_ctx ctx;
84         sip_msg_t *fmsg;
85
86         if(route == NULL) {
87                 LM_ERR("bad route\n");
88                 return;
89         }
90         rt = -1;
91         rt = route_lookup(&event_rt, route);
92         if(rt < 0 || event_rt.rlist[rt] == NULL) {
93                 LM_DBG("route does not exist");
94                 return;
95         }
96         if(faked_msg_init() < 0) {
97                 LM_ERR("faked_msg_init() failed\n");
98                 return;
99         }
100
101         fmsg = faked_msg_next();
102
103         { // set the callid
104                 struct hdr_field callid;
105                 callid.body.s = di->callid.s;
106                 callid.body.len = di->callid.len;
107                 fmsg->callid = &callid;
108         }
109         { // set the from tag
110                 struct hdr_field from;
111                 struct to_body from_parsed;
112                 from.parsed = &from_parsed;
113                 from_parsed.tag_value.len = di->remote_tag.len;
114                 from_parsed.tag_value.s = di->remote_tag.s;
115                 fmsg->from = &from;
116         }
117         //{ // set the to tag
118         //      struct hdr_field to;
119         //      struct to_body to_parsed;
120         //      to.parsed = &to_parsed;
121         //      to_parsed.tag_value.len = di->local_tag.len;
122         //      to_parsed.tag_value.s = di->local_tag.s;
123         //      fmsg->to = &to;
124         //}
125
126         backup_rt = get_route_type();
127         set_route_type(EVENT_ROUTE);
128         init_run_actions_ctx(&ctx);
129         if(rt >= 0) {
130                 run_top_route(event_rt.rlist[rt], fmsg, 0);
131         }
132         set_route_type(backup_rt);
133 }
134
135
136 static int fixup_rms_bridge(void **param, int param_no)
137 {
138         if(param_no == 1 || param_no == 2)
139                 return fixup_spve_null(param, 1);
140         LM_ERR("invalid parameter count [%d]\n", param_no);
141         return -1;
142 }
143
144 static int fixup_rms_answer(void **param, int param_no)
145 {
146         if(param_no == 1 || param_no == 2)
147                 return fixup_spve_null(param, 1);
148         LM_ERR("invalid parameter count [%d]\n", param_no);
149         return -1;
150 }
151
152 static int fixup_rms_action_play(void **param, int param_no)
153 {
154         if(param_no == 1 || param_no == 2 || param_no ==3)
155                 return fixup_spve_null(param, 1);
156         LM_ERR("invalid parameter count [%d]\n", param_no);
157         return -1;
158 }
159
160 /**
161  * @return 0 to continue to load the OpenSER, -1 to stop the loading
162  * and abort OpenSER.
163  */
164 static int mod_init(void)
165 {
166         LM_INFO("RTP media server module init\n");
167
168         rms = shm_malloc(sizeof(rms_t));
169         rms->udp_start_port = 50000;
170         LM_INFO("RTP media server module init\n");
171         rms->udp_end_port = 60000;
172         rms->udp_last_port = 50000 + rand() % 10000;
173         rms_media_init();
174
175         if(!init_rms_dialog_list()) {
176                 LM_ERR("can't initialize rms_dialog_list !\n");
177                 return -1;
178         }
179
180         register_procs(1);
181         if(load_tm_api(&tmb) != 0) {
182                 LM_ERR("can't load TM API\n");
183                 return -1;
184         }
185         FILE *log_file = fopen(log_fn.s, "w+");
186         if(log_file) {
187                 LM_INFO("ortp logs are redirected [%s]\n", log_fn.s);
188         } else {
189                 log_file = stdout;
190                 LM_INFO("ortp can not open logs file [%s]\n", log_fn.s);
191         }
192         ortp_set_log_file(log_file);
193         ortp_set_log_level_mask(
194                         NULL, ORTP_MESSAGE | ORTP_WARNING | ORTP_ERROR | ORTP_FATAL);
195         return (0);
196 }
197
198 /**
199  * Called only once when OpenSER is shuting down to clean up module
200  * resources.
201  */
202 static void mod_destroy()
203 {
204         rms_media_destroy();
205         LM_INFO("RTP media server module destroy\n");
206         return;
207 }
208
209 void rms_signal_handler(int signum)
210 {
211         LM_INFO("signal received [%d]\n", signum);
212 }
213
214
215 static rms_dialog_info_t *rms_stop(rms_dialog_info_t *di)
216 {
217         LM_NOTICE("di[%p]\n", di);
218         if(di->bridged_di) {
219                 rms_stop_bridge(&di->media, &di->bridged_di->media);
220         } else {
221                 rms_stop_media(&di->media);
222         }
223
224         rms_dialog_info_t *tmp = di->prev;
225         di->state = RMS_ST_DISCONNECTED;
226         // keep it for a little while to deal with retransmissions ...
227         //clist_rm(di, next, prev);
228         //rms_dialog_free(di);
229         di = tmp;
230         return di;
231 }
232
233 static rms_dialog_info_t *rms_dialog_action_check(rms_dialog_info_t *di)
234 {
235         rms_action_t *a;
236                 if (!di)
237                         LM_ERR("Dialog info NULL\n");
238         clist_foreach(&di->action, a, next)
239         {
240                 if (!a)
241                         LM_ERR("dialog action NULL\n");
242
243                 if(a->type == RMS_HANGUP) {
244                         LM_INFO("dialog action RMS_HANGUP [%s]\n", di->callid.s);
245                         rms_hangup_call(di);
246                         if(di->bridged_di)
247                                 rms_hangup_call(di->bridged_di);
248                         a->type = RMS_STOP;
249                         return di;
250                 } else if(a->type == RMS_BRIDGING) {
251                         LM_INFO("dialog action RMS_BRIDGING [%s]\n", di->callid.s);
252                         rms_bridging_call(di, a);
253                         a->type = RMS_NONE;
254                         shm_free(a->param.s);
255                         return di;
256                 } else if(a->type == RMS_BRIDGED) {
257                         LM_INFO("dialog action RMS_BRIDGED [%s]\n", di->callid.s);
258                         LM_INFO("di_1[%p]di_2[%p]\n", di, di->bridged_di);
259                         rms_bridged_call(di, a);
260                         a->type = RMS_NONE;
261                         return di;
262                 } else if(a->type == RMS_STOP) {
263                         LM_INFO("dialog action RMS_STOP [%s][%p|%p]\n", di->callid.s, di,
264                                         di->prev);
265                         //if (di->bridged_di)
266                         //      rms_stop(di->bridged_di);
267                         di = rms_stop(di);
268                         a->type = RMS_NONE;
269                         // di->state = RMS_SSTATE_DISCONNECTED;
270                         return di;
271                 } else if(a->type == RMS_PLAY) {
272                         LM_INFO("dialog action RMS_PLAY [%s]\n", di->callid.s);
273                         rms_playfile(&di->media, a);
274                         a->type = RMS_NONE;
275                 } else if(a->type == RMS_DONE) {
276                         LM_INFO("dialog action RMS_DONE [%s][%s]\n", di->callid.s,
277                                         a->route.s);
278                         if(a->route.s) {
279                                 run_action_route(di, a->route.s);
280                                 rms_action_t *tmp = a->prev;
281                                 clist_rm(a, next, prev);
282                                 shm_free(a);
283                                 a = tmp;
284                         } else {
285                                 a->type = RMS_HANGUP;
286                         }
287                         return di;
288                 } else if(a->type == RMS_START) {
289                         LM_INFO("dialog action RMS_START\n");
290                         create_call_leg_media(&di->media);
291                         LM_INFO("dialog action RMS_START [%s]\n", di->callid.s);
292                         rms_action_t *tmp = a->prev;
293                         clist_rm(a, next, prev);
294                         rms_start_media(&di->media, a->param.s);
295                         run_action_route(di, a->route.s);
296                         shm_free(a);
297                         a = tmp;
298                         LM_INFO("dialog action RMS_START[done]\n");
299                         return di;
300                 }
301         }
302         return di;
303 }
304
305 /**
306  * Most interaction with the RTP sessions and media streams that are controlled 
307  * in this function this is safer in the event where a library is using non shared memory
308  * all the mediastreamer2 ticker threads are spawned from here.
309  */
310 static void rms_dialog_manage_loop()
311 {
312         in_rms_process = 1;
313         while(1) {
314                 lock(&dialog_list_mutex);
315                 rms_dialog_info_t *di;
316                 clist_foreach(rms_dialog_list, di, next)
317                 {
318                         di = rms_dialog_action_check(di);
319                         //LM_INFO("next ... si[%p]\n", di);
320                 }
321                 unlock(&dialog_list_mutex);
322                 usleep(10000);
323         }
324 }
325
326 /**
327  * The rank will be o for the main process calling this function,
328  * or 1 through n for each listener process. The rank can have a negative
329  * value if it is a special process calling the child init function.
330  * Other then the listeners, the rank will equal one of these values:
331  * PROC_MAIN      0  Main ser process
332  * PROC_TIMER    -1  Timer attendant process
333  * PROC_FIFO     -2  FIFO attendant process
334  * PROC_TCP_MAIN -4  TCP main process
335  * PROC_UNIXSOCK -5  Unix domain socket server processes
336  *
337  * If this function returns a nonzero value the loading of OpenSER will
338  * stop.
339  */
340 static int child_init(int rank)
341 {
342         if(rank == PROC_MAIN) {
343                 int pid;
344                 pid = fork_process(PROC_XWORKER, "RTP_media_server", 1);
345                 if(pid < 0)
346                         return -1;
347                 if(pid == 0) {
348                         rms_dialog_manage_loop();
349                         return 0;
350                 }
351         }
352         int rtn = 0;
353         return (rtn);
354 }
355
356 static int parse_from(struct sip_msg *msg, rms_dialog_info_t *di)
357 {
358         struct to_body *from = get_from(msg);
359         LM_DBG("from[%.*s]tag[%.*s]\n", from->uri.len, from->uri.s,
360                         from->tag_value.len, from->tag_value.s);
361         rms_str_dup(&di->remote_tag, &from->tag_value, 1);
362         return 1;
363 }
364
365 static int rms_sip_reply(
366                 struct cell *cell, rms_dialog_info_t *di, int code, char *_reason)
367 {
368         if (di->state == RMS_ST_CONNECTED) {
369                 return 1;
370         }
371         str reason = str_init(_reason);
372         if(di->remote_tag.len == 0) {
373                 LM_ERR("can not find from tag\n");
374                 return 0;
375         }
376
377         if(!cell)
378                 cell = tmb.t_gett();
379
380         if(cell->uas.request) {
381                 if(!tmb.t_reply_with_body(
382                                    cell, code, &reason, NULL, NULL, &di->local_tag)) {
383                         LM_ERR("t_reply error");
384                         return 0;
385                 }
386         } else {
387                 LM_INFO("no request found\n");
388         }
389         return 1;
390 }
391
392 static int rms_answer_call(
393                 struct cell *cell, rms_dialog_info_t *di, rms_sdp_info_t *sdp_info)
394 {
395         char buffer[128];
396         str reason = str_init("OK");
397         str contact_hdr;
398         if (di->state == RMS_ST_CONNECTED) {
399                 return 1;
400         }
401
402         LM_INFO("[%s][%d]\n", sdp_info->new_body.s, sdp_info->udp_local_port);
403
404         if(di->remote_tag.len == 0) {
405                 LM_ERR("can not find from tag\n");
406                 return 0;
407         }
408         LM_INFO("ip[%s]\n", di->local_ip.s);
409         sdp_info->local_ip.s = di->local_ip.s;
410         sdp_info->local_ip.len = di->local_ip.len;
411
412         snprintf(buffer, 128,
413                         "Contact: <sip:rms@%s:%d>\r\nContent-Type: application/sdp\r\n",
414                         di->local_ip.s, di->local_port);
415         contact_hdr.len = strlen(buffer);
416         contact_hdr.s = buffer;
417
418         if(!cell)
419                 cell = tmb.t_gett();
420
421         if(cell->uas.request) {
422                 if(!tmb.t_reply_with_body(cell, 200, &reason, &sdp_info->new_body,
423                                    &contact_hdr, &di->local_tag)) {
424                         LM_ERR("t_reply error");
425                         return 0;
426                 }
427                 LM_INFO("answered\n");
428                 di->state = RMS_ST_CONNECTED;
429         } else {
430                 LM_INFO("no request found\n");
431         }
432         return 1;
433 }
434
435 // message originating leg is suspended, this is the callback function of the transaction with destination leg
436 static void forward_cb(struct cell *ptrans, int ntype, struct tmcb_params *pcbp)
437 {
438         // struct sip_msg *msg = pcbp->rpl;
439         str *reason = &pcbp->rpl->first_line.u.reply.reason;
440         rms_action_t *a = (rms_action_t *)*pcbp->param;
441         if(ntype == TMCB_ON_FAILURE) {
442                 LM_NOTICE("FAILURE [%d][%.*s]\n", pcbp->code, reason->len, reason->s);
443                 return;
444         } else {
445                 LM_NOTICE("COMPLETE [%d][%.*s] RE-INVITE/UPDATE - TODO SDP "
446                                   "renegotiation ? \n",
447                                 pcbp->code, reason->len, reason->s);
448         }
449
450         // rms_answer_call(a->cell, di, sdp_info);
451         // if(!cell) cell = tmb.t_gett();
452         if(a->cell->uas.request) {
453                 if(!tmb.t_reply_with_body(a->cell, pcbp->code, reason, NULL, NULL,
454                                    &a->di->local_tag)) {
455                         LM_ERR("t_reply error");
456                         return;
457                 }
458                 LM_INFO("replied\n");
459         } else {
460                 LM_INFO("no request found\n");
461         }
462 }
463
464
465 // legA is suspended, this is the callback function of the transaction with legB (the callee)
466 // response to legA will be not be done here but once the media negociation is completed by the RMS process.
467 static void bridge_cb(struct cell *ptrans, int ntype, struct tmcb_params *pcbp)
468 {
469         struct sip_msg *msg = pcbp->rpl;
470         if(ntype == TMCB_ON_FAILURE) {
471                 LM_NOTICE("FAILURE [%d]\n", pcbp->code);
472                 rms_action_t *a = (rms_action_t *)*pcbp->param;
473                 a->di->state = RMS_ST_DISCONNECTED;
474                 if(a->cell->uas.request) {
475                         str *reason = &pcbp->rpl->first_line.u.reply.reason;
476                         if(!tmb.t_reply_with_body(a->cell, pcbp->code, reason, NULL, NULL,
477                                            &a->di->local_tag)) {
478                                 LM_ERR("t_reply error");
479                                 return;
480                         }
481                         LM_INFO("failure replied\n");
482                         a->type = RMS_NONE;
483                 } else {
484                         LM_ERR("failure but no request found\n");
485                 }
486                 return;
487         } else if(ntype == TMCB_LOCAL_COMPLETED) {
488                 LM_NOTICE("COMPLETED [%d]\n", pcbp->code);
489         } else if(ntype == TMCB_LOCAL_RESPONSE_IN){
490                 LM_NOTICE("RESPONSE [%d]\n", pcbp->code);
491                 if (pcbp->code != 180 && pcbp->code != 183)
492                         return;
493         } else {
494                 LM_NOTICE("TMCB_TYPE[%d][%d]\n", ntype, pcbp->code);
495         }
496
497         if(parse_to_header(msg) < 0) {
498                 LM_ERR("can not parse To header!\n");
499                 return;
500         }
501         struct to_body *to = get_to(msg);
502         if(parse_from_header(msg) < 0) {
503                 LM_ERR("can not parse From header!\n");
504                 return;
505         }
506         struct to_body *from = get_from(msg);
507
508         rms_action_t *a = (rms_action_t *)*pcbp->param;
509         rms_dialog_info_t *bridged_di = a->di;
510         rms_dialog_info_t *di = bridged_di->bridged_di;
511
512         if(to->tag_value.len == 0) {
513                 LM_ERR("not to tag.\n");
514                 goto error;
515         } else {
516                 rms_str_dup(&di->remote_tag, &to->tag_value, 1);
517         }
518
519         if(from->tag_value.len == 0) {
520                 LM_ERR("not from tag.\n");
521                 goto error;
522         } else {
523                 rms_str_dup(&di->local_tag, &from->tag_value, 1);
524         }
525
526         LM_NOTICE("dialog updated [%s][%s][%s]\n", di->callid.s, di->remote_tag.s,
527                         di->local_tag.s);
528         if (pcbp->code == 180 || pcbp->code == 183) {
529                 return; // early media not tested/handled properly
530         }
531
532         rms_sdp_info_t *sdp_info = &di->sdp_info_answer;
533         if(!rms_get_sdp_info(sdp_info, msg)) {
534                 LM_ERR("can not get SDP information\n");
535                 goto error;
536         }
537         di->media.pt = rms_sdp_select_payload(sdp_info);
538         rms_update_media_sockets(pcbp->rpl, di, &di->sdp_info_answer);
539         LM_INFO("[%p][%s:%d]\n", di, sdp_info->local_ip.s,
540                         sdp_info->udp_local_port);
541         a->type = RMS_BRIDGED;
542         return;
543 error:
544         LM_ERR("TODO: free and terminate!\n");
545 }
546
547
548 static int rms_bridged_call(rms_dialog_info_t *di, rms_action_t *a)
549 {
550         rms_sdp_info_t *sdp_info = &di->bridged_di->sdp_info_answer;
551         sdp_info->udp_local_port = di->media.local_port;
552         LM_INFO("[%p][%s:%d]\n", di, sdp_info->local_ip.s,
553                         sdp_info->udp_local_port);
554         sdp_info->local_ip.s = di->local_ip.s;
555         sdp_info->local_ip.len = di->local_ip.len;
556
557         rms_sdp_prepare_new_body(sdp_info, di->bridged_di->media.pt);
558         rms_answer_call(a->cell, di, sdp_info);
559         LM_NOTICE("si_1[%p] si_2[%p]\n", di, di->bridged_di);
560         create_call_leg_media(&di->media);
561         create_call_leg_media(&di->bridged_di->media);
562         //      clist_append(rms_dialog_list, di, next, prev);
563         rms_bridge(&di->media, &di->bridged_di->media);
564         return 1;
565 }
566
567
568 static int rms_bridging_call(rms_dialog_info_t *di, rms_action_t *a)
569 {
570         uac_req_t uac_r;
571         int result;
572         str method_invite = str_init("INVITE");
573         str headers;
574
575         struct sip_uri ruri_t;
576         str *param_uri = &a->param;
577         param_uri->len = strlen(param_uri->s);
578
579         result = parse_uri(param_uri->s, param_uri->len, &ruri_t);
580         LM_INFO("parsed[%.*s][%d]\n", param_uri->len, param_uri->s, result);
581         char buff[1024];
582         di->bridged_di->remote_uri.len = snprintf(buff, 1024,
583                         "<sip:%.*s@%.*s:%.*s>", ruri_t.user.len, ruri_t.user.s,
584                         ruri_t.host.len, ruri_t.host.s, ruri_t.port.len, ruri_t.port.s);
585         di->bridged_di->remote_uri.s = rms_char_dup(buff, 1);
586         if(!di->bridged_di->remote_uri.s) {
587                 LM_ERR("can not set remote uri !");
588                 goto error;
589         }
590
591         snprintf(buff, 256, "Max-Forwards: 70\r\nContact: "
592                                                 "<sip:rms@%s:%d>\r\nContent-Type: application/sdp\r\n",
593                         di->local_ip.s, di->local_port);
594         headers.len = strlen(buff);
595         headers.s = buff;
596         LM_INFO("si[%p]call-id[%.*s]cseq[%d]ruri[%d|%s]remote_uri[%s]local_uri[%s]\n", di,
597                         di->callid.len, di->callid.s, di->bridged_di->cseq, param_uri->len, param_uri->s,
598                         di->bridged_di->remote_uri.s, di->bridged_di->local_uri.s);
599         dlg_t *dialog = NULL;
600         if(tmb.new_dlg_uac(&di->bridged_di->callid, &di->bridged_di->local_tag,
601                            di->bridged_di->cseq, &di->bridged_di->local_uri,
602                            &di->bridged_di->remote_uri, &dialog)
603                         < 0) {
604                 LM_ERR("error in tmb.new_dlg_uac\n");
605                 goto error;
606         }
607         dialog->rem_target.s = param_uri->s;
608         dialog->rem_target.len = param_uri->len - 1;
609         rms_sdp_info_t *sdp_info = &di->bridged_di->sdp_info_offer;
610
611         set_uac_req(&uac_r, &method_invite, &headers, &sdp_info->new_body, dialog,
612                         TMCB_LOCAL_COMPLETED | TMCB_LOCAL_RESPONSE_IN | TMCB_ON_FAILURE, bridge_cb, a);
613         result = tmb.t_request_within(&uac_r);
614         di->bridged_di->cseq = dialog->loc_seq.value;
615         if(result < 0) {
616                 LM_ERR("error in tmb.t_request\n");
617                 goto error;
618         } else {
619                 LM_ERR("tmb.t_request_within ok\n");
620         }
621         return 1;
622 error:
623         rms_sip_reply(a->cell, di, 503, "bridging error");
624         rms_dialog_free(di->bridged_di);
625         return -1;
626 }
627
628 static int rms_hangup_call(rms_dialog_info_t *di)
629 {
630         uac_req_t uac_r;
631         int result;
632         str headers = str_init("Max-Forwards: 70" CRLF);
633         str method_bye = str_init("BYE");
634
635         LM_INFO("si[%p]callid[%.*s]cseq[%d]remote_uri[%s]local_uri[%s]\n", di, di->callid.len, di->callid.s,
636                         di->cseq, di->remote_uri.s, di->local_uri.s);
637         LM_INFO("contact[%.*s]\n", di->contact_uri.len, di->contact_uri.s);
638         dlg_t *dialog = NULL;
639
640         if(tmb.new_dlg_uac(&di->callid, &di->local_tag, di->cseq, &di->local_uri,
641                            &di->remote_uri, &dialog)
642                         < 0) {
643                 LM_ERR("error in tmb.new_dlg_uac\n");
644                 return -1;
645         }
646         dialog->id.rem_tag.s = di->remote_tag.s;
647         dialog->id.rem_tag.len = di->remote_tag.len;
648         dialog->rem_target.s = di->contact_uri.s;
649         dialog->rem_target.len = di->contact_uri.len;
650         set_uac_req(&uac_r, &method_bye, &headers, NULL, dialog,
651                         TMCB_LOCAL_COMPLETED, NULL, NULL);
652         result = tmb.t_request_within(&uac_r);
653         di->cseq = dialog->loc_seq.value;
654         if(result < 0) {
655                 LM_ERR("error in tmb.t_request\n");
656                 return -1;
657         } else {
658                 LM_ERR("tmb.t_request_within ok\n");
659         }
660         return 1;
661 }
662
663
664 /*
665  * Create a new dialog info that will be used for bridging
666  */
667 static rms_dialog_info_t *rms_dialog_create_leg(rms_dialog_info_t *di, struct sip_msg *msg)
668 {
669         if(!di)
670                 return NULL;
671         di->bridged_di = rms_dialog_new_bleg(msg);
672         if(!di->bridged_di) {
673                 LM_ERR("can not allocate dialog info !\n");
674                 goto error;
675         }
676         memset(di->bridged_di, 0, sizeof(rms_dialog_info_t));
677         di->bridged_di->bridged_di = di;
678         if(!rms_str_dup(&di->bridged_di->callid, &di->callid, 1)) {
679                 LM_ERR("can not get callid .\n");
680                 goto error;
681         }
682         if(!rms_str_dup(&di->bridged_di->local_uri, &di->local_uri, 1))
683                 goto error;
684         if(!rms_str_dup(&di->bridged_di->local_ip, &di->local_ip, 1))
685                 goto error;
686
687         rms_update_media_sockets(msg, di->bridged_di, &di->bridged_di->sdp_info_offer);
688         rms_sdp_prepare_new_body(&di->bridged_di->sdp_info_offer, di->media.pt);
689         clist_init(&di->bridged_di->action, next, prev);
690         return di->bridged_di;
691 error:
692         rms_dialog_free(di);
693         return NULL;
694 }
695
696
697 static int rms_get_udp_port(void)
698 {
699         // RTP UDP port
700         rms->udp_last_port += 3;
701         if(rms->udp_last_port > rms->udp_end_port)
702                 rms->udp_last_port = rms->udp_start_port;
703         LM_INFO("port[%d]\n", rms->udp_last_port);
704         return rms->udp_last_port;
705 }
706
707
708
709 // update media IP and port
710 static int rms_update_media_sockets(struct sip_msg *msg, rms_dialog_info_t *di, rms_sdp_info_t *sdp_info)
711 {
712         call_leg_media_t *m = &di->media;
713         if(!m->local_port)
714                 m->local_port = rms_get_udp_port();
715         sdp_info->udp_local_port = m->local_port;
716         sdp_info->local_ip.s = di->local_ip.s;
717         sdp_info->local_ip.len = di->local_ip.len;
718         m->local_ip.s = di->local_ip.s;
719         m->local_ip.len = di->local_ip.len;
720         m->remote_port = sdp_info->remote_port;
721         m->remote_ip.s = sdp_info->remote_ip.s;
722         m->remote_ip.len = sdp_info->remote_ip.len;
723         m->di = di;
724
725         LM_INFO("remote_socket[%s:%d] local_socket[%s:%d]\n",
726                         sdp_info->remote_ip.s, sdp_info->remote_port, m->local_ip.s,
727                         m->local_port);
728         return 1;
729 }
730
731 static int rms_create_trans(struct sip_msg *msg)
732 {
733         int status = tmb.t_newtran(msg);
734         LM_INFO("new transaction[%d]\n", status);
735         if(status < 0) {
736                 LM_ERR("error creating transaction \n");
737                 return -1;
738         } else if(status == 0) {
739                 LM_DBG("retransmission");
740                 return 0;
741         }
742         return 1;
743 }
744
745 static void rms_action_add(rms_dialog_info_t *di, rms_action_t *a)
746 {
747         a->di = di;
748         clist_append(&di->action, a, next, prev);
749 }
750
751 static void rms_action_add_sync(rms_dialog_info_t *di, rms_action_t *a)
752 {
753         lock(&dialog_list_mutex);
754         rms_action_add(di, a);
755         unlock(&dialog_list_mutex);
756 }
757
758 // Called when receiving BYE
759 static int rms_disconnect(struct sip_msg *msg)
760 {
761         int status = rms_create_trans(msg);
762         if(status < 1)
763                 return status;
764
765         rms_dialog_info_t *di;
766         if(!msg || !msg->callid || !msg->callid->body.s) {
767                 LM_ERR("no callid\n");
768                 return -1;
769         }
770         di = rms_dialog_search_sync(msg);
771         if(!di) {
772                 LM_INFO("dialog not found ci[%.*s]\n", msg->callid->body.len,
773                                 msg->callid->body.s);
774                 if(!tmb.t_reply(msg, 481, "Call/Transaction Does Not Exist")) {
775                         return -1;
776                 }
777                 return 0;
778         }
779         rms_action_t *a = rms_action_new(RMS_STOP);
780         if(!a)
781                 return -1;
782         rms_action_add_sync(di, a);
783         if(!tmb.t_reply(msg, 200, "OK")) {
784                 return -1;
785         }
786         return 0;
787 }
788
789 //static int rms_action_dtmf_f(struct sip_msg *msg, char dtmf, str *route)
790 //      rms_dialog_info_t *di =
791 //                      rms_dialog_search(msg);
792 //      if(!di)
793 //              return -1;
794 //      rms_playfile();
795 //      return 0;
796 //}
797
798 static int rms_action_play_f(struct sip_msg *msg, str *playback_fn, str *route)
799 {
800         rms_dialog_info_t *di = rms_dialog_search(msg);
801         if(!di) {
802                 return -1;
803         }
804         LM_INFO("RTP session [%s:%d]<>[%s:%d]\n", di->media.local_ip.s,
805                         di->media.local_port, di->media.remote_ip.s, di->media.remote_port);
806
807         rms_action_t *a = rms_action_new(RMS_PLAY);
808         if(!a)
809                 return -1;
810         a->param.len = playback_fn->len;
811         a->param.s = playback_fn->s;
812         a->route.len = route->len;
813         a->route.s = route->s;
814         rms_action_add(di, a);
815         return 0;
816 }
817
818 static int rms_bridge_f(struct sip_msg *msg, char *_target, char *_route)
819 {
820         str target = {NULL, 0};
821         str route = {NULL, 0};
822         rms_dialog_info_t *di = rms_dialog_search(msg);
823         int status = 1;
824
825         if(!rms_check_msg(msg))
826                 return -1;
827
828         if (di) {
829                 if (di->state == RMS_ST_CONNECTED) {
830                         LM_INFO("already connected, bridging\n");
831                 } else {
832                         LM_ERR("Can not bridge an existing call leg that is not connected.\n");
833                         return -1;
834                 }
835         } else {
836                 status = rms_create_trans(msg);
837                 if(status < 1)
838                         return status;
839                 // create a_leg dialog
840                 di = rms_dialog_new(msg);
841                 if(!di)
842                         return -1;
843                 di->local_port = msg->rcv.dst_port;
844         }
845
846         // parameter 1 : target URI
847         if(get_str_fparam(&target, msg, (gparam_p)_target) != 0) {
848                 if (di->state != RMS_ST_CONNECTED) {
849                         LM_ERR("rms_bridge: missing target\n");
850                         tmb.t_reply(msg, 404, "Not found");
851                 }
852                 return -1;
853         }
854         // parameter 2 : route call-back
855         if(get_str_fparam(&route, msg, (gparam_p)_route) != 0) {
856                 route.len = strlen(rms_bridge_default_route);
857                 route.s = rms_bridge_default_route;
858         }
859
860         LM_NOTICE("rms_bridge[%s][%d]\n", target.s, target.len);
861
862         if (di->state == RMS_ST_DEFAULT) {
863                 str to_tag;
864                 parse_from(msg, di);
865                 tmb.t_get_reply_totag(msg, &to_tag);
866                 rms_str_dup(&di->local_tag, &to_tag, 1);
867                 LM_INFO("local_uri[%s]local_tag[%s]\n", di->local_uri.s,
868                                 di->local_tag.s);
869                 rms_update_media_sockets(msg, di, &di->sdp_info_offer);
870         }
871         // Prepare the body of the SDP offer for the current Payload type
872         // Both call legs will have the same offer.
873         LM_NOTICE("payload[%d]\n", di->media.pt->type);
874         rms_sdp_prepare_new_body(&di->sdp_info_offer, di->media.pt);
875
876         // create b_leg
877         di->bridged_di = rms_dialog_create_leg(di, msg);
878
879         if(!di->bridged_di) {
880                 LM_ERR("can not create dialog b_leg !\n");
881                 goto error;
882         }
883
884         rms_action_t *a = rms_action_new(RMS_BRIDGING);
885         if(!a)
886                 return -1;
887         LM_NOTICE("remote target[%.*s]\n", target.len, target.s);
888         LM_NOTICE("remote route[%.*s]\n", route.len, route.s);
889         if(!rms_str_dup(&a->param, &target, 1)) {
890                 goto error;
891         }
892
893         a->route.len = route.len;
894         a->route.s = route.s;
895
896         if (di->state != RMS_ST_CONNECTED) { // a_leg: suspend transaction
897                 a->cell = tmb.t_gett();
898                 tmb.t_reply(msg, 100, "Trying");
899                 if(tmb.t_suspend(msg, &a->tm_info.hash_index, &a->tm_info.label) < 0) {
900                         LM_ERR("t_suspend() failed\n");
901                         goto error;
902                 }
903                 LM_INFO("transaction request[%p]\n", a->cell->uas.request);
904         } else {
905                 a->cell = NULL;
906         }
907         LM_INFO("adding action\n");
908         rms_action_add(di, a);
909
910         LM_INFO("adding b_leg dialog\n");
911         rms_dialog_add(di->bridged_di);
912         LM_INFO("di_1[%p]di_2[%p]\n", di, di->bridged_di);
913         if (di->state != RMS_ST_CONNECTED)
914                 rms_dialog_add(di);
915         return 0;
916 error:
917         rms_dialog_rm(di);
918         rms_dialog_free(di);
919         return -1;
920 }
921
922
923 static int rms_sip_cancel(struct sip_msg *msg, str *callid_s, str *cseq_s)
924 {
925         tm_cell_t *trans;
926         tm_cell_t *bkt;
927         int bkb;
928         struct cancel_info cancel_data;
929         int fl = 0;
930         int rcode = 0;
931
932         if(rcode<100 || rcode>699)
933                 rcode = 0;
934
935         bkt = tmb.t_gett();
936         bkb = tmb.t_gett_branch();
937         if (tmb.t_lookup_callid(&trans, *callid_s, *cseq_s) < 0 ) {
938                 LM_NOTICE("Lookup failed - no transaction [%s][%s]\n", callid_s->s, cseq_s->s);
939                 tmb.t_sett(bkt, bkb);
940                 if(!tmb.t_reply(msg, 481, "Call/Transaction Does Not Exist")) {
941                         return -1;
942                 }
943                 return 1;
944         }
945
946         if(trans->uas.request && fl>0 && fl<32)
947                 setflag(trans->uas.request, fl);
948         init_cancel_info(&cancel_data);
949         cancel_data.reason.cause = rcode;
950         cancel_data.cancel_bitmap = 0;
951         tmb.prepare_to_cancel(trans, &cancel_data.cancel_bitmap, 0);
952         tmb.cancel_uacs(trans, &cancel_data, 0);
953
954         tmb.t_sett(bkt, bkb);
955         if(!tmb.t_reply(msg, 202, "cancelling")) {
956                 LM_ERR("can not reply cancelling ?\n");
957                 return -1;
958         }
959         LM_DBG("cancelling ...\n");
960         return 1;
961 }
962
963
964 static int rms_sip_forward(
965                 rms_dialog_info_t *di, struct sip_msg *msg, str *method)
966 {
967         uac_req_t uac_r;
968         int result;
969         str headers;
970         char buff[1024];
971
972         if(!rms_create_trans(msg))
973                 return 0;
974         di->action.cell = tmb.t_gett();
975         di->action.di = di;
976
977         if (strncmp(method->s, "CANCEL", 6) == 0) {
978                 LM_INFO("[CANCEL][%s][%.*s]\n", di->bridged_di->remote_uri.s, di->remote_tag.len, di->remote_tag.s);
979                 str cseq;
980                 cseq.s = buff;
981                 cseq.len = snprintf(buff, 1024, "%d", di->bridged_di->cseq);
982                 rms_sip_cancel(msg, &di->callid, &cseq);
983                 return 1;
984         }
985
986         if(tmb.t_suspend(
987                            msg, &di->action.tm_info.hash_index, &di->action.tm_info.label)
988                         < 0) {
989                 LM_ERR("t_suspend() failed\n");
990                 return 0;
991         }
992
993         snprintf(buff, 256, "Max-Forwards: 70\r\nContact: "
994                                                 "<sip:rms@%s:%d>\r\nContent-Type: application/sdp\r\n",
995                         di->local_ip.s, di->local_port);
996         headers.len = strlen(buff);
997         headers.s = buff;
998
999         LM_INFO("di[%p]callid[%.*s]cseq[%d]ruri[%d|%s]remote_uri[%s]local_uri[%s]\n", di, di->callid.len,
1000                         di->callid.s, di->bridged_di->cseq, di->bridged_di->contact_uri.len,
1001                         di->bridged_di->contact_uri.s, di->bridged_di->remote_uri.s,
1002                         di->bridged_di->local_uri.s);
1003         dlg_t *dialog = NULL;
1004
1005         if(tmb.new_dlg_uac(&di->bridged_di->callid, &di->bridged_di->local_tag,
1006                            di->bridged_di->cseq, &di->bridged_di->local_uri,
1007                            &di->bridged_di->remote_uri, &dialog)
1008                         < 0) {
1009                 LM_ERR("error in tmb.new_dlg_uac\n");
1010                 goto error;
1011         }
1012         dialog->id.rem_tag.s = di->bridged_di->remote_tag.s;
1013         dialog->id.rem_tag.len = di->bridged_di->remote_tag.len;
1014
1015         dialog->rem_target.s = di->bridged_di->contact_uri.s;
1016         dialog->rem_target.len = di->bridged_di->contact_uri.len;
1017
1018         set_uac_req(&uac_r, method, &headers, NULL, dialog,
1019                         TMCB_LOCAL_COMPLETED | TMCB_ON_FAILURE, forward_cb, &di->action);
1020         result = tmb.t_request_within(&uac_r);
1021         di->bridged_di->cseq = dialog->loc_seq.value;
1022         if(result < 0) {
1023                 LM_ERR("error in tmb.t_request\n");
1024                 goto error;
1025         } else {
1026                 LM_DBG("tmb.t_request_within ok\n");
1027         }
1028         return 1;
1029 error:
1030         rms_dialog_free(di->bridged_di);
1031         return -1;
1032 }
1033
1034 static int rms_sip_request_f(struct sip_msg *msg)
1035 {
1036         if(msg->parsed_uri_ok) {
1037                 LM_NOTICE("request[%s]\n", msg->parsed_uri.method_val.s);
1038         } else {
1039                 LM_NOTICE("request[%.*s] not parsed\n",
1040                                 msg->first_line.u.request.method.len,
1041                                 msg->first_line.u.request.method.s);
1042         }
1043         str *method = &msg->first_line.u.request.method;
1044         rms_dialog_info_t *di = rms_dialog_search_sync(msg);
1045         if(!di) {
1046                 rms_create_trans(msg);
1047                 LM_INFO("dialog not found ci[%.*s]\n", msg->callid->body.len,
1048                                 msg->callid->body.s);
1049                 if(!tmb.t_reply(msg, 481, "Call/Transaction Does Not Exist")) {
1050                         return -1;
1051                 }
1052                 return 1;
1053         }
1054
1055         if(di && strncmp(method->s, "BYE", 3) == 0) {
1056                 if(di->state == RMS_ST_CONNECTED)
1057                         di->state = RMS_ST_DISCONNECTING;
1058                 rms_action_t *a = rms_action_new(RMS_STOP);
1059                 if(!a)
1060                         return -1;
1061                 rms_action_add_sync(di, a);
1062                 if(di->bridged_di) { // bridged
1063                         LM_NOTICE("BYE in brigde mode\n");
1064                 } else { // connected localy
1065                         LM_NOTICE("BYE in local mode\n");
1066                         rms_disconnect(msg);
1067                         return 1;
1068                 }
1069         }
1070
1071         if(strncmp(method->s, "INVITE", 6) == 0 && di->remote_tag.len == 0) {
1072                 LM_NOTICE("initial INVITE\n");
1073                 return 1;
1074         } else {
1075                 LM_NOTICE("in dialog message\n");
1076         }
1077
1078         rms_sip_forward(di, msg, method);
1079         return 1;
1080 }
1081
1082 static int rms_answer_f(struct sip_msg *msg, char * _route)
1083 {
1084         str to_tag;
1085         str route;
1086
1087         int status = rms_create_trans(msg);
1088         if(status < 1)
1089                 return status;
1090
1091         if(get_str_fparam(&route, msg, (gparam_p)_route) != 0) {
1092                 route.len = strlen(rms_answer_default_route);
1093                 route.s = rms_answer_default_route;
1094         }
1095
1096         if(rms_dialog_search(msg))
1097                 return -1;
1098         rms_dialog_info_t *di = rms_dialog_new(msg);
1099         if(!di)
1100                 return -1;
1101         rms_dialog_add(di);
1102         rms_update_media_sockets(msg, di, &di->sdp_info_offer);
1103         parse_from(msg, di);
1104         tmb.t_get_reply_totag(msg, &to_tag);
1105         rms_str_dup(&di->local_tag, &to_tag, 1);
1106         LM_INFO("local_uri[%s]local_tag[%s]\n", di->local_uri.s, di->local_tag.s);
1107         if(!rms_sdp_prepare_new_body(&di->sdp_info_offer, di->media.pt)) {
1108                 LM_ERR("error preparing SDP body\n");
1109                 goto error;
1110         }
1111
1112         di->local_port = msg->rcv.dst_port;
1113         if(rms_answer_call(NULL, di, &di->sdp_info_offer) < 1) {
1114                 goto error;
1115         }
1116         LM_INFO("RTP session [%s:%d]<>[%s:%d]\n", di->media.local_ip.s,
1117                         di->media.local_port, di->media.remote_ip.s, di->media.remote_port);
1118
1119         rms_action_t *a = rms_action_new(RMS_START);
1120         if(!a)
1121                 return -1;
1122         a->route.len = route.len;
1123         a->route.s = route.s;
1124         rms_action_add(di, a);
1125         return 1;
1126 error:
1127         rms_dialog_rm(di);
1128         rms_dialog_free(di);
1129         return -1;
1130 }
1131
1132 static int rms_dialog_check_f(struct sip_msg *msg)
1133 {
1134         rms_dialog_info_t *di = rms_dialog_search_sync(msg);
1135         if(!di)
1136                 return -1;
1137         return 1;
1138 }
1139
1140 static int rms_hangup_f(struct sip_msg *msg)
1141 {
1142         rms_dialog_info_t *di = rms_dialog_search(msg);
1143         if(!di)
1144                 return -1;
1145         rms_action_t *a = rms_action_new(RMS_HANGUP);
1146         if(!a)
1147                 return -1;
1148         rms_action_add(di, a);
1149         return 1;
1150 }