]> sjero.net Git - linphone/blob - coreapi/callbacks.c
add message storage
[linphone] / coreapi / callbacks.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
20
21 #include "sal.h"
22
23 #include "linphonecore.h"
24 #include "private.h"
25 #include "mediastreamer2/mediastream.h"
26 #include "lpconfig.h"
27
28 static void register_failure(SalOp *op, SalError error, SalReason reason, const char *details);
29
30 static int media_parameters_changed(LinphoneCall *call, SalMediaDescription *oldmd, SalMediaDescription *newmd) {
31         if (call->params.in_conference != call->current_params.in_conference) return SAL_MEDIA_DESCRIPTION_CHANGED;
32         if (call->up_bw != linphone_core_get_upload_bandwidth(call->core)) return SAL_MEDIA_DESCRIPTION_CHANGED;
33         return sal_media_description_equals(oldmd, newmd);
34 }
35
36 void linphone_core_update_streams_destinations(LinphoneCore *lc, LinphoneCall *call, SalMediaDescription *old_md, SalMediaDescription *new_md) {
37         SalStreamDescription *old_audiodesc = NULL;
38         SalStreamDescription *old_videodesc = NULL;
39         SalStreamDescription *new_audiodesc = NULL;
40         SalStreamDescription *new_videodesc = NULL;
41         char *rtp_addr, *rtcp_addr;
42         int i;
43
44         for (i = 0; i < old_md->n_active_streams; i++) {
45                 if (old_md->streams[i].type == SalAudio) {
46                         old_audiodesc = &old_md->streams[i];
47                 } else if (old_md->streams[i].type == SalVideo) {
48                         old_videodesc = &old_md->streams[i];
49                 }
50         }
51         for (i = 0; i < new_md->n_active_streams; i++) {
52                 if (new_md->streams[i].type == SalAudio) {
53                         new_audiodesc = &new_md->streams[i];
54                 } else if (new_md->streams[i].type == SalVideo) {
55                         new_videodesc = &new_md->streams[i];
56                 }
57         }
58         if (call->audiostream && new_audiodesc) {
59                 rtp_addr = (new_audiodesc->rtp_addr[0] != '\0') ? new_audiodesc->rtp_addr : new_md->addr;
60                 rtcp_addr = (new_audiodesc->rtcp_addr[0] != '\0') ? new_audiodesc->rtcp_addr : new_md->addr;
61                 ms_message("Change audio stream destination: RTP=%s:%d RTCP=%s:%d", rtp_addr, new_audiodesc->rtp_port, rtcp_addr, new_audiodesc->rtcp_port);
62                 rtp_session_set_remote_addr_full(call->audiostream->ms.session, rtp_addr, new_audiodesc->rtp_port, rtcp_addr, new_audiodesc->rtcp_port);
63         }
64 #ifdef VIDEO_ENABLED
65         if (call->videostream && new_videodesc) {
66                 rtp_addr = (new_videodesc->rtp_addr[0] != '\0') ? new_videodesc->rtp_addr : new_md->addr;
67                 rtcp_addr = (new_videodesc->rtcp_addr[0] != '\0') ? new_videodesc->rtcp_addr : new_md->addr;
68                 ms_message("Change video stream destination: RTP=%s:%d RTCP=%s:%d", rtp_addr, new_videodesc->rtp_port, rtcp_addr, new_videodesc->rtcp_port);
69                 rtp_session_set_remote_addr_full(call->videostream->ms.session, rtp_addr, new_videodesc->rtp_port, rtcp_addr, new_videodesc->rtcp_port);
70         }
71 #endif
72
73         /* Copy address and port values from new_md to old_md since we will keep old_md as resultdesc */
74         strcpy(old_md->addr, new_md->addr);
75         if (old_audiodesc && new_audiodesc) {
76                 strcpy(old_audiodesc->rtp_addr, new_audiodesc->rtp_addr);
77                 strcpy(old_audiodesc->rtcp_addr, new_audiodesc->rtcp_addr);
78                 old_audiodesc->rtp_port = new_audiodesc->rtp_port;
79                 old_audiodesc->rtcp_port = new_audiodesc->rtcp_port;
80         }
81         if (old_videodesc && new_videodesc) {
82                 strcpy(old_videodesc->rtp_addr, new_videodesc->rtp_addr);
83                 strcpy(old_videodesc->rtcp_addr, new_videodesc->rtcp_addr);
84                 old_videodesc->rtp_port = new_videodesc->rtp_port;
85                 old_videodesc->rtcp_port = new_videodesc->rtcp_port;
86         }
87 }
88
89 void linphone_core_update_streams(LinphoneCore *lc, LinphoneCall *call, SalMediaDescription *new_md){
90         SalMediaDescription *oldmd=call->resultdesc;
91         
92         if (lc->ringstream!=NULL){
93                 ring_stop(lc->ringstream);
94                 lc->ringstream=NULL;
95         }
96         if (new_md!=NULL){
97                 sal_media_description_ref(new_md);
98                 call->media_pending=FALSE;
99         }else{
100                 call->media_pending=TRUE;
101         }
102         call->resultdesc=new_md;
103         if ((call->audiostream && call->audiostream->ms.ticker) || (call->videostream && call->videostream->ms.ticker)){
104                 /* we already started media: check if we really need to restart it*/
105                 if (oldmd){
106                         int md_changed = media_parameters_changed(call, oldmd, new_md);
107                         if ((md_changed & SAL_MEDIA_DESCRIPTION_CODEC_CHANGED) || call->playing_ringbacktone) {
108                                 ms_message("Media descriptions are different, need to restart the streams.");
109                         } else {
110                                 if (md_changed == SAL_MEDIA_DESCRIPTION_UNCHANGED) {
111                                         /*as nothing has changed, keep the oldmd */
112                                         call->resultdesc=oldmd;
113                                         sal_media_description_unref(new_md);
114                                         if (call->all_muted){
115                                                 ms_message("Early media finished, unmuting inputs...");
116                                                 /*we were in early media, now we want to enable real media */
117                                                 linphone_call_enable_camera (call,linphone_call_camera_enabled (call));
118                                                 if (call->audiostream)
119                                                         linphone_core_mute_mic (lc, linphone_core_is_mic_muted(lc));
120 #ifdef VIDEO_ENABLED
121                                                 if (call->videostream && call->camera_active)
122                                                         video_stream_change_camera(call->videostream,lc->video_conf.device );
123 #endif
124                                         }
125                                         ms_message("No need to restart streams, SDP is unchanged.");
126                                         return;
127                                 }
128                                 else {
129                                         if (md_changed & SAL_MEDIA_DESCRIPTION_NETWORK_CHANGED) {
130                                                 ms_message("Network parameters have changed, update them.");
131                                                 linphone_core_update_streams_destinations(lc, call, oldmd, new_md);
132                                         }
133                                         if (md_changed & SAL_MEDIA_DESCRIPTION_CRYPTO_CHANGED) {
134                                                 ms_message("Crypto parameters have changed, update them.");
135                                                 linphone_call_update_crypto_parameters(call, oldmd, new_md);
136                                         }
137                                         call->resultdesc = oldmd;
138                                         sal_media_description_unref(new_md);
139                                         return;
140                                 }
141                         }
142                 }
143                 linphone_call_stop_media_streams (call);
144                 linphone_call_init_media_streams (call);
145         }
146         if (oldmd) 
147                 sal_media_description_unref(oldmd);
148         
149         if (new_md) {
150                 bool_t all_muted=FALSE;
151                 bool_t send_ringbacktone=FALSE;
152                 
153                 if (call->audiostream==NULL){
154                         /*this happens after pausing the call locally. The streams is destroyed and then we wait the 200Ok to recreate it*/
155                         linphone_call_init_media_streams (call);
156                 }
157                 if (call->state==LinphoneCallIncomingEarlyMedia && linphone_core_get_remote_ringback_tone (lc)!=NULL){
158                         send_ringbacktone=TRUE;
159                 }
160                 if (call->state==LinphoneCallIncomingEarlyMedia ||
161                     (call->state==LinphoneCallOutgoingEarlyMedia && !call->params.real_early_media)){
162                         all_muted=TRUE;
163                 }
164                 linphone_call_start_media_streams(call,all_muted,send_ringbacktone);
165         }
166 }
167 #if 0
168 static bool_t is_duplicate_call(LinphoneCore *lc, const LinphoneAddress *from, const LinphoneAddress *to){
169         MSList *elem;
170         for(elem=lc->calls;elem!=NULL;elem=elem->next){
171                 LinphoneCall *call=(LinphoneCall*)elem->data;
172                 if (linphone_address_weak_equal(call->log->from,from) &&
173                     linphone_address_weak_equal(call->log->to, to)){
174                         return TRUE;
175                 }
176         }
177         return FALSE;
178 }
179 #endif
180
181 static bool_t already_a_call_with_remote_address(const LinphoneCore *lc, const LinphoneAddress *remote) {
182         ms_warning(" searching for already_a_call_with_remote_address.");
183
184         MSList *elem;
185         for(elem=lc->calls;elem!=NULL;elem=elem->next){
186                 const LinphoneCall *call=(LinphoneCall*)elem->data;
187                 const LinphoneAddress *cRemote=linphone_call_get_remote_address(call);
188                 if (linphone_address_weak_equal(cRemote,remote)) {
189                         ms_warning("already_a_call_with_remote_address found.");
190                         return TRUE;
191                 }
192         }
193         return FALSE;
194 }
195
196 static bool_t already_a_call_pending(LinphoneCore *lc){
197         MSList *elem;
198         for(elem=lc->calls;elem!=NULL;elem=elem->next){
199                 LinphoneCall *call=(LinphoneCall*)elem->data;
200                 if (call->state==LinphoneCallIncomingReceived
201                     || call->state==LinphoneCallOutgoingInit
202                     || call->state==LinphoneCallOutgoingProgress
203                     || call->state==LinphoneCallOutgoingEarlyMedia
204                     || call->state==LinphoneCallOutgoingRinging){
205                         return TRUE;
206                 }
207         }
208         return FALSE;
209 }
210
211 static void call_received(SalOp *h){
212         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(h));
213         LinphoneCall *call;
214         const char *from,*to;
215         LinphoneAddress *from_addr, *to_addr;
216         bool_t prevent_colliding_calls=lp_config_get_int(lc->config,"sip","prevent_colliding_calls",TRUE);
217         
218         /* first check if we can answer successfully to this invite */
219         if (lc->presence_mode==LinphoneStatusBusy ||
220             lc->presence_mode==LinphoneStatusOffline ||
221             lc->presence_mode==LinphoneStatusDoNotDisturb ||
222             lc->presence_mode==LinphoneStatusMoved){
223                 if (lc->presence_mode==LinphoneStatusBusy )
224                         sal_call_decline(h,SalReasonBusy,NULL);
225                 else if (lc->presence_mode==LinphoneStatusOffline)
226                         sal_call_decline(h,SalReasonTemporarilyUnavailable,NULL);
227                 else if (lc->presence_mode==LinphoneStatusDoNotDisturb)
228                         sal_call_decline(h,SalReasonTemporarilyUnavailable,NULL);
229                 else if (lc->alt_contact!=NULL && lc->presence_mode==LinphoneStatusMoved)
230                         sal_call_decline(h,SalReasonRedirect,lc->alt_contact);
231                 sal_op_release(h);
232                 return;
233         }
234         if (!linphone_core_can_we_add_call(lc)){/*busy*/
235                 sal_call_decline(h,SalReasonBusy,NULL);
236                 sal_op_release(h);
237                 return;
238         }
239         from=sal_op_get_from(h);
240         to=sal_op_get_to(h);
241         from_addr=linphone_address_new(from);
242         to_addr=linphone_address_new(to);
243
244         if ((already_a_call_with_remote_address(lc,from_addr) && prevent_colliding_calls) || already_a_call_pending(lc)){
245                 ms_warning("Receiving another call while one is ringing or initiated, refusing this one with busy message.");
246                 sal_call_decline(h,SalReasonBusy,NULL);
247                 sal_op_release(h);
248                 linphone_address_destroy(from_addr);
249                 linphone_address_destroy(to_addr);
250                 return;
251         }
252         
253         call=linphone_call_new_incoming(lc,from_addr,to_addr,h);
254         
255         /* the call is acceptable so we can now add it to our list */
256         linphone_core_add_call(lc,call);
257         linphone_call_ref(call); /*prevent the call from being destroyed while we are notifying, if the user declines within the state callback */
258
259         if ((linphone_core_get_firewall_policy(lc) == LinphonePolicyUseIce) && (call->ice_session != NULL)) {
260                 /* Defer ringing until the end of the ICE candidates gathering process. */
261                 ms_message("Defer ringing to gather ICE candidates");
262                 return;
263         }
264 #ifdef BUILD_UPNP
265         if ((linphone_core_get_firewall_policy(lc) == LinphonePolicyUseUpnp) && (call->upnp_session != NULL)) {
266                 /* Defer ringing until the end of the ICE candidates gathering process. */
267                 ms_message("Defer ringing to gather uPnP candidates");
268                 return;
269         }
270 #endif //BUILD_UPNP
271
272         linphone_core_notify_incoming_call(lc,call);
273 }
274
275 static void call_ringing(SalOp *h){
276         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(h));
277         LinphoneCall *call=(LinphoneCall*)sal_op_get_user_pointer(h);
278         SalMediaDescription *md;
279         
280         if (call==NULL) return;
281         
282         if (lc->vtable.display_status)
283                 lc->vtable.display_status(lc,_("Remote ringing."));
284         
285         md=sal_call_get_final_media_description(h);
286         if (md==NULL){
287                 if (lc->ringstream && lc->dmfs_playing_start_time!=0){
288                         ring_stop(lc->ringstream);
289                         lc->ringstream=NULL;
290                         lc->dmfs_playing_start_time=0;
291                 }
292                 if (lc->ringstream!=NULL) return;       /*already ringing !*/
293                 if (lc->sound_conf.play_sndcard!=NULL){
294                         MSSndCard *ringcard=lc->sound_conf.lsd_card ? lc->sound_conf.lsd_card : lc->sound_conf.play_sndcard;
295                         if (call->localdesc->streams[0].max_rate>0) ms_snd_card_set_preferred_sample_rate(ringcard, call->localdesc->streams[0].max_rate);
296                         /*we release sound before playing ringback tone*/
297                         if (call->audiostream)
298                                 audio_stream_unprepare_sound(call->audiostream);
299                         lc->ringstream=ring_start(lc->sound_conf.remote_ring,2000,ringcard);
300                 }
301                 ms_message("Remote ringing...");
302                 if (lc->vtable.display_status) 
303                         lc->vtable.display_status(lc,_("Remote ringing..."));
304                 linphone_call_set_state(call,LinphoneCallOutgoingRinging,"Remote ringing");
305         }else{
306                 /*accept early media */
307                 if (call->audiostream && audio_stream_started(call->audiostream)){
308                         /*streams already started */
309                         ms_message("Early media already started.");
310                         return;
311                 }
312                 if (lc->vtable.show) lc->vtable.show(lc);
313                 if (lc->vtable.display_status) 
314                         lc->vtable.display_status(lc,_("Early media."));
315                 linphone_call_set_state(call,LinphoneCallOutgoingEarlyMedia,"Early media");
316                 if (lc->ringstream!=NULL){
317                         ring_stop(lc->ringstream);
318                         lc->ringstream=NULL;
319                 }
320                 ms_message("Doing early media...");
321                 linphone_core_update_streams(lc,call,md);
322         }
323 }
324
325 /*
326  * could be reach :
327  *  - when the call is accepted
328  *  - when a request is accepted (pause, resume)
329  */
330 static void call_accepted(SalOp *op){
331         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(op));
332         LinphoneCall *call=(LinphoneCall*)sal_op_get_user_pointer(op);
333         SalMediaDescription *md;
334         
335         if (call==NULL){
336                 ms_warning("No call to accept.");
337                 return ;
338         }
339
340         /* Handle remote ICE attributes if any. */
341         if (call->ice_session != NULL) {
342                 linphone_core_update_ice_from_remote_media_description(call, sal_call_get_remote_media_description(op));
343         }
344 #ifdef BUILD_UPNP
345         if (call->upnp_session != NULL) {
346                 linphone_core_update_upnp_from_remote_media_description(call, sal_call_get_remote_media_description(op));
347         }
348 #endif //BUILD_UPNP
349
350         md=sal_call_get_final_media_description(op);
351         call->params.has_video &= linphone_core_media_description_contains_video_stream(md);
352         
353         if (call->state==LinphoneCallOutgoingProgress ||
354             call->state==LinphoneCallOutgoingRinging ||
355             call->state==LinphoneCallOutgoingEarlyMedia){
356                 linphone_call_set_state(call,LinphoneCallConnected,"Connected");
357                 if (call->referer) linphone_core_notify_refer_state(lc,call->referer,call);
358         }
359         if (md && !sal_media_description_empty(md) && !linphone_core_incompatible_security(lc,md)){
360                 linphone_call_update_remote_session_id_and_ver(call);
361                 if (sal_media_description_has_dir(md,SalStreamSendOnly) ||
362                     sal_media_description_has_dir(md,SalStreamInactive)){
363                         if (lc->vtable.display_status){
364                                 char *tmp=linphone_call_get_remote_address_as_string (call);
365                                 char *msg=ms_strdup_printf(_("Call with %s is paused."),tmp);
366                                 lc->vtable.display_status(lc,msg);
367                                 ms_free(tmp);
368                                 ms_free(msg);
369                         }
370                         linphone_core_update_streams (lc,call,md);
371                         linphone_call_set_state(call,LinphoneCallPaused,"Call paused");
372                         if (call->refer_pending)
373                                 linphone_core_start_refered_call(lc,call);
374                 }else if (sal_media_description_has_dir(md,SalStreamRecvOnly)){
375                         /*we are put on hold when the call is initially accepted */
376                         if (lc->vtable.display_status){
377                                 char *tmp=linphone_call_get_remote_address_as_string (call);
378                                 char *msg=ms_strdup_printf(_("Call answered by %s - on hold."),tmp);
379                                 lc->vtable.display_status(lc,msg);
380                                 ms_free(tmp);
381                                 ms_free(msg);
382                         }
383                         linphone_core_update_streams (lc,call,md);
384                         linphone_call_set_state(call,LinphoneCallPausedByRemote,"Call paused by remote");
385                 }else{
386                         if (call->state!=LinphoneCallUpdating){
387                                 if (call->state==LinphoneCallResuming){
388                                         if (lc->vtable.display_status){
389                                                 lc->vtable.display_status(lc,_("Call resumed."));
390                                         }
391                                 }else{
392                                         if (lc->vtable.display_status){
393                                                 char *tmp=linphone_call_get_remote_address_as_string (call);
394                                                 char *msg=ms_strdup_printf(_("Call answered by %s."),tmp);
395                                                 lc->vtable.display_status(lc,msg);
396                                                 ms_free(tmp);
397                                                 ms_free(msg);
398                                         }
399                                 }
400                         }
401                         linphone_core_update_streams (lc,call,md);
402                         if (!call->current_params.in_conference)
403                                 lc->current_call=call;
404                         linphone_call_set_state(call, LinphoneCallStreamsRunning, "Streams running");
405                 }
406         }else{
407                 /*send a bye*/
408                 ms_error("Incompatible SDP offer received in 200Ok, need to abort the call");
409                 linphone_core_abort_call(lc,call,_("Incompatible, check codecs or security settings..."));
410         }
411 }
412
413 static void call_ack(SalOp *op){
414         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(op));
415         LinphoneCall *call=(LinphoneCall*)sal_op_get_user_pointer(op);
416         if (call==NULL){
417                 ms_warning("No call to be ACK'd");
418                 return ;
419         }
420         if (call->media_pending){
421                 SalMediaDescription *md=sal_call_get_final_media_description(op);
422                 if (md && !sal_media_description_empty(md)){
423                         linphone_core_update_streams (lc,call,md);
424                         linphone_call_set_state (call,LinphoneCallStreamsRunning,"Connected (streams running)");
425                 }else{
426                         /*send a bye*/
427                         ms_error("Incompatible SDP response received in ACK, need to abort the call");
428                         linphone_core_abort_call(lc,call,"No codec intersection");
429                         return;
430                 }
431         }
432 }
433
434 static void call_accept_update(LinphoneCore *lc, LinphoneCall *call){
435         SalMediaDescription *md;
436         SalMediaDescription *rmd=sal_call_get_remote_media_description(call->op);
437         if ((rmd!=NULL) && (call->ice_session!=NULL)) {
438                 linphone_core_update_ice_from_remote_media_description(call,rmd);
439                 linphone_core_update_local_media_description_from_ice(call->localdesc,call->ice_session);
440         }
441 #ifdef BUILD_UPNP
442         if(call->upnp_session != NULL) {
443                 linphone_core_update_upnp_from_remote_media_description(call, rmd);
444                 linphone_core_update_local_media_description_from_upnp(call->localdesc,call->upnp_session);
445         }
446 #endif //BUILD_UPNP
447         linphone_call_update_remote_session_id_and_ver(call);
448         sal_call_accept(call->op);
449         md=sal_call_get_final_media_description(call->op);
450         if (md && !sal_media_description_empty(md))
451                 linphone_core_update_streams(lc,call,md);
452 }
453
454 static void call_resumed(LinphoneCore *lc, LinphoneCall *call){
455         call_accept_update(lc,call);
456         if(lc->vtable.display_status)
457                 lc->vtable.display_status(lc,_("We have been resumed."));
458         linphone_call_set_state(call,LinphoneCallStreamsRunning,"Connected (streams running)");
459         linphone_call_set_transfer_state(call, LinphoneCallIdle);
460 }
461
462 static void call_paused_by_remote(LinphoneCore *lc, LinphoneCall *call){
463         call_accept_update(lc,call);
464         /* we are being paused */
465         if(lc->vtable.display_status)
466                 lc->vtable.display_status(lc,_("We are paused by other party."));
467         linphone_call_set_state (call,LinphoneCallPausedByRemote,"Call paused by remote");
468 }
469
470 static void call_updated_by_remote(LinphoneCore *lc, LinphoneCall *call){
471         if(lc->vtable.display_status)
472                 lc->vtable.display_status(lc,_("Call is updated by remote."));
473         call->defer_update=FALSE;
474         linphone_call_set_state(call, LinphoneCallUpdatedByRemote,"Call updated by remote");
475         if (call->defer_update==FALSE){
476                 linphone_core_accept_call_update(lc,call,NULL);
477         }
478 }
479
480 /* this callback is called when an incoming re-INVITE modifies the session*/
481 static void call_updating(SalOp *op){
482         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(op));
483         LinphoneCall *call=(LinphoneCall*)sal_op_get_user_pointer(op);
484         SalMediaDescription *rmd=sal_call_get_remote_media_description(op);
485
486         if (rmd==NULL){
487                 /* case of a reINVITE without SDP */
488                 call_accept_update(lc,call);
489                 call->media_pending=TRUE;
490                 return;
491         }
492
493         switch(call->state){
494                 case LinphoneCallPausedByRemote:
495                         if (sal_media_description_has_dir(rmd,SalStreamSendRecv) || sal_media_description_has_dir(rmd,SalStreamRecvOnly)){
496                                 call_resumed(lc,call);
497                         }else call_paused_by_remote(lc,call);
498                 break;
499                 case LinphoneCallStreamsRunning:
500                 case LinphoneCallConnected:
501                         if (sal_media_description_has_dir(rmd,SalStreamSendOnly) || sal_media_description_has_dir(rmd,SalStreamInactive)){
502                                 call_paused_by_remote(lc,call);
503                         }else{
504                                 call_updated_by_remote(lc,call);
505                         }
506                 break;
507                 default:
508                         call_accept_update(lc,call);
509         }
510 }
511
512 static void call_terminated(SalOp *op, const char *from){
513         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(op));
514         LinphoneCall *call=(LinphoneCall*)sal_op_get_user_pointer(op);
515
516         if (call==NULL) return;
517         
518         switch(linphone_call_get_state(call)){
519                 case LinphoneCallEnd:
520                 case LinphoneCallError:
521                         ms_warning("call_terminated: ignoring.");
522                         return;
523                 break;
524                 case LinphoneCallIncomingReceived:
525                 case LinphoneCallIncomingEarlyMedia:
526                         call->reason=LinphoneReasonNotAnswered;
527                 break;
528                 default:
529                 break;
530         }
531         ms_message("Current call terminated...");
532         //we stop the call only if we have this current call or if we are in call
533         if (lc->ringstream!=NULL && ( (ms_list_size(lc->calls)  == 1) || linphone_core_in_call(lc) )) {
534                 ring_stop(lc->ringstream);
535                 lc->ringstream=NULL;
536         }
537         linphone_call_stop_media_streams(call);
538         if (lc->vtable.show!=NULL)
539                 lc->vtable.show(lc);
540         if (lc->vtable.display_status!=NULL)
541                 lc->vtable.display_status(lc,_("Call terminated."));
542
543 #ifdef BUILD_UPNP
544         linphone_call_delete_upnp_session(call);
545 #endif //BUILD_UPNP
546
547         linphone_call_set_state(call, LinphoneCallEnd,"Call ended");
548 }
549
550 static void call_failure(SalOp *op, SalError error, SalReason sr, const char *details, int code){
551         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(op));
552         char *msg486=_("User is busy.");
553         char *msg480=_("User is temporarily unavailable.");
554         /*char *retrymsg=_("%s. Retry after %i minute(s).");*/
555         char *msg600=_("User does not want to be disturbed.");
556         char *msg603=_("Call declined.");
557         const char *msg=details;
558         LinphoneCall *call=(LinphoneCall*)sal_op_get_user_pointer(op);
559
560         if (call==NULL){
561                 ms_warning("Call faillure reported on already cleaned call ?");
562                 return ;
563         }
564         
565         if (lc->vtable.show) lc->vtable.show(lc);
566
567         if (error==SalErrorNoResponse){
568                 msg=_("No response.");
569                 if (lc->vtable.display_status)
570                         lc->vtable.display_status(lc,msg);
571         }else if (error==SalErrorProtocol){
572                 msg=details ? details : _("Protocol error.");
573                 if (lc->vtable.display_status)
574                         lc->vtable.display_status(lc, msg);
575         }else if (error==SalErrorFailure){
576                 switch(sr){
577                         case SalReasonDeclined:
578                                 msg=msg603;
579                                 if (lc->vtable.display_status)
580                                         lc->vtable.display_status(lc,msg603);
581                         break;
582                         case SalReasonBusy:
583                                 msg=msg486;
584                                 if (lc->vtable.display_status)
585                                         lc->vtable.display_status(lc,msg486);
586                         break;
587                         case SalReasonRedirect:
588                                 msg=_("Redirected");
589                                 if (lc->vtable.display_status)
590                                         lc->vtable.display_status(lc,msg);
591                         break;
592                         case SalReasonTemporarilyUnavailable:
593                                 msg=msg480;
594                                 if (lc->vtable.display_status)
595                                         lc->vtable.display_status(lc,msg480);
596                         break;
597                         case SalReasonNotFound:
598                                 if (lc->vtable.display_status)
599                                         lc->vtable.display_status(lc,msg);
600                         break;
601                         case SalReasonDoNotDisturb:
602                                 msg=msg600;
603                                 if (lc->vtable.display_status)
604                                         lc->vtable.display_status(lc,msg600);
605                         break;
606                         case SalReasonMedia:
607                         //media_encryption_mandatory
608                                 if (call->params.media_encryption == LinphoneMediaEncryptionSRTP && 
609                                         !linphone_core_is_media_encryption_mandatory(lc)) {
610                                         int i;
611                                         ms_message("Outgoing call failed with SRTP (SAVP) enabled - retrying with AVP");
612                                         linphone_call_stop_media_streams(call);
613                                         if (call->state==LinphoneCallOutgoingInit || call->state==LinphoneCallOutgoingProgress){
614                                                 /* clear SRTP local params */
615                                                 call->params.media_encryption = LinphoneMediaEncryptionNone;
616                                                 for(i=0; i<call->localdesc->n_active_streams; i++) {
617                                                         call->localdesc->streams[i].proto = SalProtoRtpAvp;
618                                                         memset(call->localdesc->streams[i].crypto, 0, sizeof(call->localdesc->streams[i].crypto));
619                                                 }
620                                                 linphone_core_start_invite(lc, call);
621                                         }
622                                         return;
623                                 }
624                                 msg=_("Incompatible media parameters.");
625                                 if (lc->vtable.display_status)
626                                         lc->vtable.display_status(lc,msg);
627                         break;
628                         default:
629                                 if (lc->vtable.display_status)
630                                         lc->vtable.display_status(lc,_("Call failed."));
631                 }
632         }
633
634         if (lc->ringstream!=NULL) {
635                 ring_stop(lc->ringstream);
636                 lc->ringstream=NULL;
637         }
638         linphone_call_stop_media_streams (call);
639         if (call->referer && linphone_call_get_state(call->referer)==LinphoneCallPaused && call->referer->was_automatically_paused){
640                 /*resume to the call that send us the refer automatically*/
641                 linphone_core_resume_call(lc,call->referer);
642         }
643
644 #ifdef BUILD_UPNP
645         linphone_call_delete_upnp_session(call);
646 #endif //BUILD_UPNP
647
648         if (sr == SalReasonDeclined) {
649                 call->reason=LinphoneReasonDeclined;
650                 linphone_call_set_state(call,LinphoneCallEnd,"Call declined.");
651         } else if (sr == SalReasonNotFound) {
652                 call->reason=LinphoneReasonNotFound;
653                 linphone_call_set_state(call,LinphoneCallError,"User not found.");
654         } else if (sr == SalReasonBusy) {
655                 call->reason=LinphoneReasonBusy;
656                 linphone_call_set_state(call,LinphoneCallError,"User is busy.");
657         } else {
658                 linphone_call_set_state(call,LinphoneCallError,msg);
659         }
660 }
661
662 static void call_released(SalOp *op){
663         LinphoneCall *call=(LinphoneCall*)sal_op_get_user_pointer(op);
664         if (call!=NULL){
665                 linphone_call_set_state(call,LinphoneCallReleased,"Call released");
666         }else ms_error("call_released() for already destroyed call ?");
667 }
668
669 static void auth_requested(SalOp *h, const char *realm, const char *username){
670         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(h));
671         LinphoneAuthInfo *ai=(LinphoneAuthInfo*)linphone_core_find_auth_info(lc,realm,username);
672         LinphoneCall *call=is_a_linphone_call(sal_op_get_user_pointer(h));
673
674         if (call && call->ping_op==h){
675                 /*don't request authentication for ping requests. Their purpose is just to get any
676                  * answer to get the Via's received and rport parameters.
677                  */
678                 ms_message("auth_requested(): ignored for ping request.");
679                 return;
680         }
681         
682         ms_message("auth_requested() for realm=%s, username=%s",realm,username);
683
684         if (ai && ai->works==FALSE && ai->usecount>=3){
685                 /*case we tried 3 times to authenticate, without success */
686                 /*Better is to stop (implemeted below in else statement), and retry later*/
687                 if (ms_time(NULL)-ai->last_use_time>30){
688                         ai->usecount=0; /*so that we can allow to retry */
689                 }
690         }
691         
692         if (ai && (ai->works || ai->usecount<3)){
693                 SalAuthInfo sai;
694                 sai.username=ai->username;
695                 sai.userid=ai->userid;
696                 sai.realm=ai->realm;
697                 sai.password=ai->passwd;
698                 ms_message("auth_requested(): authenticating realm=%s, username=%s",realm,username);
699                 sal_op_authenticate(h,&sai);
700                 ai->usecount++;
701                 ai->last_use_time=ms_time(NULL);
702         }else{
703                 if (ai && ai->works==FALSE) {
704                         sal_op_cancel_authentication(h);
705                 } 
706                 if (lc->vtable.auth_info_requested)
707                         lc->vtable.auth_info_requested(lc,realm,username);
708         }
709 }
710
711 static void auth_success(SalOp *h, const char *realm, const char *username){
712         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(h));
713         LinphoneAuthInfo *ai=(LinphoneAuthInfo*)linphone_core_find_auth_info(lc,realm,username);
714         if (ai){
715                 ms_message("%s/%s authentication works.",realm,username);
716                 ai->works=TRUE;
717         }
718 }
719
720 static void register_success(SalOp *op, bool_t registered){
721         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(op));
722         LinphoneProxyConfig *cfg=(LinphoneProxyConfig*)sal_op_get_user_pointer(op);
723         char *msg;
724         
725         if (cfg->deletion_date!=0){
726                 ms_message("Registration success for removed proxy config, ignored");
727                 return;
728         }
729         linphone_proxy_config_set_error(cfg,LinphoneReasonNone);
730         linphone_proxy_config_set_state(cfg, registered ? LinphoneRegistrationOk : LinphoneRegistrationCleared ,
731                                         registered ? "Registration sucessful" : "Unregistration done");
732         if (lc->vtable.display_status){
733                 if (registered) msg=ms_strdup_printf(_("Registration on %s successful."),sal_op_get_proxy(op));
734                 else msg=ms_strdup_printf(_("Unregistration on %s done."),sal_op_get_proxy(op));
735                 lc->vtable.display_status(lc,msg);
736                 ms_free(msg);
737         }
738         
739 }
740
741 static void register_failure(SalOp *op, SalError error, SalReason reason, const char *details){
742         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(op));
743         LinphoneProxyConfig *cfg=(LinphoneProxyConfig*)sal_op_get_user_pointer(op);
744
745         if (cfg==NULL){
746                 ms_warning("Registration failed for unknown proxy config.");
747                 return ;
748         }
749         if (cfg->deletion_date!=0){
750                 ms_message("Registration failed for removed proxy config, ignored");
751                 return;
752         }
753         if (details==NULL)
754                 details=_("no response timeout");
755         
756         if (lc->vtable.display_status) {
757                 char *msg=ortp_strdup_printf(_("Registration on %s failed: %s"),sal_op_get_proxy(op),details  );
758                 lc->vtable.display_status(lc,msg);
759                 ms_free(msg);
760         }
761         if (error== SalErrorFailure && reason == SalReasonForbidden) {
762                 linphone_proxy_config_set_error(cfg, LinphoneReasonBadCredentials);
763         } else if (error == SalErrorNoResponse) {
764                 linphone_proxy_config_set_error(cfg, LinphoneReasonNoResponse);
765         }
766         linphone_proxy_config_set_state(cfg,LinphoneRegistrationFailed,details);
767         if (error== SalErrorFailure && reason == SalReasonForbidden) {
768                 const char *realm=NULL,*username=NULL;
769                 if (sal_op_get_auth_requested(op,&realm,&username)==0){
770                         if (lc->vtable.auth_info_requested)
771                                 lc->vtable.auth_info_requested(lc,realm,username);
772                 }
773         }
774 }
775
776 static void vfu_request(SalOp *op){
777 #ifdef VIDEO_ENABLED
778         LinphoneCall *call=(LinphoneCall*)sal_op_get_user_pointer (op);
779         if (call==NULL){
780                 ms_warning("VFU request but no call !");
781                 return ;
782         }
783         if (call->videostream)
784                 video_stream_send_vfu(call->videostream);
785 #endif
786 }
787
788 static void dtmf_received(SalOp *op, char dtmf){
789         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(op));
790         LinphoneCall *call=(LinphoneCall*)sal_op_get_user_pointer(op);
791         if (lc->vtable.dtmf_received != NULL)
792                 lc->vtable.dtmf_received(lc, call, dtmf);
793 }
794
795 static void refer_received(Sal *sal, SalOp *op, const char *referto){
796         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal);
797         LinphoneCall *call=(LinphoneCall*)sal_op_get_user_pointer(op);
798         if (call){
799                 if (call->refer_to!=NULL){
800                         ms_free(call->refer_to);
801                 }
802                 call->refer_to=ms_strdup(referto);
803                 call->refer_pending=TRUE;
804                 linphone_call_set_state(call,LinphoneCallRefered,"Refered");
805                 if (lc->vtable.display_status){
806                         char *msg=ms_strdup_printf(_("We are transferred to %s"),referto);
807                         lc->vtable.display_status(lc,msg);
808                         ms_free(msg);
809                 }
810                 if (call->state!=LinphoneCallPaused){
811                         ms_message("Automatically pausing current call to accept transfer.");
812                         linphone_core_pause_call(lc,call);
813                         call->was_automatically_paused=TRUE;
814                         /*then we will start the refered when the pause is accepted, in order to serialize transactions within the dialog.
815                          * Indeed we need to avoid to send a NOTIFY to inform about of state of the refered call while the pause isn't completed.
816                         **/
817                 }else linphone_core_start_refered_call(lc,call);
818         }else if (lc->vtable.refer_received){
819                 lc->vtable.refer_received(lc,referto);
820         }
821 }
822
823 static bool_t is_duplicate_msg(LinphoneCore *lc, const char *msg_id){
824         MSList *elem=lc->last_recv_msg_ids;
825         MSList *tail=NULL;
826         int i;
827         bool_t is_duplicate=FALSE;
828         for(i=0;elem!=NULL;elem=elem->next,i++){
829                 if (strcmp((const char*)elem->data,msg_id)==0){
830                         is_duplicate=TRUE;
831                 }
832                 tail=elem;
833         }
834         if (!is_duplicate){
835                 lc->last_recv_msg_ids=ms_list_prepend(lc->last_recv_msg_ids,ms_strdup(msg_id));
836         }
837         if (i>=10){
838                 ms_free(tail->data);
839                 lc->last_recv_msg_ids=ms_list_remove_link(lc->last_recv_msg_ids,tail);
840         }
841         return is_duplicate;
842 }
843
844
845 static void text_received(SalOp *op, const SalMessage *msg){
846         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(op));
847         if (is_duplicate_msg(lc,msg->message_id)==FALSE){
848                 linphone_core_message_received(lc,op,msg);
849         }
850 }
851
852 static void notify(SalOp *op, const char *from, const char *msg){
853         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(op));
854         LinphoneCall *call=(LinphoneCall*)sal_op_get_user_pointer (op);
855         ms_message("get a %s notify from %s",msg,from);
856         if(lc->vtable.notify_recv)
857                 lc->vtable.notify_recv(lc,call,from,msg);
858 }
859
860 static void notify_presence(SalOp *op, SalSubscribeStatus ss, SalPresenceStatus status, const char *msg){
861         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(op));
862         linphone_notify_recv(lc,op,ss,status);
863 }
864
865 static void subscribe_received(SalOp *op, const char *from){
866         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(op));
867         linphone_subscription_new(lc,op,from);
868 }
869
870 static void subscribe_closed(SalOp *op, const char *from){
871         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(op));
872         linphone_subscription_closed(lc,op);
873 }
874
875 static void ping_reply(SalOp *op){
876         LinphoneCall *call=(LinphoneCall*) sal_op_get_user_pointer(op);
877         ms_message("ping reply !");
878         if (call){
879                 if (call->state==LinphoneCallOutgoingInit){
880                         call->ping_replied=TRUE;
881                         linphone_core_proceed_with_invite_if_ready(call->core,call,NULL);
882                 }
883         }
884         else
885         {
886                 ms_warning("ping reply without call attached...");
887         }
888 }
889
890 static void notify_refer(SalOp *op, SalReferStatus status){
891         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(op));
892         LinphoneCall *call=(LinphoneCall*) sal_op_get_user_pointer(op);
893         LinphoneCallState cstate;
894         if (call==NULL) {
895                 ms_warning("Receiving notify_refer for unknown call.");
896                 return ;
897         }
898         switch(status){
899                 case SalReferTrying:
900                         cstate=LinphoneCallOutgoingProgress;
901                 break;
902                 case SalReferSuccess:
903                         cstate=LinphoneCallConnected;
904                 break;
905                 case SalReferFailed:
906                         cstate=LinphoneCallError;
907                 break;
908                 default:
909                         cstate=LinphoneCallError;
910         }
911         linphone_call_set_transfer_state(call, cstate);
912         if (cstate==LinphoneCallConnected){
913                 /*automatically terminate the call as the transfer is complete.*/
914                 linphone_core_terminate_call(lc,call);
915         }
916 }
917
918 static LinphoneChatMessageState chatStatusSal2Linphone(SalTextDeliveryStatus status){
919         switch(status){
920                 case SalTextDeliveryInProgress:
921                         return LinphoneChatMessageStateInProgress;
922                 case SalTextDeliveryDone:
923                         return LinphoneChatMessageStateDelivered;
924                 case SalTextDeliveryFailed:
925                         return LinphoneChatMessageStateNotDelivered;
926         }
927         return LinphoneChatMessageStateIdle;
928 }
929
930 static int op_equals(LinphoneCall *a, SalOp *b) {
931         return a->op !=b; /*return 0 if equals*/
932 }
933 static void text_delivery_update(SalOp *op, SalTextDeliveryStatus status){
934         LinphoneChatMessage *chat_msg=(LinphoneChatMessage* )sal_op_get_user_pointer(op);
935         const MSList* calls = linphone_core_get_calls(chat_msg->chat_room->lc);
936         
937         linphone_core_set_message_state(chat_msg->chat_room,chat_msg->message,chatStatusSal2Linphone(status),chat_msg->time);   
938         if (chat_msg && chat_msg->cb) {
939                 chat_msg->cb(chat_msg
940                         ,chatStatusSal2Linphone(status)
941                         ,chat_msg->cb_ud);
942         }
943         linphone_chat_message_destroy(chat_msg);
944         
945         if (!ms_list_find_custom((MSList*)calls, (MSCompareFunc) op_equals, op)) {
946                 /*op was only create for messaging purpose, destroying*/
947                 sal_op_release(op);
948         }
949 }
950
951 SalCallbacks linphone_sal_callbacks={
952         call_received,
953         call_ringing,
954         call_accepted,
955         call_ack,
956         call_updating,
957         call_terminated,
958         call_failure,
959         call_released,
960         auth_requested,
961         auth_success,
962         register_success,
963         register_failure,
964         vfu_request,
965         dtmf_received,
966         refer_received,
967         text_received,
968         text_delivery_update,
969         notify,
970         notify_presence,
971         notify_refer,
972         subscribe_received,
973         subscribe_closed,
974         ping_reply,
975 };
976
977