]> sjero.net Git - linphone/blob - coreapi/sal_eXosip2.c
ba5730139614ceb3f80de28890d1d049e973fe0b
[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         const char *reason=NULL;
998         SalError error=SalErrorUnknown;
999         SalReason sr=SalReasonUnknown;
1000         
1001         op=(SalOp*)find_op(sal,ev);
1002
1003         if (op==NULL) {
1004                 ms_warning("Call failure reported for a closed call, ignored.");
1005                 return TRUE;
1006         }
1007
1008         if (ev->response){
1009                 code=osip_message_get_status_code(ev->response);
1010                 reason=osip_message_get_reason_phrase(ev->response);
1011         }
1012         switch(code)
1013         {
1014                 case 401:
1015                 case 407:
1016                         return process_authentication(sal,ev);
1017                         break;
1018                 case 400:
1019                         error=SalErrorUnknown;
1020                 break;
1021                 case 404:
1022                         error=SalErrorFailure;
1023                         sr=SalReasonNotFound;
1024                 break;
1025                 case 415:
1026                         error=SalErrorFailure;
1027                         sr=SalReasonMedia;
1028                 break;
1029                 case 422:
1030                         eXosip_default_action(ev);
1031                         return TRUE;
1032                 break;
1033                 case 480:
1034                         error=SalErrorFailure;
1035                         sr=SalReasonTemporarilyUnavailable;
1036                 case 486:
1037                         error=SalErrorFailure;
1038                         sr=SalReasonBusy;
1039                 break;
1040                 case 487:
1041                 break;
1042                 case 600:
1043                         error=SalErrorFailure;
1044                         sr=SalReasonDoNotDisturb;
1045                 break;
1046                 case 603:
1047                         error=SalErrorFailure;
1048                         sr=SalReasonDeclined;
1049                 break;
1050                 default:
1051                         if (code>0){
1052                                 error=SalErrorFailure;
1053                                 sr=SalReasonUnknown;
1054                         }else error=SalErrorNoResponse;
1055         }
1056         sal->callbacks.call_failure(op,error,sr,reason);
1057         return TRUE;
1058 }
1059
1060
1061 static void process_media_control_xml(Sal *sal, eXosip_event_t *ev){
1062         SalOp *op=find_op(sal,ev);
1063         osip_body_t *body=NULL;
1064
1065         if (op==NULL){
1066                 ms_warning("media control xml received without operation context!");
1067                 return ;
1068         }
1069         
1070         osip_message_get_body(ev->request,0,&body);
1071         if (body && body->body!=NULL &&
1072                 strstr(body->body,"picture_fast_update")){
1073                 osip_message_t *ans=NULL;
1074                 ms_message("Receiving VFU request !");
1075                 if (sal->callbacks.vfu_request){
1076                         sal->callbacks.vfu_request(op);
1077                         eXosip_call_build_answer(ev->tid,200,&ans);
1078                         if (ans)
1079                                 eXosip_call_send_answer(ev->tid,200,ans);
1080                 }
1081         }
1082 }
1083
1084 static void process_dtmf_relay(Sal *sal, eXosip_event_t *ev){
1085         SalOp *op=find_op(sal,ev);
1086         osip_body_t *body=NULL;
1087
1088         if (op==NULL){
1089                 ms_warning("media dtmf relay received without operation context!");
1090                 return ;
1091         }
1092         
1093         osip_message_get_body(ev->request,0,&body);
1094         if (body && body->body!=NULL){
1095                 osip_message_t *ans=NULL;
1096                 const char *name=strstr(body->body,"Signal");
1097                 if (name==NULL) name=strstr(body->body,"signal");
1098                 if (name==NULL) {
1099                         ms_warning("Could not extract the dtmf name from the SIP INFO.");
1100                 }else{
1101                         char tmp[2];
1102                         name+=strlen("signal");
1103                         if (sscanf(name," = %1s",tmp)==1){
1104                                 ms_message("Receiving dtmf %s via SIP INFO.",tmp);
1105                                 if (sal->callbacks.dtmf_received != NULL)
1106                                         sal->callbacks.dtmf_received(op, tmp[0]);
1107                         }
1108                 }
1109                 eXosip_call_build_answer(ev->tid,200,&ans);
1110                 if (ans)
1111                         eXosip_call_send_answer(ev->tid,200,ans);
1112         }
1113 }
1114
1115 static void call_message_new(Sal *sal, eXosip_event_t *ev){
1116         osip_message_t *ans=NULL;
1117         if (ev->request){
1118                 if (MSG_IS_INFO(ev->request)){
1119                         osip_content_type_t *ct;
1120                         ct=osip_message_get_content_type(ev->request);
1121                         if (ct && ct->subtype){
1122                                 if (strcmp(ct->subtype,"media_control+xml")==0)
1123                                         process_media_control_xml(sal,ev);
1124                                 else if (strcmp(ct->subtype,"dtmf-relay")==0)
1125                                         process_dtmf_relay(sal,ev);
1126                                 else {
1127                                         ms_message("Unhandled SIP INFO.");
1128                                         /*send an "Not implemented" answer*/
1129                                         eXosip_lock();
1130                                         eXosip_call_build_answer(ev->tid,501,&ans);
1131                                         if (ans)
1132                                                 eXosip_call_send_answer(ev->tid,501,ans);
1133                                         eXosip_unlock();
1134                                 }
1135                         }else{
1136                                 /*empty SIP INFO, probably to test we are alive. Send an empty answer*/
1137                                 eXosip_lock();
1138                                 eXosip_call_build_answer(ev->tid,200,&ans);
1139                                 if (ans)
1140                                         eXosip_call_send_answer(ev->tid,200,ans);
1141                                 eXosip_unlock();
1142                         }
1143                 }
1144                 if(MSG_IS_MESSAGE(ev->request)){
1145                         /* SIP messages could be received into call */
1146                         text_received(sal, ev);
1147                         eXosip_lock();
1148                         eXosip_call_build_answer(ev->tid,200,&ans);
1149                         if (ans)
1150                                 eXosip_call_send_answer(ev->tid,200,ans);
1151                         eXosip_unlock();
1152                 }
1153                 if(MSG_IS_REFER(ev->request)){
1154                         osip_header_t *h=NULL;
1155                         SalOp *op=find_op(sal,ev);
1156                         
1157                         ms_message("Receiving REFER request !");
1158                         osip_message_header_get_byname(ev->request,"Refer-To",0,&h);
1159                         eXosip_lock();
1160                         eXosip_call_build_answer(ev->tid,202,&ans);
1161                         if (ans)
1162                                 eXosip_call_send_answer(ev->tid,202,ans);
1163                         eXosip_unlock();
1164                         if (h){
1165                                 sal->callbacks.refer_received(sal,op,h->hvalue);
1166                         }
1167                         else
1168                         {
1169                                 ms_warning("cannot do anything with the refer without destination\n");
1170                         }
1171                 }
1172                 if(MSG_IS_NOTIFY(ev->request)){
1173                         osip_header_t *h=NULL;
1174                         char *from=NULL;
1175                         SalOp *op=find_op(sal,ev);
1176
1177                         ms_message("Receiving NOTIFY request !");
1178                         osip_from_to_str(ev->request->from,&from);
1179                         osip_message_header_get_byname(ev->request,"Event",0,&h);
1180                         if(h)
1181                                 sal->callbacks.notify(op,from,h->hvalue);
1182                         /*answer that we received the notify*/
1183                         eXosip_lock();
1184                         eXosip_call_build_answer(ev->tid,200,&ans);
1185                         if (ans)
1186                                 eXosip_call_send_answer(ev->tid,200,ans);
1187                         eXosip_unlock();
1188                         osip_free(from);
1189                 }
1190         }else ms_warning("call_message_new: No request ?");
1191 }
1192
1193 static void inc_update(Sal *sal, eXosip_event_t *ev){
1194         osip_message_t *msg=NULL;
1195         ms_message("Processing incoming UPDATE");
1196         eXosip_lock();
1197         eXosip_message_build_answer(ev->tid,200,&msg);
1198         if (msg!=NULL)
1199                 eXosip_message_send_answer(ev->tid,200,msg);
1200         eXosip_unlock();
1201 }
1202
1203 static bool_t comes_from_local_if(osip_message_t *msg){
1204         osip_via_t *via=NULL;
1205         osip_message_get_via(msg,0,&via);
1206         if (via){
1207                 const char *host;
1208                 host=osip_via_get_host(via);
1209                 if (strcmp(host,"127.0.0.1")==0 || strcmp(host,"::1")==0){
1210                         osip_generic_param_t *param=NULL;
1211                         osip_via_param_get_byname(via,"received",&param);
1212                         if (param==NULL) return TRUE;
1213                         if (param->gvalue &&
1214                                 (strcmp(param->gvalue,"127.0.0.1")==0 || strcmp(param->gvalue,"::1")==0)){
1215                                 return TRUE;
1216                         }
1217                 }
1218         }
1219         return FALSE;
1220 }
1221
1222 static void text_received(Sal *sal, eXosip_event_t *ev){
1223         osip_body_t *body=NULL;
1224         char *from=NULL,*msg;
1225         
1226         osip_message_get_body(ev->request,0,&body);
1227         if (body==NULL){
1228                 ms_error("Could not get text message from SIP body");
1229                 return;
1230         }
1231         msg=body->body;
1232         osip_from_to_str(ev->request->from,&from);
1233         sal->callbacks.text_received(sal,from,msg);
1234         osip_free(from);
1235 }
1236
1237 static void other_request(Sal *sal, eXosip_event_t *ev){
1238         ms_message("in other_request");
1239         if (ev->request==NULL) return;
1240         if (strcmp(ev->request->sip_method,"MESSAGE")==0){
1241                 text_received(sal,ev);
1242                 eXosip_message_send_answer(ev->tid,200,NULL);
1243         }else if (strcmp(ev->request->sip_method,"OPTIONS")==0){
1244                 osip_message_t *options=NULL;
1245                 eXosip_options_build_answer(ev->tid,200,&options);
1246                 osip_message_set_allow(options,"INVITE, ACK, BYE, CANCEL, OPTIONS, MESSAGE, SUBSCRIBE, NOTIFY, INFO");
1247                 osip_message_set_accept(options,"application/sdp");
1248                 eXosip_options_send_answer(ev->tid,200,options);
1249         }else if (strcmp(ev->request->sip_method,"WAKEUP")==0
1250                 && comes_from_local_if(ev->request)) {
1251                 eXosip_message_send_answer(ev->tid,200,NULL);
1252                 ms_message("Receiving WAKEUP request !");
1253                 sal->callbacks.internal_message(sal,"WAKEUP");
1254         }else if (strncmp(ev->request->sip_method, "REFER", 5) == 0){
1255                 ms_message("Receiving REFER request !");
1256                 if (comes_from_local_if(ev->request)) {
1257                         osip_header_t *h=NULL;
1258                         osip_message_header_get_byname(ev->request,"Refer-To",0,&h);
1259                         eXosip_message_send_answer(ev->tid,200,NULL);
1260                         if (h){
1261                                 sal->callbacks.refer_received(sal,NULL,h->hvalue);
1262                         }
1263                 }else ms_warning("Ignored REFER not coming from this local loopback interface.");
1264         }else if (strncmp(ev->request->sip_method, "UPDATE", 6) == 0){
1265                 inc_update(sal,ev);
1266     }else {
1267                 char *tmp=NULL;
1268                 size_t msglen=0;
1269                 osip_message_to_str(ev->request,&tmp,&msglen);
1270                 if (tmp){
1271                         ms_message("Unsupported request received:\n%s",tmp);
1272                         osip_free(tmp);
1273                 }
1274                 /*answer with a 501 Not implemented*/
1275                 eXosip_message_send_answer(ev->tid,501,NULL);
1276         }
1277 }
1278
1279 static void masquerade_via(osip_message_t *msg, const char *ip, const char *port){
1280         osip_via_t *via=NULL;
1281         osip_message_get_via(msg,0,&via);
1282         if (via){
1283                 osip_free(via->port);
1284                 via->port=osip_strdup(port);
1285                 osip_free(via->host);
1286                 via->host=osip_strdup(ip);
1287         }
1288 }
1289
1290 static bool_t register_again_with_updated_contact(SalOp *op, osip_message_t *orig_request, osip_message_t *last_answer){
1291         osip_message_t *msg;
1292         const char *received;
1293         int rport;
1294         osip_contact_t *ctt=NULL;
1295         char *tmp;
1296         char port[20];
1297         SalAddress *addr;
1298         
1299         if (extract_received_rport(last_answer,&received,&rport)==-1) return FALSE;
1300         osip_message_get_contact(orig_request,0,&ctt);
1301         if (strcmp(ctt->url->host,received)==0){
1302                 /*ip address matches, check ports*/
1303                 const char *contact_port=ctt->url->port;
1304                 if (contact_port==NULL || contact_port[0]=='\0')
1305                         contact_port="5060";
1306                 if (atoi(contact_port)==rport){
1307                         ms_message("Register has up to date contact, doing nothing.");
1308                         return FALSE;
1309                 }else ms_message("ports do not match, need to update the register (%s <> %i)", contact_port,rport);
1310         }
1311         eXosip_lock();
1312         msg=NULL;
1313         eXosip_register_build_register(op->rid,op->expires,&msg);
1314         if (msg==NULL){
1315                 eXosip_unlock();
1316                 ms_warning("Fail to create a contact updated register.");
1317                 return FALSE;
1318         }
1319         osip_message_get_contact(msg,0,&ctt);
1320         if (ctt->url->host!=NULL){
1321                 osip_free(ctt->url->host);
1322         }
1323         ctt->url->host=osip_strdup(received);
1324         if (ctt->url->port!=NULL){
1325                 osip_free(ctt->url->port);
1326         }
1327         snprintf(port,sizeof(port),"%i",rport);
1328         ctt->url->port=osip_strdup(port);
1329         if (op->masquerade_via) masquerade_via(msg,received,port);
1330         eXosip_register_send_register(op->rid,msg);
1331         eXosip_unlock();
1332         osip_contact_to_str(ctt,&tmp);
1333         addr=sal_address_new(tmp);
1334         osip_free(tmp);
1335         sal_address_clean(addr);
1336         tmp=sal_address_as_string(addr);
1337         sal_op_set_contact(op,tmp);
1338         sal_address_destroy(addr);
1339         ms_message("Resending new register with updated contact %s",tmp);
1340         ms_free(tmp);
1341         return TRUE;
1342 }
1343
1344 static void registration_success(Sal *sal, eXosip_event_t *ev){
1345         SalOp *op=sal_find_register(sal,ev->rid);
1346         osip_header_t *h=NULL;
1347         bool_t registered;
1348         if (op==NULL){
1349                 ms_error("Receiving register response for unknown operation");
1350                 return;
1351         }
1352         osip_message_get_expires(ev->request,0,&h);
1353         if (h!=NULL && atoi(h->hvalue)!=0){
1354                 registered=TRUE;
1355                 if (!register_again_with_updated_contact(op,ev->request,ev->response)){
1356                         sal->callbacks.register_success(op,registered);
1357                 }
1358         }else registered=FALSE;
1359 }
1360
1361 static bool_t registration_failure(Sal *sal, eXosip_event_t *ev){
1362         int status_code=0;
1363         const char *reason=NULL;
1364         SalOp *op=sal_find_register(sal,ev->rid);
1365         SalReason sr=SalReasonUnknown;
1366         SalError se=SalErrorUnknown;
1367         
1368         if (op==NULL){
1369                 ms_error("Receiving register failure for unknown operation");
1370                 return TRUE;
1371         }
1372         if (ev->response){
1373                 status_code=osip_message_get_status_code(ev->response);
1374                 reason=osip_message_get_reason_phrase(ev->response);
1375         }else return TRUE;
1376         switch(status_code){
1377                 case 401:
1378                 case 407:
1379                         return process_authentication(sal,ev);
1380                         break;
1381                 case 606: /*Not acceptable, workaround for proxies that don't like private addresses
1382                                  in vias, such as ekiga.net 
1383                                  On the opposite, freephonie.net bugs when via are masqueraded.
1384                                  */
1385                         op->masquerade_via=TRUE;
1386                 default:
1387                         /* if contact is up to date, process the failure, otherwise resend a new register with
1388                                 updated contact first, just in case the faillure is due to incorrect contact */
1389                         if (register_again_with_updated_contact(op,ev->request,ev->response))
1390                                 return TRUE; /*we are retrying with an updated contact*/
1391                         if (status_code==403){
1392                                 se=SalErrorFailure;
1393                                 sr=SalReasonForbidden;
1394                         }else if (status_code==0){
1395                                 se=SalErrorNoResponse;
1396                         }
1397                         sal->callbacks.register_failure(op,se,sr,reason);
1398         }
1399         return TRUE;
1400 }
1401
1402 static void other_request_reply(Sal *sal,eXosip_event_t *ev){
1403         SalOp *op=find_op(sal,ev);
1404
1405         if (op==NULL){
1406                 ms_warning("other_request_reply(): Receiving response to unknown request.");
1407                 return;
1408         }
1409         if (ev->response){
1410                 update_contact_from_response(op,ev->response);
1411                 if (ev->request && strcmp(osip_message_get_method(ev->request),"OPTIONS")==0)
1412                         sal->callbacks.ping_reply(op);
1413         }
1414 }
1415
1416 static bool_t process_event(Sal *sal, eXosip_event_t *ev){
1417         ms_message("linphone process event get a message %d\n",ev->type);
1418         switch(ev->type){
1419                 case EXOSIP_CALL_ANSWERED:
1420                         ms_message("CALL_ANSWERED\n");
1421                         call_accepted(sal,ev);
1422                         authentication_ok(sal,ev);
1423                         break;
1424                 case EXOSIP_CALL_CLOSED:
1425                 case EXOSIP_CALL_CANCELLED:
1426                         ms_message("CALL_CLOSED or CANCELLED\n");
1427                         call_terminated(sal,ev);
1428                         break;
1429                 case EXOSIP_CALL_TIMEOUT:
1430                 case EXOSIP_CALL_NOANSWER:
1431                         ms_message("CALL_TIMEOUT or NOANSWER\n");
1432                         return call_failure(sal,ev);
1433                         break;
1434                 case EXOSIP_CALL_REQUESTFAILURE:
1435                 case EXOSIP_CALL_GLOBALFAILURE:
1436                 case EXOSIP_CALL_SERVERFAILURE:
1437                         ms_message("CALL_REQUESTFAILURE or GLOBALFAILURE or SERVERFAILURE\n");
1438                         return call_failure(sal,ev);
1439                         break;
1440                 case EXOSIP_CALL_RELEASED:
1441                         ms_message("CALL_RELEASED\n");
1442                         call_released(sal, ev);
1443                         break;
1444                 case EXOSIP_CALL_INVITE:
1445                         ms_message("CALL_NEW\n");
1446                         inc_new_call(sal,ev);
1447                         break;
1448                 case EXOSIP_CALL_REINVITE:
1449                         handle_reinvite(sal,ev);
1450                         break;
1451                 case EXOSIP_CALL_ACK:
1452                         ms_message("CALL_ACK");
1453                         handle_ack(sal,ev);
1454                         break;
1455                 case EXOSIP_CALL_REDIRECTED:
1456                         ms_message("CALL_REDIRECTED");
1457                         eXosip_default_action(ev);
1458                         break;
1459                 case EXOSIP_CALL_PROCEEDING:
1460                         ms_message("CALL_PROCEEDING");
1461                         call_proceeding(sal,ev);
1462                         break;
1463                 case EXOSIP_CALL_RINGING:
1464                         ms_message("CALL_RINGING");
1465                         call_ringing(sal,ev);
1466                         break;
1467                 case EXOSIP_CALL_MESSAGE_NEW:
1468                         ms_message("EXOSIP_CALL_MESSAGE_NEW");
1469                         call_message_new(sal,ev);
1470                         break;
1471                 case EXOSIP_CALL_MESSAGE_REQUESTFAILURE:
1472                         if (ev->did<0 && ev->response &&
1473                                 (ev->response->status_code==407 || ev->response->status_code==401)){
1474                                  return process_authentication(sal,ev);
1475                         }
1476                         break;
1477                 case EXOSIP_IN_SUBSCRIPTION_NEW:
1478                         ms_message("CALL_IN_SUBSCRIPTION_NEW ");
1479                         sal_exosip_subscription_recv(sal,ev);
1480                         break;
1481                 case EXOSIP_IN_SUBSCRIPTION_RELEASED:
1482                         ms_message("CALL_SUBSCRIPTION_NEW ");
1483                         sal_exosip_in_subscription_closed(sal,ev);
1484                         break;
1485                 case EXOSIP_SUBSCRIPTION_UPDATE:
1486                         ms_message("CALL_SUBSCRIPTION_UPDATE");
1487                         break;
1488                 case EXOSIP_SUBSCRIPTION_NOTIFY:
1489                         ms_message("CALL_SUBSCRIPTION_NOTIFY");
1490                         sal_exosip_notify_recv(sal,ev);
1491                         break;
1492                 case EXOSIP_SUBSCRIPTION_ANSWERED:
1493                         ms_message("EXOSIP_SUBSCRIPTION_ANSWERED, ev->sid=%i, ev->did=%i\n",ev->sid,ev->did);
1494                         sal_exosip_subscription_answered(sal,ev);
1495                         break;
1496                 case EXOSIP_SUBSCRIPTION_CLOSED:
1497                         ms_message("EXOSIP_SUBSCRIPTION_CLOSED\n");
1498                         sal_exosip_subscription_closed(sal,ev);
1499                         break;
1500                 case EXOSIP_SUBSCRIPTION_REQUESTFAILURE:   /**< announce a request failure      */
1501                         if (ev->response && (ev->response->status_code == 407 || ev->response->status_code == 401)){
1502                                 return process_authentication(sal,ev);
1503                         }
1504         case EXOSIP_SUBSCRIPTION_SERVERFAILURE:
1505                 case EXOSIP_SUBSCRIPTION_GLOBALFAILURE:
1506                         sal_exosip_subscription_closed(sal,ev);
1507                         break;
1508                 case EXOSIP_REGISTRATION_FAILURE:
1509                         ms_message("REGISTRATION_FAILURE\n");
1510                         return registration_failure(sal,ev);
1511                         break;
1512                 case EXOSIP_REGISTRATION_SUCCESS:
1513                         authentication_ok(sal,ev);
1514                         registration_success(sal,ev);
1515                         break;
1516                 case EXOSIP_MESSAGE_NEW:
1517                         other_request(sal,ev);
1518                         break;
1519                 case EXOSIP_MESSAGE_PROCEEDING:
1520                 case EXOSIP_MESSAGE_ANSWERED:
1521                 case EXOSIP_MESSAGE_REDIRECTED:
1522                 case EXOSIP_MESSAGE_SERVERFAILURE:
1523                 case EXOSIP_MESSAGE_GLOBALFAILURE:
1524                         other_request_reply(sal,ev);
1525                         break;
1526                 case EXOSIP_MESSAGE_REQUESTFAILURE:
1527                         if (ev->response && (ev->response->status_code == 407 || ev->response->status_code == 401)){
1528                                 return process_authentication(sal,ev);
1529                         }
1530                         other_request_reply(sal,ev);
1531                         break;
1532                 default:
1533                         ms_message("Unhandled exosip event ! %i",ev->type);
1534                         break;
1535         }
1536         return TRUE;
1537 }
1538
1539 int sal_iterate(Sal *sal){
1540         eXosip_event_t *ev;
1541         while((ev=eXosip_event_wait(0,0))!=NULL){
1542                 if (process_event(sal,ev))
1543                         eXosip_event_free(ev);
1544         }
1545         eXosip_lock();
1546         eXosip_automatic_refresh();
1547         eXosip_unlock();
1548         return 0;
1549 }
1550
1551 int sal_register(SalOp *h, const char *proxy, const char *from, int expires){
1552         osip_message_t *msg;
1553         sal_op_set_route(h,proxy);
1554         if (h->rid==-1){
1555                 eXosip_lock();
1556                 h->rid=eXosip_register_build_initial_register(from,proxy,sal_op_get_contact(h),expires,&msg);
1557                 sal_add_register(h->base.root,h);
1558         }else{
1559                 eXosip_lock();
1560                 eXosip_register_build_register(h->rid,expires,&msg);    
1561         }
1562         eXosip_register_send_register(h->rid,msg);
1563         eXosip_unlock();
1564         h->expires=expires;
1565         return 0;
1566 }
1567
1568 int sal_unregister(SalOp *h){
1569         osip_message_t *msg=NULL;
1570         eXosip_lock();
1571         eXosip_register_build_register(h->rid,0,&msg);
1572         if (msg) eXosip_register_send_register(h->rid,msg);
1573         else ms_warning("Could not build unREGISTER !");
1574         eXosip_unlock();
1575         return 0;
1576 }
1577
1578
1579
1580 SalAddress * sal_address_new(const char *uri){
1581         osip_from_t *from;
1582         osip_from_init(&from);
1583         if (osip_from_parse(from,uri)!=0){
1584                 osip_from_free(from);
1585                 return NULL;
1586         }
1587         return (SalAddress*)from;
1588 }
1589
1590 SalAddress * sal_address_clone(const SalAddress *addr){
1591         osip_from_t *ret=NULL;
1592         osip_from_clone((osip_from_t*)addr,&ret);
1593         return (SalAddress*)ret;
1594 }
1595
1596 #define null_if_empty(s) (((s)!=NULL && (s)[0]!='\0') ? (s) : NULL )
1597
1598 const char *sal_address_get_scheme(const SalAddress *addr){
1599         const osip_from_t *u=(const osip_from_t*)addr;
1600         return null_if_empty(u->url->scheme);
1601 }
1602
1603 const char *sal_address_get_display_name(const SalAddress* addr){
1604         const osip_from_t *u=(const osip_from_t*)addr;
1605         return null_if_empty(u->displayname);
1606 }
1607
1608 const char *sal_address_get_username(const SalAddress *addr){
1609         const osip_from_t *u=(const osip_from_t*)addr;
1610         return null_if_empty(u->url->username);
1611 }
1612
1613 const char *sal_address_get_domain(const SalAddress *addr){
1614         const osip_from_t *u=(const osip_from_t*)addr;
1615         return null_if_empty(u->url->host);
1616 }
1617
1618 void sal_address_set_display_name(SalAddress *addr, const char *display_name){
1619         osip_from_t *u=(osip_from_t*)addr;
1620         if (u->displayname!=NULL){
1621                 osip_free(u->displayname);
1622                 u->displayname=NULL;
1623         }
1624         if (display_name!=NULL)
1625                 u->displayname=osip_strdup(display_name);
1626 }
1627
1628 void sal_address_set_username(SalAddress *addr, const char *username){
1629         osip_from_t *uri=(osip_from_t*)addr;
1630         if (uri->url->username!=NULL){
1631                 osip_free(uri->url->username);
1632                 uri->url->username=NULL;
1633         }
1634         if (username)
1635                 uri->url->username=osip_strdup(username);
1636 }
1637
1638 void sal_address_set_domain(SalAddress *addr, const char *host){
1639         osip_from_t *uri=(osip_from_t*)addr;
1640         if (uri->url->host!=NULL){
1641                 osip_free(uri->url->host);
1642                 uri->url->host=NULL;
1643         }
1644         if (host)
1645                 uri->url->host=osip_strdup(host);
1646 }
1647
1648 void sal_address_set_port(SalAddress *addr, const char *port){
1649         osip_from_t *uri=(osip_from_t*)addr;
1650         if (uri->url->port!=NULL){
1651                 osip_free(uri->url->port);
1652                 uri->url->port=NULL;
1653         }
1654         if (port)
1655                 uri->url->port=osip_strdup(port);
1656 }
1657
1658 void sal_address_set_port_int(SalAddress *uri, int port){
1659         char tmp[12];
1660         if (port==5060){
1661                 /*this is the default, special case to leave the port field blank*/
1662                 sal_address_set_port(uri,NULL);
1663                 return;
1664         }
1665         snprintf(tmp,sizeof(tmp),"%i",port);
1666         sal_address_set_port(uri,tmp);
1667 }
1668
1669 void sal_address_clean(SalAddress *addr){
1670         osip_generic_param_freelist(& ((osip_from_t*)addr)->gen_params);
1671         osip_uri_param_freelist(& ((osip_from_t*)addr)->url->url_params);
1672 }
1673
1674 char *sal_address_as_string(const SalAddress *u){
1675         char *tmp,*ret;
1676         osip_from_to_str((osip_from_t*)u,&tmp);
1677         ret=ms_strdup(tmp);
1678         osip_free(tmp);
1679         return ret;
1680 }
1681
1682 char *sal_address_as_string_uri_only(const SalAddress *u){
1683         char *tmp=NULL,*ret;
1684         osip_uri_to_str(((osip_from_t*)u)->url,&tmp);
1685         ret=ms_strdup(tmp);
1686         osip_free(tmp);
1687         return ret;
1688 }
1689
1690 void sal_address_destroy(SalAddress *u){
1691         osip_from_free((osip_from_t*)u);
1692 }
1693 void sal_set_keepalive_period(Sal *ctx,unsigned int value) {
1694         eXosip_set_option (EXOSIP_OPT_UDP_KEEP_ALIVE, &value);
1695 }
1696