]> sjero.net Git - linphone/blob - coreapi/sal_eXosip2.c
many bugfixes and improvements for multicall
[linphone] / coreapi / sal_eXosip2.c
1 /*
2 linphone
3 Copyright (C) 2010  Simon MORLAT (simon.morlat@free.fr)
4
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License
7 as published by the Free Software Foundation; either version 2
8 of the License, or (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18 */
19 #ifdef HAVE_CONFIG_H
20 #include "config.h"
21 #endif
22
23 #include "sal_eXosip2.h"
24
25 #include "offeranswer.h"
26
27 static void text_received(Sal *sal, eXosip_event_t *ev);
28
29 static void _osip_list_set_empty(osip_list_t *l, void (*freefunc)(void*)){
30         void *data;
31         while((data=osip_list_get(l,0))!=NULL){
32                 osip_list_remove(l,0);
33                 freefunc(data);
34         }
35 }
36
37 void sal_get_default_local_ip(Sal *sal, int address_family,char *ip, size_t iplen){
38         if (eXosip_guess_localip(address_family,ip,iplen)<0){
39                 /*default to something */
40                 strncpy(ip,address_family==AF_INET6 ? "::1" : "127.0.0.1",iplen);
41                 ms_error("Could not find default routable ip address !");
42         }
43 }
44
45
46 static SalOp * sal_find_call(Sal *sal, int cid){
47         const MSList *elem;
48         SalOp *op;
49         for(elem=sal->calls;elem!=NULL;elem=elem->next){
50                 op=(SalOp*)elem->data;
51                 if (op->cid==cid) return op;
52         }
53         return NULL;
54 }
55
56 static void sal_add_call(Sal *sal, SalOp *op){
57         sal->calls=ms_list_append(sal->calls,op);
58 }
59
60 static void sal_remove_call(Sal *sal, SalOp *op){
61         sal->calls=ms_list_remove(sal->calls, op);
62 }
63
64 static SalOp * sal_find_register(Sal *sal, int rid){
65         const MSList *elem;
66         SalOp *op;
67         for(elem=sal->registers;elem!=NULL;elem=elem->next){
68                 op=(SalOp*)elem->data;
69                 if (op->rid==rid) return op;
70         }
71         return NULL;
72 }
73
74 static void sal_add_register(Sal *sal, SalOp *op){
75         sal->registers=ms_list_append(sal->registers,op);
76 }
77
78 static void sal_remove_register(Sal *sal, int rid){
79         MSList *elem;
80         SalOp *op;
81         for(elem=sal->registers;elem!=NULL;elem=elem->next){
82                 op=(SalOp*)elem->data;
83                 if (op->rid==rid) {
84                         sal->registers=ms_list_remove_link(sal->registers,elem);
85                         return;
86                 }
87         }
88 }
89
90 static SalOp * sal_find_other(Sal *sal, osip_message_t *response){
91         const MSList *elem;
92         SalOp *op;
93         osip_call_id_t *callid=osip_message_get_call_id(response);
94         if (callid==NULL) {
95                 ms_error("There is no call-id in this response !");
96                 return NULL;
97         }
98         for(elem=sal->other_transactions;elem!=NULL;elem=elem->next){
99                 op=(SalOp*)elem->data;
100                 if (osip_call_id_match(callid,op->call_id)==0) return op;
101         }
102         return NULL;
103 }
104
105 static void sal_add_other(Sal *sal, SalOp *op, osip_message_t *request){
106         osip_call_id_t *callid=osip_message_get_call_id(request);
107         if (callid==NULL) {
108                 ms_error("There is no call id in the request !");
109                 return;
110         }
111         osip_call_id_clone(callid,&op->call_id);
112         sal->other_transactions=ms_list_append(sal->other_transactions,op);
113 }
114
115 static void sal_remove_other(Sal *sal, SalOp *op){
116         sal->other_transactions=ms_list_remove(sal->other_transactions,op);
117 }
118
119
120 static void sal_add_pending_auth(Sal *sal, SalOp *op){
121         sal->pending_auths=ms_list_append(sal->pending_auths,op);
122 }
123
124
125 static void sal_remove_pending_auth(Sal *sal, SalOp *op){
126         sal->pending_auths=ms_list_remove(sal->pending_auths,op);
127 }
128
129 void sal_exosip_fix_route(SalOp *op){
130         if (sal_op_get_route(op)!=NULL){
131                 osip_route_t *rt=NULL;
132                 osip_uri_param_t *lr_param=NULL;
133                 
134                 osip_route_init(&rt);
135                 if (osip_route_parse(rt,sal_op_get_route(op))<0){
136                         ms_warning("Bad route  %s!",sal_op_get_route(op));
137                         sal_op_set_route(op,NULL);
138                 }else{
139                         /* check if the lr parameter is set , if not add it */
140                         osip_uri_uparam_get_byname(rt->url, "lr", &lr_param);
141                         if (lr_param==NULL){
142                                 char *tmproute;
143                                 osip_uri_uparam_add(rt->url,osip_strdup("lr"),NULL);
144                                 osip_route_to_str(rt,&tmproute);
145                                 sal_op_set_route(op,tmproute);
146                                 osip_free(tmproute);
147                         }
148                 }
149                 osip_route_free(rt);
150         }
151 }
152
153 SalOp * sal_op_new(Sal *sal){
154         SalOp *op=ms_new(SalOp,1);
155         __sal_op_init(op,sal);
156         op->cid=op->did=op->tid=op->rid=op->nid=op->sid=-1;
157         op->result=NULL;
158         op->supports_session_timers=FALSE;
159         op->sdp_offering=TRUE;
160         op->pending_auth=NULL;
161         op->sdp_answer=NULL;
162         op->reinvite=FALSE;
163         op->call_id=NULL;
164         op->masquerade_via=FALSE;
165         op->auto_answer_asked=FALSE;
166         return op;
167 }
168
169 bool_t sal_call_autoanswer_asked(SalOp *op)
170 {
171         return op->auto_answer_asked;
172 }
173
174 void sal_op_release(SalOp *op){
175         if (op->sdp_answer)
176                 sdp_message_free(op->sdp_answer);
177         if (op->pending_auth)
178                 eXosip_event_free(op->pending_auth);
179         if (op->rid!=-1){
180                 sal_remove_register(op->base.root,op->rid);
181         }
182         if (op->cid!=-1){
183                 ms_message("Cleaning cid %i",op->cid);
184                 sal_remove_call(op->base.root,op);
185         }
186         if (op->sid!=-1){
187                 sal_remove_out_subscribe(op->base.root,op);
188         }
189         if (op->nid!=-1){
190                 sal_remove_in_subscribe(op->base.root,op);
191                 if (op->call_id)
192                         osip_call_id_free(op->call_id);
193                 op->call_id=NULL;
194         }
195         if (op->pending_auth){
196                 sal_remove_pending_auth(op->base.root,op);
197         }
198         if (op->result)
199                 sal_media_description_unref(op->result);
200         if (op->call_id){
201                 sal_remove_other(op->base.root,op);
202                 osip_call_id_free(op->call_id);
203         }
204         __sal_op_free(op);
205 }
206
207 static void _osip_trace_func(char *fi, int li, osip_trace_level_t level, char *chfr, va_list ap){
208         int ortp_level=ORTP_DEBUG;
209         switch(level){
210                 case OSIP_INFO1:
211                 case OSIP_INFO2:
212                 case OSIP_INFO3:
213                 case OSIP_INFO4:
214                         ortp_level=ORTP_MESSAGE;
215                         break;
216                 case OSIP_WARNING:
217                         ortp_level=ORTP_WARNING;
218                         break;
219                 case OSIP_ERROR:
220                 case OSIP_BUG:
221                         ortp_level=ORTP_ERROR;
222                         break;
223                 case OSIP_FATAL:
224                         ortp_level=ORTP_FATAL;
225                         break;
226                 case END_TRACE_LEVEL:
227                         break;
228         }
229         if (ortp_log_level_enabled(level)){
230                 int len=strlen(chfr);
231                 char *chfrdup=ortp_strdup(chfr);
232                 /*need to remove endline*/
233                 if (len>1){
234                         if (chfrdup[len-1]=='\n')
235                                 chfrdup[len-1]='\0';
236                         if (chfrdup[len-2]=='\r')
237                                 chfrdup[len-2]='\0';
238                 }
239                 ortp_logv(ortp_level,chfrdup,ap);
240                 ortp_free(chfrdup);
241         }
242 }
243
244
245 Sal * sal_init(){
246         static bool_t firsttime=TRUE;
247         Sal *sal;
248         if (firsttime){
249                 osip_trace_initialize_func (OSIP_INFO4,&_osip_trace_func);
250                 firsttime=FALSE;
251         }
252         eXosip_init();
253         sal=ms_new0(Sal,1);
254         sal->keepalive_period=30;
255         return sal;
256 }
257
258 void sal_uninit(Sal* sal){
259         eXosip_quit();
260         ms_free(sal);
261 }
262
263 void sal_set_user_pointer(Sal *sal, void *user_data){
264         sal->up=user_data;
265 }
266
267 void *sal_get_user_pointer(const Sal *sal){
268         return sal->up;
269 }
270
271 static void unimplemented_stub(){
272         ms_warning("Unimplemented SAL callback");
273 }
274
275 void sal_set_callbacks(Sal *ctx, const SalCallbacks *cbs){
276         memcpy(&ctx->callbacks,cbs,sizeof(*cbs));
277         if (ctx->callbacks.call_received==NULL) 
278                 ctx->callbacks.call_received=(SalOnCallReceived)unimplemented_stub;
279         if (ctx->callbacks.call_ringing==NULL) 
280                 ctx->callbacks.call_ringing=(SalOnCallRinging)unimplemented_stub;
281         if (ctx->callbacks.call_accepted==NULL) 
282                 ctx->callbacks.call_accepted=(SalOnCallAccepted)unimplemented_stub;
283         if (ctx->callbacks.call_failure==NULL) 
284                 ctx->callbacks.call_failure=(SalOnCallFailure)unimplemented_stub;
285         if (ctx->callbacks.call_terminated==NULL) 
286                 ctx->callbacks.call_terminated=(SalOnCallTerminated)unimplemented_stub;
287         if (ctx->callbacks.call_updating==NULL) 
288                 ctx->callbacks.call_updating=(SalOnCallUpdating)unimplemented_stub;
289         if (ctx->callbacks.auth_requested==NULL) 
290                 ctx->callbacks.auth_requested=(SalOnAuthRequested)unimplemented_stub;
291         if (ctx->callbacks.auth_success==NULL) 
292                 ctx->callbacks.auth_success=(SalOnAuthSuccess)unimplemented_stub;
293         if (ctx->callbacks.register_success==NULL) 
294                 ctx->callbacks.register_success=(SalOnRegisterSuccess)unimplemented_stub;
295         if (ctx->callbacks.register_failure==NULL) 
296                 ctx->callbacks.register_failure=(SalOnRegisterFailure)unimplemented_stub;
297         if (ctx->callbacks.dtmf_received==NULL) 
298                 ctx->callbacks.dtmf_received=(SalOnDtmfReceived)unimplemented_stub;
299         if (ctx->callbacks.notify==NULL)
300                 ctx->callbacks.notify=(SalOnNotify)unimplemented_stub;
301         if (ctx->callbacks.notify_presence==NULL)
302                 ctx->callbacks.notify_presence=(SalOnNotifyPresence)unimplemented_stub;
303         if (ctx->callbacks.subscribe_received==NULL)
304                 ctx->callbacks.subscribe_received=(SalOnSubscribeReceived)unimplemented_stub;
305         if (ctx->callbacks.text_received==NULL)
306                 ctx->callbacks.text_received=(SalOnTextReceived)unimplemented_stub;
307         if (ctx->callbacks.internal_message==NULL)
308                 ctx->callbacks.internal_message=(SalOnInternalMsg)unimplemented_stub;
309         if (ctx->callbacks.ping_reply==NULL)
310                 ctx->callbacks.ping_reply=(SalOnPingReply)unimplemented_stub;
311 }
312
313 int sal_unlisten_ports(Sal *ctx){
314         if (ctx->running){
315                 eXosip_quit();
316                 eXosip_init();
317         }
318         return 0;
319 }
320
321 int sal_listen_port(Sal *ctx, const char *addr, int port, SalTransport tr, int is_secure){
322         int err;
323         bool_t ipv6;
324         int proto=IPPROTO_UDP;
325         
326         switch (tr) {
327         case SalTransportDatagram:
328                 proto=IPPROTO_UDP;
329                 break;
330         case SalTransportStream:
331                 proto= IPPROTO_TCP;
332                 break;
333         default:
334                 ms_warning("unexpected proto, using datagram");
335         }
336
337         err=0;
338         eXosip_set_option(13,&err); /*13=EXOSIP_OPT_SRV_WITH_NAPTR, as it is an enum value, we can't use it unless we are sure of the
339                                         version of eXosip, which is not the case*/
340         /*see if it looks like an IPv6 address*/
341         ipv6=strchr(addr,':')!=NULL;
342         eXosip_enable_ipv6(ipv6);
343
344         if (is_secure){
345                 ms_fatal("SIP over TLS or DTLS is not supported yet.");
346                 return -1;
347         }
348         err=eXosip_listen_addr(proto, addr, port, ipv6 ?  PF_INET6 : PF_INET, 0);
349 #ifdef HAVE_EXOSIP_GET_SOCKET
350         ms_message("Exosip has socket number %i",eXosip_get_socket(proto));
351 #endif
352         eXosip_set_option (EXOSIP_OPT_UDP_KEEP_ALIVE, &ctx->keepalive_period);
353         ctx->running=TRUE;
354         return err;
355 }
356
357 ortp_socket_t sal_get_socket(Sal *ctx){
358 #ifdef HAVE_EXOSIP_GET_SOCKET
359         return eXosip_get_socket(IPPROTO_UDP);
360 #else
361         ms_warning("Sorry, eXosip does not have eXosip_get_socket() method");
362         return -1;
363 #endif
364 }
365
366 void sal_set_user_agent(Sal *ctx, const char *user_agent){
367         eXosip_set_user_agent(user_agent);
368 }
369
370 void sal_use_session_timers(Sal *ctx, int expires){
371         ctx->session_expires=expires;
372 }
373
374 MSList *sal_get_pending_auths(Sal *sal){
375         return ms_list_copy(sal->pending_auths);
376 }
377
378 static int extract_received_rport(osip_message_t *msg, const char **received, int *rportval){
379         osip_via_t *via=NULL;
380         osip_generic_param_t *param=NULL;
381         const char *rport=NULL;
382
383         *rportval=5060;
384         *received=NULL;
385         osip_message_get_via(msg,0,&via);
386         if (!via) return -1;
387
388         /* it is useless to do that with tcp since client socket might have a different port
389                 than the server socket.
390         */
391         if (strcasecmp(via->protocol,"tcp")==0) return -1;
392         
393         if (via->port && via->port[0]!='\0')
394                 *rportval=atoi(via->port);
395         
396         osip_via_param_get_byname(via,"rport",&param);
397         if (param) {
398                 rport=param->gvalue;
399                 if (rport && rport[0]!='\0') *rportval=atoi(rport);
400                 else *rportval=5060;
401                 *received=via->host;
402         }
403         param=NULL;
404         osip_via_param_get_byname(via,"received",&param);
405         if (param) *received=param->gvalue;
406
407         if (rport==NULL && *received==NULL) return -1;
408         return 0;
409 }
410
411 static void set_sdp(osip_message_t *sip,sdp_message_t *msg){
412         int sdplen;
413         char clen[10];
414         char *sdp=NULL;
415         sdp_message_to_str(msg,&sdp);
416         sdplen=strlen(sdp);
417         snprintf(clen,sizeof(clen),"%i",sdplen);
418         osip_message_set_body(sip,sdp,sdplen);
419         osip_message_set_content_type(sip,"application/sdp");
420         osip_message_set_content_length(sip,clen);
421         osip_free(sdp);
422 }
423
424 static void set_sdp_from_desc(osip_message_t *sip, const SalMediaDescription *desc){
425         sdp_message_t *msg=media_description_to_sdp(desc);
426         if (msg==NULL) {
427                 ms_error("Fail to print sdp message !");
428                 return;
429         }
430         set_sdp(sip,msg);
431         sdp_message_free(msg);
432 }
433
434 static void sdp_process(SalOp *h){
435         ms_message("Doing SDP offer/answer process");
436         if (h->result){
437                 sal_media_description_unref(h->result);
438         }
439         h->result=sal_media_description_new();
440         if (h->sdp_offering){   
441                 offer_answer_initiate_outgoing(h->base.local_media,h->base.remote_media,h->result);
442         }else{
443                 int i;
444                 offer_answer_initiate_incoming(h->base.local_media,h->base.remote_media,h->result);
445                 h->sdp_answer=media_description_to_sdp(h->result);
446                 strcpy(h->result->addr,h->base.remote_media->addr);
447                 h->result->bandwidth=h->base.remote_media->bandwidth;
448                 for(i=0;i<h->result->nstreams;++i){
449                         if (h->result->streams[i].port>0){
450                                 strcpy(h->result->streams[i].addr,h->base.remote_media->streams[i].addr);
451                                 h->result->streams[i].ptime=h->base.remote_media->streams[i].ptime;
452                                 h->result->streams[i].bandwidth=h->base.remote_media->streams[i].bandwidth;
453                                 h->result->streams[i].port=h->base.remote_media->streams[i].port;
454                         }
455                 }
456         }
457         
458 }
459
460 int sal_call_set_local_media_description(SalOp *h, SalMediaDescription *desc){
461         if (desc)
462                 sal_media_description_ref(desc);
463         if (h->base.local_media)
464                 sal_media_description_unref(h->base.local_media);
465         h->base.local_media=desc;
466         return 0;
467 }
468
469 int sal_call(SalOp *h, const char *from, const char *to){
470         int err;
471         osip_message_t *invite=NULL;
472         sal_op_set_from(h,from);
473         sal_op_set_to(h,to);
474         sal_exosip_fix_route(h);
475         err=eXosip_call_build_initial_invite(&invite,to,from,sal_op_get_route(h),"Phone call");
476         if (err!=0){
477                 ms_error("Could not create call.");
478                 return -1;
479         }
480         osip_message_set_allow(invite, "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, NOTIFY, MESSAGE, SUBSCRIBE, INFO");
481         if (h->base.contact){
482                 _osip_list_set_empty(&invite->contacts,(void (*)(void*))osip_contact_free);
483                 osip_message_set_contact(invite,h->base.contact);
484         }
485         if (h->base.root->session_expires!=0){
486                 osip_message_set_header(invite, "Session-expires", "200");
487                 osip_message_set_supported(invite, "timer");
488         }
489         if (h->base.local_media){
490                 h->sdp_offering=TRUE;
491                 set_sdp_from_desc(invite,h->base.local_media);
492         }else h->sdp_offering=FALSE;
493         eXosip_lock();
494         err=eXosip_call_send_initial_invite(invite);
495         eXosip_unlock();
496         h->cid=err;
497         if (err<0){
498                 ms_error("Fail to send invite !");
499                 return -1;
500         }else{
501                 sal_add_call(h->base.root,h);
502         }
503         return 0;
504 }
505
506 int sal_call_notify_ringing(SalOp *h){
507         eXosip_lock();
508         eXosip_call_send_answer(h->tid,180,NULL);
509         eXosip_unlock();
510         return 0;
511 }
512
513 int sal_call_accept(SalOp * h){
514         osip_message_t *msg;
515         const char *contact=sal_op_get_contact(h);
516         /* sends a 200 OK */
517         int err=eXosip_call_build_answer(h->tid,200,&msg);
518         if (err<0 || msg==NULL){
519                 ms_error("Fail to build answer for call: err=%i",err);
520                 return -1;
521         }
522         if (h->base.root->session_expires!=0){
523                 if (h->supports_session_timers) osip_message_set_supported(msg, "timer");
524         }
525
526         if (contact) {
527                 _osip_list_set_empty(&msg->contacts,(void (*)(void*))osip_contact_free);
528                 osip_message_set_contact(msg,contact);
529         }
530         
531         if (h->base.local_media){
532                 /*this is the case where we received an invite without SDP*/
533                 if (h->sdp_offering) {
534                         set_sdp_from_desc(msg,h->base.local_media);
535                 }else{
536                         if (h->sdp_answer){
537                                 set_sdp(msg,h->sdp_answer);
538                                 sdp_message_free(h->sdp_answer);
539                                 h->sdp_answer=NULL;
540                         }
541                 }
542         }else{
543                 ms_error("You are accepting a call but not defined any media capabilities !");
544         }
545         eXosip_call_send_answer(h->tid,200,msg);
546         return 0;
547 }
548
549 int sal_call_decline(SalOp *h, SalReason reason, const char *redirect){
550         if (reason==SalReasonBusy){
551                 eXosip_lock();
552                 eXosip_call_send_answer(h->tid,486,NULL);
553                 eXosip_unlock();
554         }
555         else if (reason==SalReasonTemporarilyUnavailable){
556                 eXosip_lock();
557                 eXosip_call_send_answer(h->tid,480,NULL);
558                 eXosip_unlock();
559         }else if (reason==SalReasonDoNotDisturb){
560                 eXosip_lock();
561                 eXosip_call_send_answer(h->tid,600,NULL);
562                 eXosip_unlock();
563         }else if (reason==SalReasonMedia){
564                 eXosip_lock();
565                 eXosip_call_send_answer(h->tid,415,NULL);
566                 eXosip_unlock();
567         }else if (redirect!=NULL && reason==SalReasonRedirect){
568                 osip_message_t *msg;
569                 int code;
570                 if (strstr(redirect,"sip:")!=0) code=302;
571                 else code=380;
572                 eXosip_lock();
573                 eXosip_call_build_answer(h->tid,code,&msg);
574                 osip_message_set_contact(msg,redirect);
575                 eXosip_call_send_answer(h->tid,code,msg);
576                 eXosip_unlock();
577         }else sal_call_terminate(h);
578         return 0;
579 }
580
581 SalMediaDescription * sal_call_get_final_media_description(SalOp *h){
582         if (h->base.local_media && h->base.remote_media && !h->result){
583                 sdp_process(h);
584         }
585         return h->result;
586 }
587
588 int sal_ping(SalOp *op, const char *from, const char *to){
589         osip_message_t *options=NULL;
590         
591         sal_op_set_from(op,from);
592         sal_op_set_to(op,to);
593         eXosip_options_build_request (&options, sal_op_get_to(op),
594                         sal_op_get_from(op),sal_op_get_route(op));
595         if (options){
596                 if (op->base.root->session_expires!=0){
597                         osip_message_set_header(options, "Session-expires", "200");
598                         osip_message_set_supported(options, "timer");
599                 }
600                 sal_add_other(sal_op_get_sal(op),op,options);
601                 return eXosip_options_send_request(options);
602         }
603         return -1;
604 }
605
606 int sal_refer_accept(SalOp *op){
607         osip_message_t *msg=NULL;
608         int err=0;
609         eXosip_lock();
610         err = eXosip_call_build_notify(op->did,EXOSIP_SUBCRSTATE_ACTIVE,&msg);
611         if(msg != NULL)
612         {
613                 osip_message_set_header(msg,(const char *)"event","refer");
614                 osip_message_set_content_type(msg,"message/sipfrag");
615                 osip_message_set_body(msg,"SIP/2.0 100 Trying",sizeof("SIP/2.0 100 Trying"));
616                 eXosip_call_send_request(op->did,msg);
617         }
618         else
619         {
620                 ms_error("could not get a notify built\n");
621         }
622         eXosip_unlock();
623         return err;
624 }
625
626 int sal_refer(SalOp *h, const char *refer_to){
627         osip_message_t *msg=NULL;
628         int err=0;
629         eXosip_lock();
630         eXosip_call_build_refer(h->did,refer_to, &msg);
631         if (msg) err=eXosip_call_send_request(h->did, msg);
632         else err=-1;
633         eXosip_unlock();
634         return err;
635 }
636
637 int sal_call_send_dtmf(SalOp *h, char dtmf){
638         osip_message_t *msg=NULL;
639         char dtmf_body[128];
640         char clen[10];
641
642         eXosip_lock();
643         eXosip_call_build_info(h->did,&msg);
644         if (msg){
645                 snprintf(dtmf_body, sizeof(dtmf_body), "Signal=%c\r\nDuration=250\r\n", dtmf);
646                 osip_message_set_body(msg,dtmf_body,strlen(dtmf_body));
647                 osip_message_set_content_type(msg,"application/dtmf-relay");
648                 snprintf(clen,sizeof(clen),"%lu",(unsigned long)strlen(dtmf_body));
649                 osip_message_set_content_length(msg,clen);              
650                 eXosip_call_send_request(h->did,msg);
651         }
652         eXosip_unlock();
653         return 0;
654 }
655
656 int sal_call_terminate(SalOp *h){
657         int err;
658         eXosip_lock();
659         err=eXosip_call_terminate(h->cid,h->did);
660         eXosip_unlock();
661         if (err!=0){
662                 ms_warning("Exosip could not terminate the call: cid=%i did=%i", h->cid,h->did);
663         }
664         sal_remove_call(h->base.root,h);
665         h->cid=-1;
666         return 0;
667 }
668
669 void sal_op_authenticate(SalOp *h, const SalAuthInfo *info){
670         if (h->pending_auth){
671                 const char *userid;
672                 if (info->userid==NULL || info->userid[0]=='\0') userid=info->username;
673                 else userid=info->userid;
674                 ms_message("Authentication info for %s %s added to eXosip", info->username,info->realm);
675                 eXosip_add_authentication_info (info->username,userid,
676                                       info->password, NULL,info->realm);
677                 eXosip_lock();
678                 eXosip_default_action(h->pending_auth);
679                 eXosip_unlock();
680                 ms_message("eXosip_default_action() done");
681                 eXosip_clear_authentication_info();
682                 eXosip_event_free(h->pending_auth);
683                 sal_remove_pending_auth(sal_op_get_sal(h),h);
684                 h->pending_auth=NULL;
685         }
686 }
687
688 static void set_network_origin(SalOp *op, osip_message_t *req){
689         const char *received=NULL;
690         int rport=5060;
691         char origin[64];
692         if (extract_received_rport(req,&received,&rport)!=0){
693                 osip_via_t *via=NULL;
694                 char *tmp;
695                 osip_message_get_via(req,0,&via);
696                 received=osip_via_get_host(via);
697                 tmp=osip_via_get_port(via);
698                 if (tmp) rport=atoi(tmp);
699         }
700         snprintf(origin,sizeof(origin)-1,"sip:%s:%i",received,rport);
701         __sal_op_set_network_origin(op,origin);
702 }
703
704 static SalOp *find_op(Sal *sal, eXosip_event_t *ev){
705         if (ev->cid>0){
706                 return sal_find_call(sal,ev->cid);
707         }
708         if (ev->rid>0){
709                 return sal_find_register(sal,ev->rid);
710         }
711         if (ev->response) return sal_find_other(sal,ev->response);
712         return NULL;
713 }
714
715 static void inc_new_call(Sal *sal, eXosip_event_t *ev){
716         SalOp *op=sal_op_new(sal);
717         osip_from_t *from,*to;
718         osip_call_info_t *call_info;
719         char *tmp;
720         sdp_message_t *sdp=eXosip_get_sdp_info(ev->request);
721
722         set_network_origin(op,ev->request);
723         
724         if (sdp){
725                 op->sdp_offering=FALSE;
726                 op->base.remote_media=sal_media_description_new();
727                 sdp_to_media_description(sdp,op->base.remote_media);
728                 sdp_message_free(sdp);
729         }else op->sdp_offering=TRUE;
730
731         from=osip_message_get_from(ev->request);
732         to=osip_message_get_to(ev->request);
733         osip_from_to_str(from,&tmp);
734         sal_op_set_from(op,tmp);
735         osip_free(tmp);
736         osip_from_to_str(to,&tmp);
737         sal_op_set_to(op,tmp);
738         osip_free(tmp);
739
740         osip_message_get_call_info(ev->request,0,&call_info);
741         if(call_info)
742         {
743                 osip_call_info_to_str(call_info,&tmp);
744                 if( strstr(tmp,"answer-after=") != NULL)
745                 {
746                         op->auto_answer_asked=TRUE;
747                         ms_message("The caller asked to automatically answer the call(Emergency?)\n");
748                 }
749                 osip_free(tmp);
750         }
751
752         op->tid=ev->tid;
753         op->cid=ev->cid;
754         op->did=ev->did;
755         
756         sal_add_call(op->base.root,op);
757         sal->callbacks.call_received(op);
758 }
759
760 static void handle_reinvite(Sal *sal,  eXosip_event_t *ev){
761         SalOp *op=find_op(sal,ev);
762         sdp_message_t *sdp;
763         osip_message_t *msg=NULL;
764
765         if (op==NULL) {
766                 ms_warning("Reinvite for non-existing operation !");
767                 return;
768         }
769         op->reinvite=TRUE;
770         op->tid=ev->tid;
771         sdp=eXosip_get_sdp_info(ev->request);
772         if (op->base.remote_media){
773                 sal_media_description_unref(op->base.remote_media);
774                 op->base.remote_media=NULL;
775         }
776         if (op->result){
777                 sal_media_description_unref(op->result);
778                 op->result=NULL;
779         }
780         if (sdp){
781                 op->sdp_offering=FALSE;
782                 op->base.remote_media=sal_media_description_new();
783                 sdp_to_media_description(sdp,op->base.remote_media);
784                 sdp_message_free(sdp);
785                 sal->callbacks.call_updating(op);
786         }else {
787                 op->sdp_offering=TRUE;
788                 eXosip_lock();
789                 eXosip_call_build_answer(ev->tid,200,&msg);
790                 if (msg!=NULL){
791                         set_sdp_from_desc(msg,op->base.local_media);
792                         eXosip_call_send_answer(ev->tid,200,msg);
793                 }
794                 eXosip_unlock();
795         }
796         
797 }
798
799 static void handle_ack(Sal *sal,  eXosip_event_t *ev){
800         SalOp *op=find_op(sal,ev);
801         sdp_message_t *sdp;
802
803         if (op==NULL) {
804                 ms_warning("ack for non-existing call !");
805                 return;
806         }
807         sdp=eXosip_get_sdp_info(ev->ack);
808         if (sdp){
809                 op->base.remote_media=sal_media_description_new();
810                 sdp_to_media_description(sdp,op->base.remote_media);
811                 sdp_process(op);
812                 sdp_message_free(sdp);
813         }
814         if (op->reinvite){
815                 if (sdp) sal->callbacks.call_updating(op);
816                 op->reinvite=FALSE;
817         }else{
818                 sal->callbacks.call_ack(op);
819         }
820 }
821
822 static void update_contact_from_response(SalOp *op, osip_message_t *response){
823         const char *received;
824         int rport;
825         if (extract_received_rport(response,&received,&rport)==0){
826                 const char *contact=sal_op_get_contact(op);
827                 if (!contact){
828                         /*no contact given yet, use from instead*/
829                         contact=sal_op_get_from(op);
830                 }
831                 if (contact){
832                         SalAddress *addr=sal_address_new(contact);
833                         char *tmp;
834                         sal_address_set_domain(addr,received);
835                         sal_address_set_port_int(addr,rport);
836                         tmp=sal_address_as_string(addr);
837                         ms_message("Contact address updated to %s for this dialog",tmp);
838                         sal_op_set_contact(op,tmp);
839                         ms_free(tmp);
840                 }
841         }
842 }
843
844 static int call_proceeding(Sal *sal, eXosip_event_t *ev){
845         SalOp *op=find_op(sal,ev);
846         
847         if (op==NULL) {
848                 ms_warning("This call has been canceled.");
849                 eXosip_lock();
850                 eXosip_call_terminate(ev->cid,ev->did);
851                 eXosip_unlock();
852                 return -1;
853         }
854         if (ev->did>0)
855                 op->did=ev->did;
856         op->tid=ev->tid;
857         
858         /* update contact if received and rport are set by the server
859          note: will only be used by remote for next INVITE, if any...*/
860         update_contact_from_response(op,ev->response);
861         return 0;
862 }
863
864 static void call_ringing(Sal *sal, eXosip_event_t *ev){
865         sdp_message_t *sdp;
866         SalOp *op=find_op(sal,ev);
867         if (call_proceeding(sal, ev)==-1) return;
868         
869         sdp=eXosip_get_sdp_info(ev->response);
870         if (sdp){
871                 op->base.remote_media=sal_media_description_new();
872                 sdp_to_media_description(sdp,op->base.remote_media);
873                 sdp_message_free(sdp);
874                 if (op->base.local_media) sdp_process(op);
875         }
876         sal->callbacks.call_ringing(op);
877 }
878
879 static void call_accepted(Sal *sal, eXosip_event_t *ev){
880         sdp_message_t *sdp;
881         osip_message_t *msg=NULL;
882         SalOp *op=find_op(sal,ev);
883         const char *contact;
884         
885         if (op==NULL){
886                 ms_error("A closed call is accepted ?");
887                 return;
888         }
889
890         op->did=ev->did;
891         
892         sdp=eXosip_get_sdp_info(ev->response);
893         if (sdp){
894                 op->base.remote_media=sal_media_description_new();
895                 sdp_to_media_description(sdp,op->base.remote_media);
896                 sdp_message_free(sdp);
897                 if (op->base.local_media) sdp_process(op);
898         }
899         eXosip_call_build_ack(ev->did,&msg);
900         contact=sal_op_get_contact(op);
901         if (contact) {
902                 _osip_list_set_empty(&msg->contacts,(void (*)(void*))osip_contact_free);
903                 osip_message_set_contact(msg,contact);
904         }
905         if (op->sdp_answer){
906                 set_sdp(msg,op->sdp_answer);
907                 sdp_message_free(op->sdp_answer);
908                 op->sdp_answer=NULL;
909         }
910         eXosip_call_send_ack(ev->did,msg);
911         sal->callbacks.call_accepted(op);
912 }
913
914 static void call_terminated(Sal *sal, eXosip_event_t *ev){
915         char *from=NULL;
916         SalOp *op=find_op(sal,ev);
917         if (op==NULL){
918                 ms_warning("Call terminated for already closed call ?");
919                 return;
920         }
921         if (ev->request){
922                 osip_from_to_str(ev->request->from,&from);
923         }
924         sal_remove_call(sal,op);
925         op->cid=-1;
926         sal->callbacks.call_terminated(op,from!=NULL ? from : sal_op_get_from(op));
927         if (from) osip_free(from);
928 }
929
930 static void call_released(Sal *sal, eXosip_event_t *ev){
931         SalOp *op=find_op(sal,ev);
932         if (op==NULL){
933                 ms_warning("No op associated to this call_released()");
934                 return;
935         }
936         op->cid=-1;
937         if (op->did==-1) 
938                 sal->callbacks.call_failure(op,SalErrorNoResponse,SalReasonUnknown,NULL, 487);
939 }
940
941 static int get_auth_data_from_response(osip_message_t *resp, const char **realm, const char **username){
942         const char *prx_realm=NULL,*www_realm=NULL;
943         osip_proxy_authenticate_t *prx_auth;
944         osip_www_authenticate_t *www_auth;
945         
946         *username=osip_uri_get_username(resp->from->url);
947         prx_auth=(osip_proxy_authenticate_t*)osip_list_get(&resp->proxy_authenticates,0);
948         www_auth=(osip_proxy_authenticate_t*)osip_list_get(&resp->www_authenticates,0);
949         if (prx_auth!=NULL)
950                 prx_realm=osip_proxy_authenticate_get_realm(prx_auth);
951         if (www_auth!=NULL)
952                 www_realm=osip_www_authenticate_get_realm(www_auth);
953
954         if (prx_realm){
955                 *realm=prx_realm;
956         }else if (www_realm){
957                 *realm=www_realm;
958         }else{
959                 return -1;
960         }
961         return 0;
962 }
963
964 static int get_auth_data_from_request(osip_message_t *msg, const char **realm, const char **username){
965         osip_authorization_t *auth=NULL;
966         osip_proxy_authorization_t *prx_auth=NULL;
967         
968         *username=osip_uri_get_username(msg->from->url);
969         osip_message_get_authorization(msg, 0, &auth);
970         if (auth){
971                 *realm=osip_authorization_get_realm(auth);
972                 return 0;
973         }
974         osip_message_get_proxy_authorization(msg,0,&prx_auth);
975         if (prx_auth){
976                 *realm=osip_proxy_authorization_get_realm(prx_auth);
977                 return 0;
978         }
979         return -1;
980 }
981
982 static int get_auth_data(eXosip_event_t *ev, const char **realm, const char **username){
983         if (ev->response && get_auth_data_from_response(ev->response,realm,username)==0) return 0;
984         if (ev->request && get_auth_data_from_request(ev->request,realm,username)==0) return 0;
985         return -1;
986 }
987
988 int sal_op_get_auth_requested(SalOp *op, const char **realm, const char **username){
989         if (op->pending_auth){
990                 return get_auth_data(op->pending_auth,realm,username);
991         }
992         return -1;
993 }
994
995 static bool_t process_authentication(Sal *sal, eXosip_event_t *ev){
996         SalOp *op;
997         const char *username,*realm;
998         op=find_op(sal,ev);
999         if (op==NULL){
1000                 ms_warning("No operation associated with this authentication !");
1001                 return TRUE;
1002         }
1003         if (get_auth_data(ev,&realm,&username)==0){
1004                 if (op->pending_auth!=NULL)
1005                         eXosip_event_free(op->pending_auth);
1006                 op->pending_auth=ev;
1007                 sal_add_pending_auth (sal,op);
1008                 sal->callbacks.auth_requested(op,realm,username);
1009                 return FALSE;
1010         }
1011         return TRUE;
1012 }
1013
1014 static void authentication_ok(Sal *sal, eXosip_event_t *ev){
1015         SalOp *op;
1016         const char *username,*realm;
1017         op=find_op(sal,ev);
1018         if (op==NULL){
1019                 ms_warning("No operation associated with this authentication_ok!");
1020                 return ;
1021         }
1022         if (get_auth_data(ev,&realm,&username)==0){
1023                 sal->callbacks.auth_success(op,realm,username);
1024         }
1025 }
1026
1027 static bool_t call_failure(Sal *sal, eXosip_event_t *ev){
1028         SalOp *op;
1029         int code=0;
1030         char* computedReason=NULL;
1031         const char *reason=NULL;
1032         SalError error=SalErrorUnknown;
1033         SalReason sr=SalReasonUnknown;
1034         
1035
1036         op=(SalOp*)find_op(sal,ev);
1037
1038         if (op==NULL) {
1039                 ms_warning("Call failure reported for a closed call, ignored.");
1040                 return TRUE;
1041         }
1042
1043         if (ev->response){
1044                 code=osip_message_get_status_code(ev->response);
1045                 reason=osip_message_get_reason_phrase(ev->response);
1046                 osip_header_t *h=NULL;
1047                 if (!osip_message_header_get_byname(    ev->response
1048                                                                                         ,"Reason"
1049                                                                                         ,0
1050                                                                                         ,&h)) {
1051                         computedReason = ms_strdup_printf("%s %s",reason,osip_header_get_value(h));
1052                         reason = computedReason;
1053
1054                 }
1055         }
1056         switch(code)
1057         {
1058                 case 401:
1059                 case 407:
1060                         return process_authentication(sal,ev);
1061                         break;
1062                 case 400:
1063                         error=SalErrorUnknown;
1064                 break;
1065                 case 404:
1066                         error=SalErrorFailure;
1067                         sr=SalReasonNotFound;
1068                 break;
1069                 case 415:
1070                         error=SalErrorFailure;
1071                         sr=SalReasonMedia;
1072                 break;
1073                 case 422:
1074                         eXosip_default_action(ev);
1075                         return TRUE;
1076                 break;
1077                 case 480:
1078                         error=SalErrorFailure;
1079                         sr=SalReasonTemporarilyUnavailable;
1080                 case 486:
1081                         error=SalErrorFailure;
1082                         sr=SalReasonBusy;
1083                 break;
1084                 case 487:
1085                 break;
1086                 case 600:
1087                         error=SalErrorFailure;
1088                         sr=SalReasonDoNotDisturb;
1089                 break;
1090                 case 603:
1091                         error=SalErrorFailure;
1092                         sr=SalReasonDeclined;
1093                 break;
1094                 default:
1095                         if (code>0){
1096                                 error=SalErrorFailure;
1097                                 sr=SalReasonUnknown;
1098                         }else error=SalErrorNoResponse;
1099         }
1100         sal->callbacks.call_failure(op,error,sr,reason,code);
1101         if (computedReason != NULL){
1102                 ms_free(computedReason);
1103         }
1104         return TRUE;
1105 }
1106
1107
1108 static void process_media_control_xml(Sal *sal, eXosip_event_t *ev){
1109         SalOp *op=find_op(sal,ev);
1110         osip_body_t *body=NULL;
1111
1112         if (op==NULL){
1113                 ms_warning("media control xml received without operation context!");
1114                 return ;
1115         }
1116         
1117         osip_message_get_body(ev->request,0,&body);
1118         if (body && body->body!=NULL &&
1119                 strstr(body->body,"picture_fast_update")){
1120                 osip_message_t *ans=NULL;
1121                 ms_message("Receiving VFU request !");
1122                 if (sal->callbacks.vfu_request){
1123                         sal->callbacks.vfu_request(op);
1124                         eXosip_call_build_answer(ev->tid,200,&ans);
1125                         if (ans)
1126                                 eXosip_call_send_answer(ev->tid,200,ans);
1127                 }
1128         }
1129 }
1130
1131 static void process_dtmf_relay(Sal *sal, eXosip_event_t *ev){
1132         SalOp *op=find_op(sal,ev);
1133         osip_body_t *body=NULL;
1134
1135         if (op==NULL){
1136                 ms_warning("media dtmf relay received without operation context!");
1137                 return ;
1138         }
1139         
1140         osip_message_get_body(ev->request,0,&body);
1141         if (body && body->body!=NULL){
1142                 osip_message_t *ans=NULL;
1143                 const char *name=strstr(body->body,"Signal");
1144                 if (name==NULL) name=strstr(body->body,"signal");
1145                 if (name==NULL) {
1146                         ms_warning("Could not extract the dtmf name from the SIP INFO.");
1147                 }else{
1148                         char tmp[2];
1149                         name+=strlen("signal");
1150                         if (sscanf(name," = %1s",tmp)==1){
1151                                 ms_message("Receiving dtmf %s via SIP INFO.",tmp);
1152                                 if (sal->callbacks.dtmf_received != NULL)
1153                                         sal->callbacks.dtmf_received(op, tmp[0]);
1154                         }
1155                 }
1156                 eXosip_call_build_answer(ev->tid,200,&ans);
1157                 if (ans)
1158                         eXosip_call_send_answer(ev->tid,200,ans);
1159         }
1160 }
1161
1162 static void call_message_new(Sal *sal, eXosip_event_t *ev){
1163         osip_message_t *ans=NULL;
1164         if (ev->request){
1165                 if (MSG_IS_INFO(ev->request)){
1166                         osip_content_type_t *ct;
1167                         ct=osip_message_get_content_type(ev->request);
1168                         if (ct && ct->subtype){
1169                                 if (strcmp(ct->subtype,"media_control+xml")==0)
1170                                         process_media_control_xml(sal,ev);
1171                                 else if (strcmp(ct->subtype,"dtmf-relay")==0)
1172                                         process_dtmf_relay(sal,ev);
1173                                 else {
1174                                         ms_message("Unhandled SIP INFO.");
1175                                         /*send an "Not implemented" answer*/
1176                                         eXosip_lock();
1177                                         eXosip_call_build_answer(ev->tid,501,&ans);
1178                                         if (ans)
1179                                                 eXosip_call_send_answer(ev->tid,501,ans);
1180                                         eXosip_unlock();
1181                                 }
1182                         }else{
1183                                 /*empty SIP INFO, probably to test we are alive. Send an empty answer*/
1184                                 eXosip_lock();
1185                                 eXosip_call_build_answer(ev->tid,200,&ans);
1186                                 if (ans)
1187                                         eXosip_call_send_answer(ev->tid,200,ans);
1188                                 eXosip_unlock();
1189                         }
1190                 }
1191                 if(MSG_IS_MESSAGE(ev->request)){
1192                         /* SIP messages could be received into call */
1193                         text_received(sal, ev);
1194                         eXosip_lock();
1195                         eXosip_call_build_answer(ev->tid,200,&ans);
1196                         if (ans)
1197                                 eXosip_call_send_answer(ev->tid,200,ans);
1198                         eXosip_unlock();
1199                 }
1200                 if(MSG_IS_REFER(ev->request)){
1201                         osip_header_t *h=NULL;
1202                         SalOp *op=find_op(sal,ev);
1203                         
1204                         ms_message("Receiving REFER request !");
1205                         osip_message_header_get_byname(ev->request,"Refer-To",0,&h);
1206                         eXosip_lock();
1207                         eXosip_call_build_answer(ev->tid,202,&ans);
1208                         if (ans)
1209                                 eXosip_call_send_answer(ev->tid,202,ans);
1210                         eXosip_unlock();
1211                         if (h){
1212                                 sal->callbacks.refer_received(sal,op,h->hvalue);
1213                         }
1214                         else
1215                         {
1216                                 ms_warning("cannot do anything with the refer without destination\n");
1217                         }
1218                 }
1219                 if(MSG_IS_NOTIFY(ev->request)){
1220                         osip_header_t *h=NULL;
1221                         char *from=NULL;
1222                         SalOp *op=find_op(sal,ev);
1223
1224                         ms_message("Receiving NOTIFY request !");
1225                         osip_from_to_str(ev->request->from,&from);
1226                         osip_message_header_get_byname(ev->request,"Event",0,&h);
1227                         if(h)
1228                                 sal->callbacks.notify(op,from,h->hvalue);
1229                         /*answer that we received the notify*/
1230                         eXosip_lock();
1231                         eXosip_call_build_answer(ev->tid,200,&ans);
1232                         if (ans)
1233                                 eXosip_call_send_answer(ev->tid,200,ans);
1234                         eXosip_unlock();
1235                         osip_free(from);
1236                 }
1237         }else ms_warning("call_message_new: No request ?");
1238 }
1239
1240 static void inc_update(Sal *sal, eXosip_event_t *ev){
1241         osip_message_t *msg=NULL;
1242         ms_message("Processing incoming UPDATE");
1243         eXosip_lock();
1244         eXosip_message_build_answer(ev->tid,200,&msg);
1245         if (msg!=NULL)
1246                 eXosip_message_send_answer(ev->tid,200,msg);
1247         eXosip_unlock();
1248 }
1249
1250 static bool_t comes_from_local_if(osip_message_t *msg){
1251         osip_via_t *via=NULL;
1252         osip_message_get_via(msg,0,&via);
1253         if (via){
1254                 const char *host;
1255                 host=osip_via_get_host(via);
1256                 if (strcmp(host,"127.0.0.1")==0 || strcmp(host,"::1")==0){
1257                         osip_generic_param_t *param=NULL;
1258                         osip_via_param_get_byname(via,"received",&param);
1259                         if (param==NULL) return TRUE;
1260                         if (param->gvalue &&
1261                                 (strcmp(param->gvalue,"127.0.0.1")==0 || strcmp(param->gvalue,"::1")==0)){
1262                                 return TRUE;
1263                         }
1264                 }
1265         }
1266         return FALSE;
1267 }
1268
1269 static void text_received(Sal *sal, eXosip_event_t *ev){
1270         osip_body_t *body=NULL;
1271         char *from=NULL,*msg;
1272         
1273         osip_message_get_body(ev->request,0,&body);
1274         if (body==NULL){
1275                 ms_error("Could not get text message from SIP body");
1276                 return;
1277         }
1278         msg=body->body;
1279         osip_from_to_str(ev->request->from,&from);
1280         sal->callbacks.text_received(sal,from,msg);
1281         osip_free(from);
1282 }
1283
1284 static void other_request(Sal *sal, eXosip_event_t *ev){
1285         ms_message("in other_request");
1286         if (ev->request==NULL) return;
1287         if (strcmp(ev->request->sip_method,"MESSAGE")==0){
1288                 text_received(sal,ev);
1289                 eXosip_message_send_answer(ev->tid,200,NULL);
1290         }else if (strcmp(ev->request->sip_method,"OPTIONS")==0){
1291                 osip_message_t *options=NULL;
1292                 eXosip_options_build_answer(ev->tid,200,&options);
1293                 osip_message_set_allow(options,"INVITE, ACK, BYE, CANCEL, OPTIONS, MESSAGE, SUBSCRIBE, NOTIFY, INFO");
1294                 osip_message_set_accept(options,"application/sdp");
1295                 eXosip_options_send_answer(ev->tid,200,options);
1296         }else if (strcmp(ev->request->sip_method,"WAKEUP")==0
1297                 && comes_from_local_if(ev->request)) {
1298                 eXosip_message_send_answer(ev->tid,200,NULL);
1299                 ms_message("Receiving WAKEUP request !");
1300                 sal->callbacks.internal_message(sal,"WAKEUP");
1301         }else if (strncmp(ev->request->sip_method, "REFER", 5) == 0){
1302                 ms_message("Receiving REFER request !");
1303                 if (comes_from_local_if(ev->request)) {
1304                         osip_header_t *h=NULL;
1305                         osip_message_header_get_byname(ev->request,"Refer-To",0,&h);
1306                         eXosip_message_send_answer(ev->tid,200,NULL);
1307                         if (h){
1308                                 sal->callbacks.refer_received(sal,NULL,h->hvalue);
1309                         }
1310                 }else ms_warning("Ignored REFER not coming from this local loopback interface.");
1311         }else if (strncmp(ev->request->sip_method, "UPDATE", 6) == 0){
1312                 inc_update(sal,ev);
1313     }else {
1314                 char *tmp=NULL;
1315                 size_t msglen=0;
1316                 osip_message_to_str(ev->request,&tmp,&msglen);
1317                 if (tmp){
1318                         ms_message("Unsupported request received:\n%s",tmp);
1319                         osip_free(tmp);
1320                 }
1321                 /*answer with a 501 Not implemented*/
1322                 eXosip_message_send_answer(ev->tid,501,NULL);
1323         }
1324 }
1325
1326 static void masquerade_via(osip_message_t *msg, const char *ip, const char *port){
1327         osip_via_t *via=NULL;
1328         osip_message_get_via(msg,0,&via);
1329         if (via){
1330                 osip_free(via->port);
1331                 via->port=osip_strdup(port);
1332                 osip_free(via->host);
1333                 via->host=osip_strdup(ip);
1334         }
1335 }
1336
1337 static bool_t register_again_with_updated_contact(SalOp *op, osip_message_t *orig_request, osip_message_t *last_answer){
1338         osip_message_t *msg;
1339         const char *received;
1340         int rport;
1341         osip_contact_t *ctt=NULL;
1342         char *tmp;
1343         char port[20];
1344         SalAddress *addr;
1345         
1346         if (extract_received_rport(last_answer,&received,&rport)==-1) return FALSE;
1347         osip_message_get_contact(orig_request,0,&ctt);
1348         if (strcmp(ctt->url->host,received)==0){
1349                 /*ip address matches, check ports*/
1350                 const char *contact_port=ctt->url->port;
1351                 if (contact_port==NULL || contact_port[0]=='\0')
1352                         contact_port="5060";
1353                 if (atoi(contact_port)==rport){
1354                         ms_message("Register has up to date contact, doing nothing.");
1355                         return FALSE;
1356                 }else ms_message("ports do not match, need to update the register (%s <> %i)", contact_port,rport);
1357         }
1358         eXosip_lock();
1359         msg=NULL;
1360         eXosip_register_build_register(op->rid,op->expires,&msg);
1361         if (msg==NULL){
1362                 eXosip_unlock();
1363                 ms_warning("Fail to create a contact updated register.");
1364                 return FALSE;
1365         }
1366         osip_message_get_contact(msg,0,&ctt);
1367         if (ctt->url->host!=NULL){
1368                 osip_free(ctt->url->host);
1369         }
1370         ctt->url->host=osip_strdup(received);
1371         if (ctt->url->port!=NULL){
1372                 osip_free(ctt->url->port);
1373         }
1374         snprintf(port,sizeof(port),"%i",rport);
1375         ctt->url->port=osip_strdup(port);
1376         if (op->masquerade_via) masquerade_via(msg,received,port);
1377         eXosip_register_send_register(op->rid,msg);
1378         eXosip_unlock();
1379         osip_contact_to_str(ctt,&tmp);
1380         addr=sal_address_new(tmp);
1381         osip_free(tmp);
1382         sal_address_clean(addr);
1383         tmp=sal_address_as_string(addr);
1384         sal_op_set_contact(op,tmp);
1385         sal_address_destroy(addr);
1386         ms_message("Resending new register with updated contact %s",tmp);
1387         ms_free(tmp);
1388         return TRUE;
1389 }
1390
1391 static void registration_success(Sal *sal, eXosip_event_t *ev){
1392         SalOp *op=sal_find_register(sal,ev->rid);
1393         osip_header_t *h=NULL;
1394         bool_t registered;
1395         if (op==NULL){
1396                 ms_error("Receiving register response for unknown operation");
1397                 return;
1398         }
1399         osip_message_get_expires(ev->request,0,&h);
1400         if (h!=NULL && atoi(h->hvalue)!=0){
1401                 registered=TRUE;
1402                 if (!register_again_with_updated_contact(op,ev->request,ev->response)){
1403                         sal->callbacks.register_success(op,registered);
1404                 }
1405         }else registered=FALSE;
1406 }
1407
1408 static bool_t registration_failure(Sal *sal, eXosip_event_t *ev){
1409         int status_code=0;
1410         const char *reason=NULL;
1411         SalOp *op=sal_find_register(sal,ev->rid);
1412         SalReason sr=SalReasonUnknown;
1413         SalError se=SalErrorUnknown;
1414         
1415         if (op==NULL){
1416                 ms_error("Receiving register failure for unknown operation");
1417                 return TRUE;
1418         }
1419         if (ev->response){
1420                 status_code=osip_message_get_status_code(ev->response);
1421                 reason=osip_message_get_reason_phrase(ev->response);
1422         }else return TRUE;
1423         switch(status_code){
1424                 case 401:
1425                 case 407:
1426                         return process_authentication(sal,ev);
1427                         break;
1428                 case 606: /*Not acceptable, workaround for proxies that don't like private addresses
1429                                  in vias, such as ekiga.net 
1430                                  On the opposite, freephonie.net bugs when via are masqueraded.
1431                                  */
1432                         op->masquerade_via=TRUE;
1433                 default:
1434                         /* if contact is up to date, process the failure, otherwise resend a new register with
1435                                 updated contact first, just in case the faillure is due to incorrect contact */
1436                         if (register_again_with_updated_contact(op,ev->request,ev->response))
1437                                 return TRUE; /*we are retrying with an updated contact*/
1438                         if (status_code==403){
1439                                 se=SalErrorFailure;
1440                                 sr=SalReasonForbidden;
1441                         }else if (status_code==0){
1442                                 se=SalErrorNoResponse;
1443                         }
1444                         sal->callbacks.register_failure(op,se,sr,reason);
1445         }
1446         return TRUE;
1447 }
1448
1449 static void other_request_reply(Sal *sal,eXosip_event_t *ev){
1450         SalOp *op=find_op(sal,ev);
1451
1452         if (op==NULL){
1453                 ms_warning("other_request_reply(): Receiving response to unknown request.");
1454                 return;
1455         }
1456         if (ev->response){
1457                 update_contact_from_response(op,ev->response);
1458                 if (ev->request && strcmp(osip_message_get_method(ev->request),"OPTIONS")==0)
1459                         sal->callbacks.ping_reply(op);
1460         }
1461 }
1462
1463 static bool_t process_event(Sal *sal, eXosip_event_t *ev){
1464         ms_message("linphone process event get a message %d\n",ev->type);
1465         switch(ev->type){
1466                 case EXOSIP_CALL_ANSWERED:
1467                         ms_message("CALL_ANSWERED\n");
1468                         call_accepted(sal,ev);
1469                         authentication_ok(sal,ev);
1470                         break;
1471                 case EXOSIP_CALL_CLOSED:
1472                 case EXOSIP_CALL_CANCELLED:
1473                         ms_message("CALL_CLOSED or CANCELLED\n");
1474                         call_terminated(sal,ev);
1475                         break;
1476                 case EXOSIP_CALL_TIMEOUT:
1477                 case EXOSIP_CALL_NOANSWER:
1478                         ms_message("CALL_TIMEOUT or NOANSWER\n");
1479                         return call_failure(sal,ev);
1480                         break;
1481                 case EXOSIP_CALL_REQUESTFAILURE:
1482                 case EXOSIP_CALL_GLOBALFAILURE:
1483                 case EXOSIP_CALL_SERVERFAILURE:
1484                         ms_message("CALL_REQUESTFAILURE or GLOBALFAILURE or SERVERFAILURE\n");
1485                         return call_failure(sal,ev);
1486                         break;
1487                 case EXOSIP_CALL_RELEASED:
1488                         ms_message("CALL_RELEASED\n");
1489                         call_released(sal, ev);
1490                         break;
1491                 case EXOSIP_CALL_INVITE:
1492                         ms_message("CALL_NEW\n");
1493                         inc_new_call(sal,ev);
1494                         break;
1495                 case EXOSIP_CALL_REINVITE:
1496                         handle_reinvite(sal,ev);
1497                         break;
1498                 case EXOSIP_CALL_ACK:
1499                         ms_message("CALL_ACK");
1500                         handle_ack(sal,ev);
1501                         break;
1502                 case EXOSIP_CALL_REDIRECTED:
1503                         ms_message("CALL_REDIRECTED");
1504                         eXosip_default_action(ev);
1505                         break;
1506                 case EXOSIP_CALL_PROCEEDING:
1507                         ms_message("CALL_PROCEEDING");
1508                         call_proceeding(sal,ev);
1509                         break;
1510                 case EXOSIP_CALL_RINGING:
1511                         ms_message("CALL_RINGING");
1512                         call_ringing(sal,ev);
1513                         break;
1514                 case EXOSIP_CALL_MESSAGE_NEW:
1515                         ms_message("EXOSIP_CALL_MESSAGE_NEW");
1516                         call_message_new(sal,ev);
1517                         break;
1518                 case EXOSIP_CALL_MESSAGE_REQUESTFAILURE:
1519                         if (ev->did<0 && ev->response &&
1520                                 (ev->response->status_code==407 || ev->response->status_code==401)){
1521                                  return process_authentication(sal,ev);
1522                         }
1523                         break;
1524                 case EXOSIP_IN_SUBSCRIPTION_NEW:
1525                         ms_message("CALL_IN_SUBSCRIPTION_NEW ");
1526                         sal_exosip_subscription_recv(sal,ev);
1527                         break;
1528                 case EXOSIP_IN_SUBSCRIPTION_RELEASED:
1529                         ms_message("CALL_SUBSCRIPTION_NEW ");
1530                         sal_exosip_in_subscription_closed(sal,ev);
1531                         break;
1532                 case EXOSIP_SUBSCRIPTION_UPDATE:
1533                         ms_message("CALL_SUBSCRIPTION_UPDATE");
1534                         break;
1535                 case EXOSIP_SUBSCRIPTION_NOTIFY:
1536                         ms_message("CALL_SUBSCRIPTION_NOTIFY");
1537                         sal_exosip_notify_recv(sal,ev);
1538                         break;
1539                 case EXOSIP_SUBSCRIPTION_ANSWERED:
1540                         ms_message("EXOSIP_SUBSCRIPTION_ANSWERED, ev->sid=%i, ev->did=%i\n",ev->sid,ev->did);
1541                         sal_exosip_subscription_answered(sal,ev);
1542                         break;
1543                 case EXOSIP_SUBSCRIPTION_CLOSED:
1544                         ms_message("EXOSIP_SUBSCRIPTION_CLOSED\n");
1545                         sal_exosip_subscription_closed(sal,ev);
1546                         break;
1547                 case EXOSIP_SUBSCRIPTION_REQUESTFAILURE:   /**< announce a request failure      */
1548                         if (ev->response && (ev->response->status_code == 407 || ev->response->status_code == 401)){
1549                                 return process_authentication(sal,ev);
1550                         }
1551         case EXOSIP_SUBSCRIPTION_SERVERFAILURE:
1552                 case EXOSIP_SUBSCRIPTION_GLOBALFAILURE:
1553                         sal_exosip_subscription_closed(sal,ev);
1554                         break;
1555                 case EXOSIP_REGISTRATION_FAILURE:
1556                         ms_message("REGISTRATION_FAILURE\n");
1557                         return registration_failure(sal,ev);
1558                         break;
1559                 case EXOSIP_REGISTRATION_SUCCESS:
1560                         authentication_ok(sal,ev);
1561                         registration_success(sal,ev);
1562                         break;
1563                 case EXOSIP_MESSAGE_NEW:
1564                         other_request(sal,ev);
1565                         break;
1566                 case EXOSIP_MESSAGE_PROCEEDING:
1567                 case EXOSIP_MESSAGE_ANSWERED:
1568                 case EXOSIP_MESSAGE_REDIRECTED:
1569                 case EXOSIP_MESSAGE_SERVERFAILURE:
1570                 case EXOSIP_MESSAGE_GLOBALFAILURE:
1571                         other_request_reply(sal,ev);
1572                         break;
1573                 case EXOSIP_MESSAGE_REQUESTFAILURE:
1574                         if (ev->response && (ev->response->status_code == 407 || ev->response->status_code == 401)){
1575                                 return process_authentication(sal,ev);
1576                         }
1577                         other_request_reply(sal,ev);
1578                         break;
1579                 default:
1580                         ms_message("Unhandled exosip event ! %i",ev->type);
1581                         break;
1582         }
1583         return TRUE;
1584 }
1585
1586 int sal_iterate(Sal *sal){
1587         eXosip_event_t *ev;
1588         while((ev=eXosip_event_wait(0,0))!=NULL){
1589                 if (process_event(sal,ev))
1590                         eXosip_event_free(ev);
1591         }
1592         eXosip_lock();
1593         eXosip_automatic_refresh();
1594         eXosip_unlock();
1595         return 0;
1596 }
1597
1598 int sal_register(SalOp *h, const char *proxy, const char *from, int expires){
1599         osip_message_t *msg;
1600         sal_op_set_route(h,proxy);
1601         if (h->rid==-1){
1602                 eXosip_lock();
1603                 h->rid=eXosip_register_build_initial_register(from,proxy,sal_op_get_contact(h),expires,&msg);
1604                 sal_add_register(h->base.root,h);
1605         }else{
1606                 eXosip_lock();
1607                 eXosip_register_build_register(h->rid,expires,&msg);    
1608         }
1609         eXosip_register_send_register(h->rid,msg);
1610         eXosip_unlock();
1611         h->expires=expires;
1612         return 0;
1613 }
1614
1615 int sal_unregister(SalOp *h){
1616         osip_message_t *msg=NULL;
1617         eXosip_lock();
1618         eXosip_register_build_register(h->rid,0,&msg);
1619         if (msg) eXosip_register_send_register(h->rid,msg);
1620         else ms_warning("Could not build unREGISTER !");
1621         eXosip_unlock();
1622         return 0;
1623 }
1624
1625 SalAddress * sal_address_new(const char *uri){
1626         osip_from_t *from;
1627         osip_from_init(&from);
1628         if (osip_from_parse(from,uri)!=0){
1629                 osip_from_free(from);
1630                 return NULL;
1631         }
1632         if (from->displayname!=NULL && from->displayname[0]=='"'){
1633                 char *unquoted=osip_strdup_without_quote(from->displayname);
1634                 osip_free(from->displayname);
1635                 from->displayname=unquoted;
1636         }
1637         return (SalAddress*)from;
1638 }
1639
1640 SalAddress * sal_address_clone(const SalAddress *addr){
1641         osip_from_t *ret=NULL;
1642         osip_from_clone((osip_from_t*)addr,&ret);
1643         return (SalAddress*)ret;
1644 }
1645
1646 #define null_if_empty(s) (((s)!=NULL && (s)[0]!='\0') ? (s) : NULL )
1647
1648 const char *sal_address_get_scheme(const SalAddress *addr){
1649         const osip_from_t *u=(const osip_from_t*)addr;
1650         return null_if_empty(u->url->scheme);
1651 }
1652
1653 const char *sal_address_get_display_name(const SalAddress* addr){
1654         const osip_from_t *u=(const osip_from_t*)addr;
1655         return null_if_empty(u->displayname);
1656 }
1657
1658 const char *sal_address_get_username(const SalAddress *addr){
1659         const osip_from_t *u=(const osip_from_t*)addr;
1660         return null_if_empty(u->url->username);
1661 }
1662
1663 const char *sal_address_get_domain(const SalAddress *addr){
1664         const osip_from_t *u=(const osip_from_t*)addr;
1665         return null_if_empty(u->url->host);
1666 }
1667
1668 void sal_address_set_display_name(SalAddress *addr, const char *display_name){
1669         osip_from_t *u=(osip_from_t*)addr;
1670         if (u->displayname!=NULL){
1671                 osip_free(u->displayname);
1672                 u->displayname=NULL;
1673         }
1674         if (display_name!=NULL && display_name[0]!='\0'){
1675                 u->displayname=osip_strdup(display_name);
1676         }
1677 }
1678
1679 void sal_address_set_username(SalAddress *addr, const char *username){
1680         osip_from_t *uri=(osip_from_t*)addr;
1681         if (uri->url->username!=NULL){
1682                 osip_free(uri->url->username);
1683                 uri->url->username=NULL;
1684         }
1685         if (username)
1686                 uri->url->username=osip_strdup(username);
1687 }
1688
1689 void sal_address_set_domain(SalAddress *addr, const char *host){
1690         osip_from_t *uri=(osip_from_t*)addr;
1691         if (uri->url->host!=NULL){
1692                 osip_free(uri->url->host);
1693                 uri->url->host=NULL;
1694         }
1695         if (host)
1696                 uri->url->host=osip_strdup(host);
1697 }
1698
1699 void sal_address_set_port(SalAddress *addr, const char *port){
1700         osip_from_t *uri=(osip_from_t*)addr;
1701         if (uri->url->port!=NULL){
1702                 osip_free(uri->url->port);
1703                 uri->url->port=NULL;
1704         }
1705         if (port)
1706                 uri->url->port=osip_strdup(port);
1707 }
1708
1709 void sal_address_set_port_int(SalAddress *uri, int port){
1710         char tmp[12];
1711         if (port==5060){
1712                 /*this is the default, special case to leave the port field blank*/
1713                 sal_address_set_port(uri,NULL);
1714                 return;
1715         }
1716         snprintf(tmp,sizeof(tmp),"%i",port);
1717         sal_address_set_port(uri,tmp);
1718 }
1719
1720 void sal_address_clean(SalAddress *addr){
1721         osip_generic_param_freelist(& ((osip_from_t*)addr)->gen_params);
1722         osip_uri_param_freelist(& ((osip_from_t*)addr)->url->url_params);
1723 }
1724
1725 char *sal_address_as_string(const SalAddress *u){
1726         char *tmp,*ret;
1727         osip_from_t *from=(osip_from_t *)u;
1728         char *old_displayname=NULL;
1729         /* hack to force use of quotes around the displayname*/
1730         if (from->displayname!=NULL
1731             && from->displayname[0]!='"'){
1732                 old_displayname=from->displayname;
1733                 from->displayname=osip_enquote(from->displayname);
1734         }
1735         osip_from_to_str(from,&tmp);
1736         if (old_displayname!=NULL){
1737                 ms_free(from->displayname);
1738                 from->displayname=old_displayname;
1739         }
1740         ret=ms_strdup(tmp);
1741         osip_free(tmp);
1742         return ret;
1743 }
1744
1745 char *sal_address_as_string_uri_only(const SalAddress *u){
1746         char *tmp=NULL,*ret;
1747         osip_uri_to_str(((osip_from_t*)u)->url,&tmp);
1748         ret=ms_strdup(tmp);
1749         osip_free(tmp);
1750         return ret;
1751 }
1752 void sal_address_add_param(SalAddress *u,const char* name,const char* value) {
1753         osip_uri_uparam_add     (((osip_from_t*)u)->url,ms_strdup(name),ms_strdup(value));
1754 }
1755
1756 void sal_address_destroy(SalAddress *u){
1757         osip_from_free((osip_from_t*)u);
1758 }
1759
1760 void sal_set_keepalive_period(Sal *ctx,unsigned int value) {
1761         ctx->keepalive_period=value;
1762         eXosip_set_option (EXOSIP_OPT_UDP_KEEP_ALIVE, &value);
1763 }
1764 const char * sal_address_get_port(const SalAddress *addr) {
1765         const osip_from_t *u=(const osip_from_t*)addr;
1766         return null_if_empty(u->url->port);
1767 }
1768 int sal_address_get_port_int(const SalAddress *uri) {
1769         const char* port = sal_address_get_port(uri);
1770         if (port != NULL) {
1771                 return atoi(port);
1772         } else {
1773                 return 5060;
1774         }
1775 }
1776
1777 /*
1778  * Send a re-Invite used to hold the current call
1779 */
1780 int sal_call_hold(SalOp *h, bool_t holdon)
1781 {
1782         int err=0;
1783
1784         osip_message_t *reinvite=NULL;
1785         if(eXosip_call_build_request(h->did,"INVITE",&reinvite) != OSIP_SUCCESS || reinvite==NULL)
1786                 return -1;
1787         osip_message_set_subject(reinvite,osip_strdup("Phone Call Hold"));
1788         osip_message_set_allow(reinvite, "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, NOTIFY, MESSAGE, SUBSCRIBE, INFO");
1789         if (h->base.root->session_expires!=0){
1790                 osip_message_set_header(reinvite, "Session-expires", "200");
1791                 osip_message_set_supported(reinvite, "timer");
1792         }
1793         //add something to say that the distant sip phone will be in sendonly/sendrecv mode
1794         if (h->base.local_media){
1795                 h->sdp_offering=TRUE;
1796                 sal_media_description_set_dir(h->base.local_media, holdon ? SalStreamSendOnly : SalStreamSendRecv);
1797                 set_sdp_from_desc(reinvite,h->base.local_media);
1798         }else h->sdp_offering=FALSE;
1799         eXosip_lock();
1800         err = eXosip_call_send_request(h->did, reinvite);
1801         eXosip_unlock();
1802         
1803         return err;
1804 }
1805