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