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