]> sjero.net Git - linphone/blob - coreapi/sal_eXosip2.c
7b9d3581bd197c4f9d6f08b829ea9c35ae5eab41
[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->sock=-1;
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_updated==NULL) 
288                 ctx->callbacks.call_updated=(SalOnCallUpdated)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
314 static ortp_socket_t create_socket(int pf, int proto, const char *addr, int local_port){
315         struct addrinfo hints;
316         struct addrinfo *res=NULL;
317         ortp_socket_t sock;
318         int optval;
319         char tmp[20];
320         int err;
321         
322         sock=socket(pf,(proto==IPPROTO_UDP) ? SOCK_DGRAM : SOCK_STREAM,0);
323         if (sock<0) {
324                 ms_error("Fail to create socket");
325                 return -1;
326         }
327         snprintf(tmp,sizeof(tmp)-1,"%i",local_port);
328         memset (&hints,0,sizeof(hints));
329         hints.ai_family=(pf==PF_INET) ? AF_INET : AF_INET6;
330         hints.ai_socktype=(proto==IPPROTO_UDP) ? SOCK_DGRAM : SOCK_STREAM;
331         
332         if ((err=getaddrinfo(addr,
333                 tmp,
334                 &hints,&res))<0) {
335                 ms_error("create_socket: getaddrinfo() failed: %s",gai_strerror(err));
336                 close_socket(sock);
337                 return -1;
338         }
339         if (bind(sock,(struct sockaddr*)res->ai_addr,res->ai_addrlen)<0){
340                 ms_error("Bind socket to localhost:%i failed: %s",local_port,getSocketError());
341                 freeaddrinfo(res);
342                 close_socket(sock);
343                 return -1;
344         }
345         freeaddrinfo(res);
346         optval=1;
347         if (setsockopt (sock, SOL_SOCKET, SO_REUSEADDR,
348                                 (SOCKET_OPTION_VALUE)&optval, sizeof (optval))<0){
349                 ms_warning("Fail to set SO_REUSEADDR");
350         }
351         /*set_non_blocking_socket(sock);*/
352         return sock;
353 }
354
355
356 int sal_listen_port(Sal *ctx, const char *addr, int port, SalTransport tr, int is_secure){
357         int err;
358         bool_t ipv6;
359         int proto=IPPROTO_UDP;
360         
361         if (ctx->running){
362                 eXosip_quit();
363                 eXosip_init();
364         }
365         err=0;
366         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
367                                         version of eXosip, which is not the case*/
368         /*see if it looks like an IPv6 address*/
369         ipv6=strchr(addr,':')!=NULL;
370         eXosip_enable_ipv6(ipv6);
371
372         if (tr!=SalTransportDatagram || is_secure){
373                 ms_fatal("SIP over TCP or TLS or DTLS is not supported yet.");
374                 return -1;
375         }
376         ctx->sock=create_socket(ipv6 ?  PF_INET6 : PF_INET, proto, addr, port);
377         if (ctx->sock==-1) return -1;
378         ms_message("Exosip is given socket %i",ctx->sock);
379         eXosip_set_socket(proto,ctx->sock,port);
380         /*
381         err=eXosip_listen_addr(proto, addr, port, ipv6 ?  PF_INET6 : PF_INET, 0);
382         */
383         ctx->running=TRUE;
384         return err;
385 }
386
387 ortp_socket_t sal_get_socket(Sal *ctx){
388         return ctx->sock;
389 }
390
391 void sal_set_user_agent(Sal *ctx, const char *user_agent){
392         eXosip_set_user_agent(user_agent);
393 }
394
395 void sal_use_session_timers(Sal *ctx, int expires){
396         ctx->session_expires=expires;
397 }
398
399 MSList *sal_get_pending_auths(Sal *sal){
400         return ms_list_copy(sal->pending_auths);
401 }
402
403 static int extract_received_rport(osip_message_t *msg, const char **received, int *rportval){
404         osip_via_t *via=NULL;
405         osip_generic_param_t *param=NULL;
406         const char *rport;
407         
408         osip_message_get_via(msg,0,&via);
409         if (!via) return -1;
410         osip_via_param_get_byname(via,"rport",&param);
411         if (param) {
412                 rport=param->gvalue;
413                 if (rport && rport[0]!='\0') *rportval=atoi(rport);
414                 else *rportval=5060;
415         }
416         param=NULL;
417         osip_via_param_get_byname(via,"received",&param);
418         if (param) *received=param->gvalue;
419         else return -1;
420         return 0;
421 }
422
423 static void set_sdp(osip_message_t *sip,sdp_message_t *msg){
424         int sdplen;
425         char clen[10];
426         char *sdp=NULL;
427         sdp_message_to_str(msg,&sdp);
428         sdplen=strlen(sdp);
429         snprintf(clen,sizeof(clen),"%i",sdplen);
430         osip_message_set_body(sip,sdp,sdplen);
431         osip_message_set_content_type(sip,"application/sdp");
432         osip_message_set_content_length(sip,clen);
433         osip_free(sdp);
434 }
435
436 static void set_sdp_from_desc(osip_message_t *sip, const SalMediaDescription *desc){
437         sdp_message_t *msg=media_description_to_sdp(desc);
438         if (msg==NULL) {
439                 ms_error("Fail to print sdp message !");
440                 return;
441         }
442         set_sdp(sip,msg);
443         sdp_message_free(msg);
444 }
445
446 static void sdp_process(SalOp *h){
447         ms_message("Doing SDP offer/answer process");
448         if (h->result){
449                 sal_media_description_unref(h->result);
450         }
451         h->result=sal_media_description_new();
452         if (h->sdp_offering){   
453                 offer_answer_initiate_outgoing(h->base.local_media,h->base.remote_media,h->result);
454         }else{
455                 int i;
456                 offer_answer_initiate_incoming(h->base.local_media,h->base.remote_media,h->result);
457                 h->sdp_answer=media_description_to_sdp(h->result);
458                 strcpy(h->result->addr,h->base.remote_media->addr);
459                 h->result->bandwidth=h->base.remote_media->bandwidth;
460                 for(i=0;i<h->result->nstreams;++i){
461                         if (h->result->streams[i].port>0){
462                                 strcpy(h->result->streams[i].addr,h->base.remote_media->streams[i].addr);
463                                 h->result->streams[i].ptime=h->base.remote_media->streams[i].ptime;
464                                 h->result->streams[i].bandwidth=h->base.remote_media->streams[i].bandwidth;
465                                 h->result->streams[i].port=h->base.remote_media->streams[i].port;
466                         }
467                 }
468         }
469         
470 }
471
472 int sal_call_set_local_media_description(SalOp *h, SalMediaDescription *desc){
473         if (desc)
474                 sal_media_description_ref(desc);
475         if (h->base.local_media)
476                 sal_media_description_unref(h->base.local_media);
477         h->base.local_media=desc;
478         return 0;
479 }
480
481 int sal_call(SalOp *h, const char *from, const char *to){
482         int err;
483         osip_message_t *invite=NULL;
484         sal_op_set_from(h,from);
485         sal_op_set_to(h,to);
486         sal_exosip_fix_route(h);
487         err=eXosip_call_build_initial_invite(&invite,to,from,sal_op_get_route(h),"Phone call");
488         if (err!=0){
489                 ms_error("Could not create call.");
490                 return -1;
491         }
492         if (h->base.contact){
493                 _osip_list_set_empty(&invite->contacts,(void (*)(void*))osip_contact_free);
494                 osip_message_set_contact(invite,h->base.contact);
495         }
496         if (h->base.root->session_expires!=0){
497                 osip_message_set_header(invite, "Session-expires", "200");
498                 osip_message_set_supported(invite, "timer");
499         }
500         if (h->base.local_media){
501                 h->sdp_offering=TRUE;
502                 set_sdp_from_desc(invite,h->base.local_media);
503         }else h->sdp_offering=FALSE;
504         eXosip_lock();
505         err=eXosip_call_send_initial_invite(invite);
506         eXosip_unlock();
507         h->cid=err;
508         if (err<0){
509                 ms_error("Fail to send invite !");
510                 return -1;
511         }else{
512                 sal_add_call(h->base.root,h);
513         }
514         return 0;
515 }
516
517 int sal_call_notify_ringing(SalOp *h){
518         eXosip_lock();
519         eXosip_call_send_answer(h->tid,180,NULL);
520         eXosip_unlock();
521         return 0;
522 }
523
524 int sal_call_accept(SalOp * h){
525         osip_message_t *msg;
526         const char *contact=sal_op_get_contact(h);
527         /* sends a 200 OK */
528         int err=eXosip_call_build_answer(h->tid,200,&msg);
529         if (err<0 || msg==NULL){
530                 ms_error("Fail to build answer for call: err=%i",err);
531                 return -1;
532         }
533         if (h->base.root->session_expires!=0){
534                 if (h->supports_session_timers) osip_message_set_supported(msg, "timer");
535         }
536
537         if (contact) {
538                 _osip_list_set_empty(&msg->contacts,(void (*)(void*))osip_contact_free);
539                 osip_message_set_contact(msg,contact);
540         }
541         
542         if (h->base.local_media){
543                 /*this is the case where we received an invite without SDP*/
544                 if (h->sdp_offering) {
545                         set_sdp_from_desc(msg,h->base.local_media);
546                 }else{
547                         if (h->sdp_answer)
548                                 set_sdp(msg,h->sdp_answer);
549                 }
550         }else{
551                 ms_error("You are accepting a call but not defined any media capabilities !");
552         }
553         eXosip_call_send_answer(h->tid,200,msg);
554         return 0;
555 }
556
557 int sal_call_decline(SalOp *h, SalReason reason, const char *redirect){
558         if (reason==SalReasonBusy){
559                 eXosip_lock();
560                 eXosip_call_send_answer(h->tid,486,NULL);
561                 eXosip_unlock();
562         }
563         else if (reason==SalReasonTemporarilyUnavailable){
564                 eXosip_lock();
565                 eXosip_call_send_answer(h->tid,480,NULL);
566                 eXosip_unlock();
567         }else if (reason==SalReasonDoNotDisturb){
568                 eXosip_lock();
569                 eXosip_call_send_answer(h->tid,600,NULL);
570                 eXosip_unlock();
571         }else if (reason==SalReasonMedia){
572                 eXosip_lock();
573                 eXosip_call_send_answer(h->tid,415,NULL);
574                 eXosip_unlock();
575         }else if (redirect!=NULL && reason==SalReasonRedirect){
576                 osip_message_t *msg;
577                 int code;
578                 if (strstr(redirect,"sip:")!=0) code=302;
579                 else code=380;
580                 eXosip_lock();
581                 eXosip_call_build_answer(h->tid,code,&msg);
582                 osip_message_set_contact(msg,redirect);
583                 eXosip_call_send_answer(h->tid,code,msg);
584                 eXosip_unlock();
585         }else sal_call_terminate(h);
586         return 0;
587 }
588
589 SalMediaDescription * sal_call_get_final_media_description(SalOp *h){
590         if (h->base.local_media && h->base.remote_media && !h->result){
591                 sdp_process(h);
592         }
593         return h->result;
594 }
595
596 int sal_ping(SalOp *op, const char *from, const char *to){
597         osip_message_t *options=NULL;
598         
599         sal_op_set_from(op,from);
600         sal_op_set_to(op,to);
601         eXosip_options_build_request (&options, sal_op_get_to(op),
602                         sal_op_get_from(op),sal_op_get_route(op));
603         if (options){
604                 if (op->base.root->session_expires!=0){
605                         osip_message_set_header(options, "Session-expires", "200");
606                         osip_message_set_supported(options, "timer");
607                 }
608                 sal_add_other(sal_op_get_sal(op),op,options);
609                 return eXosip_options_send_request(options);
610         }
611         return -1;
612 }
613
614 int sal_refer_accept(SalOp *op){
615         osip_message_t *msg=NULL;
616         int err=0;
617         eXosip_lock();
618         err = eXosip_call_build_notify(op->did,EXOSIP_SUBCRSTATE_ACTIVE,&msg);
619         if(msg != NULL)
620         {
621                 osip_message_set_header(msg,(const char *)"event","refer");
622                 osip_message_set_content_type(msg,"message/sipfrag");
623                 osip_message_set_body(msg,"SIP/2.0 100 Trying",sizeof("SIP/2.0 100 Trying"));
624                 eXosip_call_send_request(op->did,msg);
625         }
626         else
627         {
628                 ms_error("could not get a notify built\n");
629         }
630         eXosip_unlock();
631         return err;
632 }
633
634 int sal_refer(SalOp *h, const char *refer_to){
635         osip_message_t *msg=NULL;
636         int err=0;
637         eXosip_lock();
638         eXosip_call_build_refer(h->did,refer_to, &msg);
639         if (msg) err=eXosip_call_send_request(h->did, msg);
640         else err=-1;
641         eXosip_unlock();
642         return err;
643 }
644
645 int sal_call_send_dtmf(SalOp *h, char dtmf){
646         osip_message_t *msg=NULL;
647         char dtmf_body[128];
648         char clen[10];
649
650         eXosip_lock();
651         eXosip_call_build_info(h->did,&msg);
652         if (msg){
653                 snprintf(dtmf_body, sizeof(dtmf_body), "Signal=%c\r\nDuration=250\r\n", dtmf);
654                 osip_message_set_body(msg,dtmf_body,strlen(dtmf_body));
655                 osip_message_set_content_type(msg,"application/dtmf-relay");
656                 snprintf(clen,sizeof(clen),"%lu",(unsigned long)strlen(dtmf_body));
657                 osip_message_set_content_length(msg,clen);              
658                 eXosip_call_send_request(h->did,msg);
659         }
660         eXosip_unlock();
661         return 0;
662 }
663
664 int sal_call_terminate(SalOp *h){
665         eXosip_lock();
666         eXosip_call_terminate(h->cid,h->did);
667         eXosip_unlock();
668         sal_remove_call(h->base.root,h);
669         return 0;
670 }
671
672 void sal_op_authenticate(SalOp *h, const SalAuthInfo *info){
673         if (h->pending_auth){
674                 const char *userid;
675                 if (info->userid==NULL || info->userid[0]=='\0') userid=info->username;
676                 else userid=info->userid;
677                 ms_message("Authentication info for %s %s added to eXosip", info->username,info->realm);
678                 eXosip_add_authentication_info (info->username,userid,
679                                       info->password, NULL,info->realm);
680                 eXosip_lock();
681                 eXosip_default_action(h->pending_auth);
682                 eXosip_unlock();
683                 ms_message("eXosip_default_action() done");
684                 eXosip_clear_authentication_info();
685                 eXosip_event_free(h->pending_auth);
686                 sal_remove_pending_auth(sal_op_get_sal(h),h);
687                 h->pending_auth=NULL;
688         }
689 }
690
691 static void set_network_origin(SalOp *op, osip_message_t *req){
692         const char *received=NULL;
693         int rport=5060;
694         char origin[64];
695         if (extract_received_rport(req,&received,&rport)!=0){
696                 osip_via_t *via=NULL;
697                 char *tmp;
698                 osip_message_get_via(req,0,&via);
699                 received=osip_via_get_host(via);
700                 tmp=osip_via_get_port(via);
701                 if (tmp) rport=atoi(tmp);
702         }
703         snprintf(origin,sizeof(origin)-1,"sip:%s:%i",received,rport);
704         __sal_op_set_network_origin(op,origin);
705 }
706
707 static SalOp *find_op(Sal *sal, eXosip_event_t *ev){
708         if (ev->cid>0){
709                 return sal_find_call(sal,ev->cid);
710         }
711         if (ev->rid>0){
712                 return sal_find_register(sal,ev->rid);
713         }
714         if (ev->response) return sal_find_other(sal,ev->response);
715         return NULL;
716 }
717
718 static void inc_new_call(Sal *sal, eXosip_event_t *ev){
719         SalOp *op=sal_op_new(sal);
720         osip_from_t *from,*to;
721         osip_call_info_t *call_info;
722         char *tmp;
723         sdp_message_t *sdp=eXosip_get_sdp_info(ev->request);
724
725         set_network_origin(op,ev->request);
726         
727         if (sdp){
728                 op->sdp_offering=FALSE;
729                 op->base.remote_media=sal_media_description_new();
730                 sdp_to_media_description(sdp,op->base.remote_media);
731                 sdp_message_free(sdp);
732         }else op->sdp_offering=TRUE;
733
734         from=osip_message_get_from(ev->request);
735         to=osip_message_get_to(ev->request);
736         osip_from_to_str(from,&tmp);
737         sal_op_set_from(op,tmp);
738         osip_free(tmp);
739         osip_from_to_str(to,&tmp);
740         sal_op_set_to(op,tmp);
741         osip_free(tmp);
742
743         osip_message_get_call_info(ev->request,0,&call_info);
744         if(call_info)
745         {
746                 osip_call_info_to_str(call_info,&tmp);
747                 if( strstr(tmp,"answer-after=") != NULL)
748                 {
749                         op->auto_answer_asked=TRUE;
750                         ms_message("The caller asked to automatically answer the call(Emergency?)\n");
751                 }
752                 osip_free(tmp);
753         }
754
755         op->tid=ev->tid;
756         op->cid=ev->cid;
757         op->did=ev->did;
758         
759         sal_add_call(op->base.root,op);
760         sal->callbacks.call_received(op);
761 }
762
763 static void handle_reinvite(Sal *sal,  eXosip_event_t *ev){
764         SalOp *op=find_op(sal,ev);
765         sdp_message_t *sdp;
766         osip_message_t *msg=NULL;
767
768         if (op==NULL) {
769                 ms_warning("Reinvite for non-existing operation !");
770                 return;
771         }
772         op->reinvite=TRUE;
773         op->tid=ev->tid;
774         sdp=eXosip_get_sdp_info(ev->request);
775         if (op->base.remote_media){
776                 sal_media_description_unref(op->base.remote_media);
777                 op->base.remote_media=NULL;
778         }
779         eXosip_lock();
780         eXosip_call_build_answer(ev->tid,200,&msg);
781         eXosip_unlock();
782         if (msg==NULL) return;
783         if (op->base.root->session_expires!=0){
784                 if (op->supports_session_timers) osip_message_set_supported(msg, "timer");
785         }
786         if (op->base.contact){
787                 _osip_list_set_empty(&msg->contacts,(void (*)(void*))osip_contact_free);
788                 osip_message_set_contact(msg,op->base.contact);
789         }
790         if (sdp){
791                 op->sdp_offering=FALSE;
792                 op->base.remote_media=sal_media_description_new();
793                 sdp_to_media_description(sdp,op->base.remote_media);
794                 sdp_message_free(sdp);
795                 sdp_process(op);
796                 set_sdp(msg,op->sdp_answer);
797         }else {
798                 op->sdp_offering=TRUE;
799                 set_sdp_from_desc(msg,op->base.local_media);
800         }
801         eXosip_lock();
802         eXosip_call_send_answer(ev->tid,200,msg);
803         eXosip_unlock();
804 }
805
806 static void handle_ack(Sal *sal,  eXosip_event_t *ev){
807         SalOp *op=find_op(sal,ev);
808         sdp_message_t *sdp;
809
810         if (op==NULL) {
811                 ms_warning("ack for non-existing call !");
812                 return;
813         }
814         sdp=eXosip_get_sdp_info(ev->ack);
815         if (sdp){
816                 op->base.remote_media=sal_media_description_new();
817                 sdp_to_media_description(sdp,op->base.remote_media);
818                 sdp_process(op);
819                 sdp_message_free(sdp);
820         }
821         if (op->reinvite){
822                 sal->callbacks.call_updated(op);
823                 op->reinvite=FALSE;
824         }else{
825                 sal->callbacks.call_ack(op);
826         }
827 }
828
829 static void update_contact_from_response(SalOp *op, osip_message_t *response){
830         const char *received;
831         int rport;
832         if (extract_received_rport(response,&received,&rport)==0){
833                 const char *contact=sal_op_get_contact(op);
834                 if (!contact){
835                         /*no contact given yet, use from instead*/
836                         contact=sal_op_get_from(op);
837                 }
838                 if (contact){
839                         SalAddress *addr=sal_address_new(contact);
840                         char *tmp;
841                         sal_address_set_domain(addr,received);
842                         sal_address_set_port_int(addr,rport);
843                         tmp=sal_address_as_string(addr);
844                         ms_message("Contact address updated to %s for this dialog",tmp);
845                         sal_op_set_contact(op,tmp);
846                         ms_free(tmp);
847                 }
848         }
849 }
850
851 static int call_proceeding(Sal *sal, eXosip_event_t *ev){
852         SalOp *op=find_op(sal,ev);
853         
854         if (op==NULL) {
855                 ms_warning("This call has been canceled.");
856                 eXosip_lock();
857                 eXosip_call_terminate(ev->cid,ev->did);
858                 eXosip_unlock();
859                 return -1;
860         }
861         op->did=ev->did;
862         op->tid=ev->tid;
863         
864         /* update contact if received and rport are set by the server
865          note: will only be used by remote for next INVITE, if any...*/
866         update_contact_from_response(op,ev->response);
867         return 0;
868 }
869
870 static void call_ringing(Sal *sal, eXosip_event_t *ev){
871         sdp_message_t *sdp;
872         SalOp *op=find_op(sal,ev);
873         if (call_proceeding(sal, ev)==-1) return;
874         
875         sdp=eXosip_get_sdp_info(ev->response);
876         if (sdp){
877                 op->base.remote_media=sal_media_description_new();
878                 sdp_to_media_description(sdp,op->base.remote_media);
879                 sdp_message_free(sdp);
880                 if (op->base.local_media) sdp_process(op);
881         }
882         sal->callbacks.call_ringing(op);
883 }
884
885 static void call_accepted(Sal *sal, eXosip_event_t *ev){
886         sdp_message_t *sdp;
887         osip_message_t *msg=NULL;
888         SalOp *op=find_op(sal,ev);
889         const char *contact;
890         
891         if (op==NULL){
892                 ms_error("A closed call is accepted ?");
893                 return;
894         }
895         sdp=eXosip_get_sdp_info(ev->response);
896         if (sdp){
897                 op->base.remote_media=sal_media_description_new();
898                 sdp_to_media_description(sdp,op->base.remote_media);
899                 sdp_message_free(sdp);
900                 if (op->base.local_media) sdp_process(op);
901         }
902         eXosip_call_build_ack(ev->did,&msg);
903         contact=sal_op_get_contact(op);
904         if (contact) {
905                 _osip_list_set_empty(&msg->contacts,(void (*)(void*))osip_contact_free);
906                 osip_message_set_contact(msg,contact);
907         }
908         if (op->sdp_answer)
909                         set_sdp(msg,op->sdp_answer);
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;
916         SalOp *op=find_op(sal,ev);
917         if (op==NULL){
918                 ms_warning("Call terminated for already closed call ?");
919                 return;
920         }
921         osip_from_to_str(ev->request->from,&from);
922         sal_remove_call(sal,op);
923         op->cid=-1;
924         sal->callbacks.call_terminated(op,from);
925         osip_free(from);
926 }
927
928 static void call_released(Sal *sal, eXosip_event_t *ev){
929         SalOp *op=find_op(sal,ev);
930         if (op==NULL){
931                 ms_warning("No op associated to this call_released()");
932                 return;
933         }
934         op->cid=-1;
935         if (op->did==-1) 
936                 sal->callbacks.call_failure(op,SalErrorNoResponse,SalReasonUnknown,NULL);
937 }
938
939 static int get_auth_data_from_response(osip_message_t *resp, const char **realm, const char **username){
940         const char *prx_realm=NULL,*www_realm=NULL;
941         osip_proxy_authenticate_t *prx_auth;
942         osip_www_authenticate_t *www_auth;
943         
944         *username=osip_uri_get_username(resp->from->url);
945         prx_auth=(osip_proxy_authenticate_t*)osip_list_get(&resp->proxy_authenticates,0);
946         www_auth=(osip_proxy_authenticate_t*)osip_list_get(&resp->www_authenticates,0);
947         if (prx_auth!=NULL)
948                 prx_realm=osip_proxy_authenticate_get_realm(prx_auth);
949         if (www_auth!=NULL)
950                 www_realm=osip_www_authenticate_get_realm(www_auth);
951
952         if (prx_realm){
953                 *realm=prx_realm;
954         }else if (www_realm){
955                 *realm=www_realm;
956         }else{
957                 return -1;
958         }
959         return 0;
960 }
961
962 static int get_auth_data_from_request(osip_message_t *msg, const char **realm, const char **username){
963         osip_authorization_t *auth=NULL;
964         osip_proxy_authorization_t *prx_auth=NULL;
965         
966         *username=osip_uri_get_username(msg->from->url);
967         osip_message_get_authorization(msg, 0, &auth);
968         if (auth){
969                 *realm=osip_authorization_get_realm(auth);
970                 return 0;
971         }
972         osip_message_get_proxy_authorization(msg,0,&prx_auth);
973         if (prx_auth){
974                 *realm=osip_proxy_authorization_get_realm(prx_auth);
975                 return 0;
976         }
977         return -1;
978 }
979
980 static int get_auth_data(eXosip_event_t *ev, const char **realm, const char **username){
981         if (ev->response && get_auth_data_from_response(ev->response,realm,username)==0) return 0;
982         if (ev->request && get_auth_data_from_request(ev->request,realm,username)==0) return 0;
983         return -1;
984 }
985
986 int sal_op_get_auth_requested(SalOp *op, const char **realm, const char **username){
987         if (op->pending_auth){
988                 return get_auth_data(op->pending_auth,realm,username);
989         }
990         return -1;
991 }
992
993 static bool_t process_authentication(Sal *sal, eXosip_event_t *ev){
994         SalOp *op;
995         const char *username,*realm;
996         op=find_op(sal,ev);
997         if (op==NULL){
998                 ms_warning("No operation associated with this authentication !");
999                 return TRUE;
1000         }
1001         if (get_auth_data(ev,&realm,&username)==0){
1002                 if (op->pending_auth!=NULL)
1003                         eXosip_event_free(op->pending_auth);
1004                 op->pending_auth=ev;
1005                 sal_add_pending_auth (sal,op);
1006                 sal->callbacks.auth_requested(op,realm,username);
1007                 return FALSE;
1008         }
1009         return TRUE;
1010 }
1011
1012 static void authentication_ok(Sal *sal, eXosip_event_t *ev){
1013         SalOp *op;
1014         const char *username,*realm;
1015         op=find_op(sal,ev);
1016         if (op==NULL){
1017                 ms_warning("No operation associated with this authentication_ok!");
1018                 return ;
1019         }
1020         if (get_auth_data(ev,&realm,&username)==0){
1021                 sal->callbacks.auth_success(op,realm,username);
1022         }
1023 }
1024
1025 static bool_t call_failure(Sal *sal, eXosip_event_t *ev){
1026         SalOp *op;
1027         int code=0;
1028         const char *reason=NULL;
1029         SalError error=SalErrorUnknown;
1030         SalReason sr=SalReasonUnknown;
1031         
1032         op=(SalOp*)find_op(sal,ev);
1033
1034         if (op==NULL) {
1035                 ms_warning("Call failure reported for a closed call, ignored.");
1036                 return TRUE;
1037         }
1038
1039         if (ev->response){
1040                 code=osip_message_get_status_code(ev->response);
1041                 reason=osip_message_get_reason_phrase(ev->response);
1042         }
1043         switch(code)
1044         {
1045                 case 401:
1046                 case 407:
1047                         return process_authentication(sal,ev);
1048                         break;
1049                 case 400:
1050                         error=SalErrorUnknown;
1051                 break;
1052                 case 404:
1053                         error=SalErrorFailure;
1054                         sr=SalReasonNotFound;
1055                 break;
1056                 case 415:
1057                         error=SalErrorFailure;
1058                         sr=SalReasonMedia;
1059                 break;
1060                 case 422:
1061                         eXosip_default_action(ev);
1062                         return TRUE;
1063                 break;
1064                 case 480:
1065                         error=SalErrorFailure;
1066                         sr=SalReasonTemporarilyUnavailable;
1067                 case 486:
1068                         error=SalErrorFailure;
1069                         sr=SalReasonBusy;
1070                 break;
1071                 case 487:
1072                 break;
1073                 case 600:
1074                         error=SalErrorFailure;
1075                         sr=SalReasonDoNotDisturb;
1076                 break;
1077                 case 603:
1078                         error=SalErrorFailure;
1079                         sr=SalReasonDeclined;
1080                 break;
1081                 default:
1082                         if (code>0){
1083                                 error=SalErrorFailure;
1084                                 sr=SalReasonUnknown;
1085                         }else error=SalErrorNoResponse;
1086         }
1087         sal->callbacks.call_failure(op,error,sr,reason);
1088         return TRUE;
1089 }
1090
1091
1092 static void process_media_control_xml(Sal *sal, eXosip_event_t *ev){
1093         SalOp *op=find_op(sal,ev);
1094         osip_body_t *body=NULL;
1095
1096         if (op==NULL){
1097                 ms_warning("media control xml received without operation context!");
1098                 return ;
1099         }
1100         
1101         osip_message_get_body(ev->request,0,&body);
1102         if (body && body->body!=NULL &&
1103                 strstr(body->body,"picture_fast_update")){
1104                 osip_message_t *ans=NULL;
1105                 ms_message("Receiving VFU request !");
1106                 if (sal->callbacks.vfu_request){
1107                         sal->callbacks.vfu_request(op);
1108                         eXosip_call_build_answer(ev->tid,200,&ans);
1109                         if (ans)
1110                                 eXosip_call_send_answer(ev->tid,200,ans);
1111                 }
1112         }
1113 }
1114
1115 static void process_dtmf_relay(Sal *sal, eXosip_event_t *ev){
1116         SalOp *op=find_op(sal,ev);
1117         osip_body_t *body=NULL;
1118
1119         if (op==NULL){
1120                 ms_warning("media dtmf relay received without operation context!");
1121                 return ;
1122         }
1123         
1124         osip_message_get_body(ev->request,0,&body);
1125         if (body && body->body!=NULL){
1126                 osip_message_t *ans=NULL;
1127                 const char *name=strstr(body->body,"Signal");
1128                 if (name==NULL) name=strstr(body->body,"signal");
1129                 if (name==NULL) {
1130                         ms_warning("Could not extract the dtmf name from the SIP INFO.");
1131                 }else{
1132                         char tmp[2];
1133                         name+=strlen("signal");
1134                         if (sscanf(name," = %1s",tmp)==1){
1135                                 ms_message("Receiving dtmf %s via SIP INFO.",tmp);
1136                                 if (sal->callbacks.dtmf_received != NULL)
1137                                         sal->callbacks.dtmf_received(op, tmp[0]);
1138                         }
1139                 }
1140                 eXosip_call_build_answer(ev->tid,200,&ans);
1141                 if (ans)
1142                         eXosip_call_send_answer(ev->tid,200,ans);
1143         }
1144 }
1145
1146 static void call_message_new(Sal *sal, eXosip_event_t *ev){
1147         osip_message_t *ans=NULL;
1148         if (ev->request){
1149                 if (MSG_IS_INFO(ev->request)){
1150                         osip_content_type_t *ct;
1151                         ct=osip_message_get_content_type(ev->request);
1152                         if (ct && ct->subtype){
1153                                 if (strcmp(ct->subtype,"media_control+xml")==0)
1154                                         process_media_control_xml(sal,ev);
1155                                 else if (strcmp(ct->subtype,"dtmf-relay")==0)
1156                                         process_dtmf_relay(sal,ev);
1157                                 else {
1158                                         ms_message("Unhandled SIP INFO.");
1159                                         /*send an "Not implemented" answer*/
1160                                         eXosip_lock();
1161                                         eXosip_call_build_answer(ev->tid,501,&ans);
1162                                         if (ans)
1163                                                 eXosip_call_send_answer(ev->tid,501,ans);
1164                                         eXosip_unlock();
1165                                 }
1166                         }else{
1167                                 /*empty SIP INFO, probably to test we are alive. Send an empty answer*/
1168                                 eXosip_lock();
1169                                 eXosip_call_build_answer(ev->tid,200,&ans);
1170                                 if (ans)
1171                                         eXosip_call_send_answer(ev->tid,200,ans);
1172                                 eXosip_unlock();
1173                         }
1174                 }
1175                 if(MSG_IS_MESSAGE(ev->request)){
1176                         /* SIP messages could be received into call */
1177                         text_received(sal, ev);
1178                         eXosip_lock();
1179                         eXosip_call_build_answer(ev->tid,200,&ans);
1180                         if (ans)
1181                                 eXosip_call_send_answer(ev->tid,200,ans);
1182                         eXosip_unlock();
1183                 }
1184                 if(MSG_IS_REFER(ev->request)){
1185                         osip_header_t *h=NULL;
1186                         SalOp *op=find_op(sal,ev);
1187                         
1188                         ms_message("Receiving REFER request !");
1189                         osip_message_header_get_byname(ev->request,"Refer-To",0,&h);
1190                         eXosip_lock();
1191                         eXosip_call_build_answer(ev->tid,202,&ans);
1192                         if (ans)
1193                                 eXosip_call_send_answer(ev->tid,202,ans);
1194                         eXosip_unlock();
1195                         if (h){
1196                                 sal->callbacks.refer_received(sal,op,h->hvalue);
1197                         }
1198                         else
1199                         {
1200                                 ms_warning("cannot do anything with the refer without destination\n");
1201                         }
1202                 }
1203                 if(MSG_IS_NOTIFY(ev->request)){
1204                         osip_header_t *h=NULL;
1205                         char *from=NULL;
1206                         SalOp *op=find_op(sal,ev);
1207
1208                         ms_message("Receiving NOTIFY request !");
1209                         osip_from_to_str(ev->request->from,&from);
1210                         osip_message_header_get_byname(ev->request,"Event",0,&h);
1211                         if(h)
1212                                 sal->callbacks.notify(op,from,h->hvalue);
1213                         /*answer that we received the notify*/
1214                         eXosip_lock();
1215                         eXosip_call_build_answer(ev->tid,200,&ans);
1216                         if (ans)
1217                                 eXosip_call_send_answer(ev->tid,200,ans);
1218                         eXosip_unlock();
1219                         osip_free(from);
1220                 }
1221         }else ms_warning("call_message_new: No request ?");
1222 }
1223
1224 static void inc_update(Sal *sal, eXosip_event_t *ev){
1225         osip_message_t *msg=NULL;
1226         ms_message("Processing incoming UPDATE");
1227         eXosip_lock();
1228         eXosip_message_build_answer(ev->tid,200,&msg);
1229         if (msg!=NULL)
1230                 eXosip_message_send_answer(ev->tid,200,msg);
1231         eXosip_unlock();
1232 }
1233
1234 static bool_t comes_from_local_if(osip_message_t *msg){
1235         osip_via_t *via=NULL;
1236         osip_message_get_via(msg,0,&via);
1237         if (via){
1238                 const char *host;
1239                 host=osip_via_get_host(via);
1240                 if (strcmp(host,"127.0.0.1")==0 || strcmp(host,"::1")==0){
1241                         osip_generic_param_t *param=NULL;
1242                         osip_via_param_get_byname(via,"received",&param);
1243                         if (param==NULL) return TRUE;
1244                         if (param->gvalue &&
1245                                 (strcmp(param->gvalue,"127.0.0.1")==0 || strcmp(param->gvalue,"::1")==0)){
1246                                 return TRUE;
1247                         }
1248                 }
1249         }
1250         return FALSE;
1251 }
1252
1253 static void text_received(Sal *sal, eXosip_event_t *ev){
1254         osip_body_t *body=NULL;
1255         char *from=NULL,*msg;
1256         
1257         osip_message_get_body(ev->request,0,&body);
1258         if (body==NULL){
1259                 ms_error("Could not get text message from SIP body");
1260                 return;
1261         }
1262         msg=body->body;
1263         osip_from_to_str(ev->request->from,&from);
1264         sal->callbacks.text_received(sal,from,msg);
1265         osip_free(from);
1266 }
1267
1268 static void other_request(Sal *sal, eXosip_event_t *ev){
1269         ms_message("in other_request");
1270         if (ev->request==NULL) return;
1271         if (strcmp(ev->request->sip_method,"MESSAGE")==0){
1272                 text_received(sal,ev);
1273                 eXosip_message_send_answer(ev->tid,200,NULL);
1274         }else if (strcmp(ev->request->sip_method,"OPTIONS")==0){
1275                 osip_message_t *options=NULL;
1276                 eXosip_options_build_answer(ev->tid,200,&options);
1277                 osip_message_set_allow(options,"INVITE, ACK, BYE, CANCEL, OPTIONS, MESSAGE, SUBSCRIBE, NOTIFY, INFO");
1278                 osip_message_set_accept(options,"application/sdp");
1279                 eXosip_options_send_answer(ev->tid,200,options);
1280         }else if (strcmp(ev->request->sip_method,"WAKEUP")==0
1281                 && comes_from_local_if(ev->request)) {
1282                 eXosip_message_send_answer(ev->tid,200,NULL);
1283                 ms_message("Receiving WAKEUP request !");
1284                 sal->callbacks.internal_message(sal,"WAKEUP");
1285         }else if (strncmp(ev->request->sip_method, "REFER", 5) == 0){
1286                 ms_message("Receiving REFER request !");
1287                 if (comes_from_local_if(ev->request)) {
1288                         osip_header_t *h=NULL;
1289                         osip_message_header_get_byname(ev->request,"Refer-To",0,&h);
1290                         eXosip_message_send_answer(ev->tid,200,NULL);
1291                         if (h){
1292                                 sal->callbacks.refer_received(sal,NULL,h->hvalue);
1293                         }
1294                 }else ms_warning("Ignored REFER not coming from this local loopback interface.");
1295         }else if (strncmp(ev->request->sip_method, "UPDATE", 6) == 0){
1296                 inc_update(sal,ev);
1297     }else {
1298                 char *tmp=NULL;
1299                 size_t msglen=0;
1300                 osip_message_to_str(ev->request,&tmp,&msglen);
1301                 if (tmp){
1302                         ms_message("Unsupported request received:\n%s",tmp);
1303                         osip_free(tmp);
1304                 }
1305                 /*answer with a 501 Not implemented*/
1306                 eXosip_message_send_answer(ev->tid,501,NULL);
1307         }
1308 }
1309
1310 static void masquerade_via(osip_message_t *msg, const char *ip, const char *port){
1311         osip_via_t *via=NULL;
1312         osip_message_get_via(msg,0,&via);
1313         if (via){
1314                 osip_free(via->port);
1315                 via->port=osip_strdup(port);
1316                 osip_free(via->host);
1317                 via->host=osip_strdup(ip);
1318         }
1319 }
1320
1321 static bool_t register_again_with_updated_contact(SalOp *op, osip_message_t *orig_request, osip_message_t *last_answer){
1322         osip_message_t *msg;
1323         const char *received;
1324         int rport;
1325         osip_contact_t *ctt=NULL;
1326         char *tmp;
1327         char port[20];
1328         SalAddress *addr;
1329         
1330         if (extract_received_rport(last_answer,&received,&rport)==-1) return FALSE;
1331         osip_message_get_contact(orig_request,0,&ctt);
1332         if (strcmp(ctt->url->host,received)==0){
1333                 /*ip address matches, check ports*/
1334                 const char *contact_port=ctt->url->port;
1335                 if (contact_port==NULL || contact_port[0]=='\0')
1336                         contact_port="5060";
1337                 if (atoi(contact_port)==rport){
1338                         ms_message("Register has up to date contact, doing nothing.");
1339                         return FALSE;
1340                 }else ms_message("ports do not match, need to update the register (%s <> %i)", contact_port,rport);
1341         }
1342         eXosip_lock();
1343         msg=NULL;
1344         eXosip_register_build_register(op->rid,op->expires,&msg);
1345         if (msg==NULL){
1346                 eXosip_unlock();
1347                 ms_warning("Fail to create a contact updated register.");
1348                 return FALSE;
1349         }
1350         osip_message_get_contact(msg,0,&ctt);
1351         if (ctt->url->host!=NULL){
1352                 osip_free(ctt->url->host);
1353         }
1354         ctt->url->host=osip_strdup(received);
1355         if (ctt->url->port!=NULL){
1356                 osip_free(ctt->url->port);
1357         }
1358         snprintf(port,sizeof(port),"%i",rport);
1359         ctt->url->port=osip_strdup(port);
1360         if (op->masquerade_via) masquerade_via(msg,received,port);
1361         eXosip_register_send_register(op->rid,msg);
1362         eXosip_unlock();
1363         osip_contact_to_str(ctt,&tmp);
1364         addr=sal_address_new(tmp);
1365         osip_free(tmp);
1366         sal_address_clean(addr);
1367         tmp=sal_address_as_string(addr);
1368         sal_op_set_contact(op,tmp);
1369         sal_address_destroy(addr);
1370         ms_message("Resending new register with updated contact %s",tmp);
1371         ms_free(tmp);
1372         return TRUE;
1373 }
1374
1375 static void registration_success(Sal *sal, eXosip_event_t *ev){
1376         SalOp *op=sal_find_register(sal,ev->rid);
1377         osip_header_t *h=NULL;
1378         bool_t registered;
1379         if (op==NULL){
1380                 ms_error("Receiving register response for unknown operation");
1381                 return;
1382         }
1383         osip_message_get_expires(ev->request,0,&h);
1384         if (h!=NULL && atoi(h->hvalue)!=0){
1385                 registered=TRUE;
1386                 if (!register_again_with_updated_contact(op,ev->request,ev->response)){
1387                         sal->callbacks.register_success(op,registered);
1388                 }
1389         }else registered=FALSE;
1390 }
1391
1392 static bool_t registration_failure(Sal *sal, eXosip_event_t *ev){
1393         int status_code=0;
1394         const char *reason=NULL;
1395         SalOp *op=sal_find_register(sal,ev->rid);
1396         SalReason sr=SalReasonUnknown;
1397         SalError se=SalErrorUnknown;
1398         
1399         if (op==NULL){
1400                 ms_error("Receiving register failure for unknown operation");
1401                 return TRUE;
1402         }
1403         if (ev->response){
1404                 status_code=osip_message_get_status_code(ev->response);
1405                 reason=osip_message_get_reason_phrase(ev->response);
1406         }else return TRUE;
1407         switch(status_code){
1408                 case 401:
1409                 case 407:
1410                         return process_authentication(sal,ev);
1411                         break;
1412                 case 606: /*Not acceptable, workaround for proxies that don't like private addresses
1413                                  in vias, such as ekiga.net 
1414                                  On the opposite, freephonie.net bugs when via are masqueraded.
1415                                  */
1416                         op->masquerade_via=TRUE;
1417                 default:
1418                         /* if contact is up to date, process the failure, otherwise resend a new register with
1419                                 updated contact first, just in case the faillure is due to incorrect contact */
1420                         if (register_again_with_updated_contact(op,ev->request,ev->response))
1421                                 return TRUE; /*we are retrying with an updated contact*/
1422                         if (status_code==403){
1423                                 se=SalErrorFailure;
1424                                 sr=SalReasonForbidden;
1425                         }else if (status_code==0){
1426                                 se=SalErrorNoResponse;
1427                         }
1428                         sal->callbacks.register_failure(op,se,sr,reason);
1429         }
1430         return TRUE;
1431 }
1432
1433 static void other_request_reply(Sal *sal,eXosip_event_t *ev){
1434         SalOp *op=find_op(sal,ev);
1435
1436         if (op==NULL){
1437                 ms_warning("other_request_reply(): Receiving response to unknown request.");
1438                 return;
1439         }
1440         if (ev->response){
1441                 update_contact_from_response(op,ev->response);
1442                 sal->callbacks.ping_reply(op);
1443         }
1444 }
1445
1446 static bool_t process_event(Sal *sal, eXosip_event_t *ev){
1447         ms_message("linphone process event get a message %d\n",ev->type);
1448         switch(ev->type){
1449                 case EXOSIP_CALL_ANSWERED:
1450                         ms_message("CALL_ANSWERED\n");
1451                         call_accepted(sal,ev);
1452                         authentication_ok(sal,ev);
1453                         break;
1454                 case EXOSIP_CALL_CLOSED:
1455                 case EXOSIP_CALL_CANCELLED:
1456                         ms_message("CALL_CLOSED or CANCELLED\n");
1457                         call_terminated(sal,ev);
1458                         break;
1459                 case EXOSIP_CALL_TIMEOUT:
1460                 case EXOSIP_CALL_NOANSWER:
1461                         ms_message("CALL_TIMEOUT or NOANSWER\n");
1462                         return call_failure(sal,ev);
1463                         break;
1464                 case EXOSIP_CALL_REQUESTFAILURE:
1465                 case EXOSIP_CALL_GLOBALFAILURE:
1466                 case EXOSIP_CALL_SERVERFAILURE:
1467                         ms_message("CALL_REQUESTFAILURE or GLOBALFAILURE or SERVERFAILURE\n");
1468                         return call_failure(sal,ev);
1469                         break;
1470                 case EXOSIP_CALL_RELEASED:
1471                         ms_message("CALL_RELEASED\n");
1472                         call_released(sal, ev);
1473                         break;
1474                 case EXOSIP_CALL_INVITE:
1475                         ms_message("CALL_NEW\n");
1476                         inc_new_call(sal,ev);
1477                         break;
1478                 case EXOSIP_CALL_REINVITE:
1479                         handle_reinvite(sal,ev);
1480                         break;
1481                 case EXOSIP_CALL_ACK:
1482                         ms_message("CALL_ACK");
1483                         handle_ack(sal,ev);
1484                         break;
1485                 case EXOSIP_CALL_REDIRECTED:
1486                         ms_message("CALL_REDIRECTED");
1487                         eXosip_default_action(ev);
1488                         break;
1489                 case EXOSIP_CALL_PROCEEDING:
1490                         ms_message("CALL_PROCEEDING");
1491                         call_proceeding(sal,ev);
1492                         break;
1493                 case EXOSIP_CALL_RINGING:
1494                         ms_message("CALL_RINGING");
1495                         call_ringing(sal,ev);
1496                         break;
1497                 case EXOSIP_CALL_MESSAGE_NEW:
1498                         ms_message("EXOSIP_CALL_MESSAGE_NEW");
1499                         call_message_new(sal,ev);
1500                         break;
1501                 case EXOSIP_CALL_MESSAGE_REQUESTFAILURE:
1502                         if (ev->did<0 && ev->response &&
1503                                 (ev->response->status_code==407 || ev->response->status_code==401)){
1504                                  return process_authentication(sal,ev);
1505                         }
1506                         break;
1507                 case EXOSIP_IN_SUBSCRIPTION_NEW:
1508                         ms_message("CALL_IN_SUBSCRIPTION_NEW ");
1509                         sal_exosip_subscription_recv(sal,ev);
1510                         break;
1511                 case EXOSIP_IN_SUBSCRIPTION_RELEASED:
1512                         ms_message("CALL_SUBSCRIPTION_NEW ");
1513                         sal_exosip_in_subscription_closed(sal,ev);
1514                         break;
1515                 case EXOSIP_SUBSCRIPTION_UPDATE:
1516                         ms_message("CALL_SUBSCRIPTION_UPDATE");
1517                         break;
1518                 case EXOSIP_SUBSCRIPTION_NOTIFY:
1519                         ms_message("CALL_SUBSCRIPTION_NOTIFY");
1520                         sal_exosip_notify_recv(sal,ev);
1521                         break;
1522                 case EXOSIP_SUBSCRIPTION_ANSWERED:
1523                         ms_message("EXOSIP_SUBSCRIPTION_ANSWERED, ev->sid=%i, ev->did=%i\n",ev->sid,ev->did);
1524                         sal_exosip_subscription_answered(sal,ev);
1525                         break;
1526                 case EXOSIP_SUBSCRIPTION_CLOSED:
1527                         ms_message("EXOSIP_SUBSCRIPTION_CLOSED\n");
1528                         sal_exosip_subscription_closed(sal,ev);
1529                         break;
1530                 case EXOSIP_SUBSCRIPTION_REQUESTFAILURE:   /**< announce a request failure      */
1531                         if (ev->response && (ev->response->status_code == 407 || ev->response->status_code == 401)){
1532                                 return process_authentication(sal,ev);
1533                         }
1534         case EXOSIP_SUBSCRIPTION_SERVERFAILURE:
1535                 case EXOSIP_SUBSCRIPTION_GLOBALFAILURE:
1536                         sal_exosip_subscription_closed(sal,ev);
1537                         break;
1538                 case EXOSIP_REGISTRATION_FAILURE:
1539                         ms_message("REGISTRATION_FAILURE\n");
1540                         return registration_failure(sal,ev);
1541                         break;
1542                 case EXOSIP_REGISTRATION_SUCCESS:
1543                         authentication_ok(sal,ev);
1544                         registration_success(sal,ev);
1545                         break;
1546                 case EXOSIP_MESSAGE_NEW:
1547                         other_request(sal,ev);
1548                         break;
1549                 case EXOSIP_MESSAGE_PROCEEDING:
1550                 case EXOSIP_MESSAGE_ANSWERED:
1551                 case EXOSIP_MESSAGE_REDIRECTED:
1552                 case EXOSIP_MESSAGE_SERVERFAILURE:
1553                 case EXOSIP_MESSAGE_GLOBALFAILURE:
1554                         other_request_reply(sal,ev);
1555                         break;
1556                 case EXOSIP_MESSAGE_REQUESTFAILURE:
1557                         if (ev->response && (ev->response->status_code == 407 || ev->response->status_code == 401)){
1558                                 return process_authentication(sal,ev);
1559                         }
1560                         break;
1561                 default:
1562                         ms_message("Unhandled exosip event ! %i",ev->type);
1563                         break;
1564         }
1565         return TRUE;
1566 }
1567
1568 int sal_iterate(Sal *sal){
1569         eXosip_event_t *ev;
1570         while((ev=eXosip_event_wait(0,0))!=NULL){
1571                 if (process_event(sal,ev))
1572                         eXosip_event_free(ev);
1573         }
1574         eXosip_lock();
1575         eXosip_automatic_refresh();
1576         eXosip_unlock();
1577         return 0;
1578 }
1579
1580 int sal_register(SalOp *h, const char *proxy, const char *from, int expires){
1581         osip_message_t *msg;
1582         sal_op_set_route(h,proxy);
1583         if (h->rid==-1){
1584                 eXosip_lock();
1585                 h->rid=eXosip_register_build_initial_register(from,proxy,sal_op_get_contact(h),expires,&msg);
1586                 sal_add_register(h->base.root,h);
1587         }else{
1588                 eXosip_lock();
1589                 eXosip_register_build_register(h->rid,expires,&msg);    
1590         }
1591         eXosip_register_send_register(h->rid,msg);
1592         eXosip_unlock();
1593         h->expires=expires;
1594         return 0;
1595 }
1596
1597 int sal_unregister(SalOp *h){
1598         osip_message_t *msg=NULL;
1599         eXosip_lock();
1600         eXosip_register_build_register(h->rid,0,&msg);
1601         if (msg) eXosip_register_send_register(h->rid,msg);
1602         else ms_warning("Could not build unREGISTER !");
1603         eXosip_unlock();
1604         return 0;
1605 }
1606
1607
1608
1609 SalAddress * sal_address_new(const char *uri){
1610         osip_from_t *from;
1611         osip_from_init(&from);
1612         if (osip_from_parse(from,uri)!=0){
1613                 osip_from_free(from);
1614                 return NULL;
1615         }
1616         return (SalAddress*)from;
1617 }
1618
1619 SalAddress * sal_address_clone(const SalAddress *addr){
1620         osip_from_t *ret=NULL;
1621         osip_from_clone((osip_from_t*)addr,&ret);
1622         return (SalAddress*)ret;
1623 }
1624
1625 #define null_if_empty(s) (((s)!=NULL && (s)[0]!='\0') ? (s) : NULL )
1626
1627 const char *sal_address_get_scheme(const SalAddress *addr){
1628         const osip_from_t *u=(const osip_from_t*)addr;
1629         return null_if_empty(u->url->scheme);
1630 }
1631
1632 const char *sal_address_get_display_name(const SalAddress* addr){
1633         const osip_from_t *u=(const osip_from_t*)addr;
1634         return null_if_empty(u->displayname);
1635 }
1636
1637 const char *sal_address_get_username(const SalAddress *addr){
1638         const osip_from_t *u=(const osip_from_t*)addr;
1639         return null_if_empty(u->url->username);
1640 }
1641
1642 const char *sal_address_get_domain(const SalAddress *addr){
1643         const osip_from_t *u=(const osip_from_t*)addr;
1644         return null_if_empty(u->url->host);
1645 }
1646
1647 void sal_address_set_display_name(SalAddress *addr, const char *display_name){
1648         osip_from_t *u=(osip_from_t*)addr;
1649         if (u->displayname!=NULL){
1650                 osip_free(u->displayname);
1651                 u->displayname=NULL;
1652         }
1653         if (display_name!=NULL)
1654                 u->displayname=osip_strdup(display_name);
1655 }
1656
1657 void sal_address_set_username(SalAddress *addr, const char *username){
1658         osip_from_t *uri=(osip_from_t*)addr;
1659         if (uri->url->username!=NULL){
1660                 osip_free(uri->url->username);
1661                 uri->url->username=NULL;
1662         }
1663         if (username)
1664                 uri->url->username=osip_strdup(username);
1665 }
1666
1667 void sal_address_set_domain(SalAddress *addr, const char *host){
1668         osip_from_t *uri=(osip_from_t*)addr;
1669         if (uri->url->host!=NULL){
1670                 osip_free(uri->url->host);
1671                 uri->url->host=NULL;
1672         }
1673         if (host)
1674                 uri->url->host=osip_strdup(host);
1675 }
1676
1677 void sal_address_set_port(SalAddress *addr, const char *port){
1678         osip_from_t *uri=(osip_from_t*)addr;
1679         if (uri->url->port!=NULL){
1680                 osip_free(uri->url->port);
1681                 uri->url->port=NULL;
1682         }
1683         if (port)
1684                 uri->url->port=osip_strdup(port);
1685 }
1686
1687 void sal_address_set_port_int(SalAddress *uri, int port){
1688         char tmp[12];
1689         if (port==5060){
1690                 /*this is the default, special case to leave the port field blank*/
1691                 sal_address_set_port(uri,NULL);
1692                 return;
1693         }
1694         snprintf(tmp,sizeof(tmp),"%i",port);
1695         sal_address_set_port(uri,tmp);
1696 }
1697
1698 void sal_address_clean(SalAddress *addr){
1699         osip_generic_param_freelist(& ((osip_from_t*)addr)->gen_params);
1700         osip_uri_param_freelist(& ((osip_from_t*)addr)->url->url_params);
1701 }
1702
1703 char *sal_address_as_string(const SalAddress *u){
1704         char *tmp,*ret;
1705         osip_from_to_str((osip_from_t*)u,&tmp);
1706         ret=ms_strdup(tmp);
1707         osip_free(tmp);
1708         return ret;
1709 }
1710
1711 char *sal_address_as_string_uri_only(const SalAddress *u){
1712         char *tmp=NULL,*ret;
1713         osip_uri_to_str(((osip_from_t*)u)->url,&tmp);
1714         ret=ms_strdup(tmp);
1715         osip_free(tmp);
1716         return ret;
1717 }
1718
1719 void sal_address_destroy(SalAddress *u){
1720         osip_from_free((osip_from_t*)u);
1721 }
1722