]> sjero.net Git - linphone/blob - console/linphonec.c
refer improvements, and caught refers
[linphone] / console / linphonec.c
1 /****************************************************************************
2  *
3  *  $Id: linphonec.c,v 1.57 2007/11/14 13:40:27 smorlat Exp $
4  *
5  *  Copyright (C) 2006  Sandro Santilli <strk@keybit.net>
6  *  Copyright (C) 2002  Florian Winterstein <flox@gmx.net>
7  *  Copyright (C) 2000  Simon MORLAT <simon.morlat@free.fr>
8  *
9 ****************************************************************************
10  *
11  * This program is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU General Public License
13  * as published by the Free Software Foundation; either version 2
14  * of the License, or (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
24  *
25  ****************************************************************************/
26 #include <string.h>
27 #ifndef _WIN32_WCE
28 #include <sys/time.h>
29 #include <sys/types.h>
30 #include <unistd.h>
31 #include <errno.h>
32 #include <signal.h>
33 #include "private.h" /*coreapi/private.h, needed for LINPHONE_VERSION */
34 #endif /*_WIN32_WCE*/
35 #include <limits.h>
36 #include <ctype.h>
37
38 #include <linphonecore.h>
39
40 #include "linphonec.h"
41
42 #ifdef WIN32
43 #include <ws2tcpip.h>
44 #include <ctype.h>
45 #ifndef _WIN32_WCE
46 #include <conio.h>
47 #endif /*_WIN32_WCE*/
48 #else
49 #include <sys/socket.h>
50 #include <netdb.h>
51 #include <sys/un.h>
52 #include <sys/stat.h>
53 #endif
54
55 #if defined(_WIN32_WCE)
56
57 #if !defined(PATH_MAX)
58 #define PATH_MAX 256
59 #endif /*PATH_MAX*/
60
61 #if !defined(strdup)
62 #define strdup _strdup
63 #endif /*strdup*/
64
65 #endif /*_WIN32_WCE*/
66
67 #ifdef HAVE_GETTEXT
68 #include <libintl.h>
69 #ifndef _
70 #define _(String) gettext(String)
71 #endif
72 #else
73 #define _(something)    (something)
74 #endif
75
76 #ifndef PACKAGE_DIR
77 #define PACKAGE_DIR ""
78 #endif
79
80 /***************************************************************************
81  *
82  *  Types
83  *
84  ***************************************************************************/
85
86 typedef struct {
87         LinphoneAuthInfo *elem[MAX_PENDING_AUTH];
88         int nitems;
89 } LPC_AUTH_STACK;
90
91 /***************************************************************************
92  *
93  *  Forward declarations
94  *
95  ***************************************************************************/
96
97 char *lpc_strip_blanks(char *input);
98
99 static int handle_configfile_migration(void);
100 #if !defined(_WIN32_WCE)
101 static int copy_file(const char *from, const char *to);
102 #endif /*_WIN32_WCE*/
103 static int linphonec_parse_cmdline(int argc, char **argv);
104 static int linphonec_init(int argc, char **argv);
105 static int linphonec_main_loop (LinphoneCore * opm, char * sipAddr);
106 static int linphonec_idle_call (void);
107 #ifdef HAVE_READLINE
108 static int linphonec_initialize_readline(void);
109 static int linphonec_finish_readline();
110 static char **linephonec_readline_completion(const char *text,
111         int start, int end);
112 #endif
113
114 /* These are callback for linphone core */
115 static void linphonec_call_received(LinphoneCore *lc, const char *from);
116 static void linphonec_prompt_for_auth(LinphoneCore *lc, const char *realm,
117         const char *username);
118 static void linphonec_display_refer (LinphoneCore * lc,const char *refer_to);
119 static void linphonec_display_something (LinphoneCore * lc, const char *something);
120 static void linphonec_display_url (LinphoneCore * lc, const char *something, const char *url);
121 static void linphonec_display_warning (LinphoneCore * lc, const char *something);
122 static void stub () {}
123 static void linphonec_notify_received(LinphoneCore *lc,const char *from,const char *msg);
124 static void linphonec_notify_presence_received(LinphoneCore *lc,LinphoneFriend *fid);
125 static void linphonec_new_unknown_subscriber(LinphoneCore *lc,
126                 LinphoneFriend *lf, const char *url);
127 static void linphonec_bye_received(LinphoneCore *lc, const char *from);
128 static void linphonec_text_received(LinphoneCore *lc, LinphoneChatRoom *cr,
129                 const char *from, const char *msg);
130 static void linphonec_display_status (LinphoneCore * lc, const char *something);
131 static void linphonec_general_state (LinphoneCore * lc, LinphoneGeneralState *gstate);
132 static void linphonec_dtmf_received(LinphoneCore *lc, int dtmf);
133 static void print_prompt(LinphoneCore *opm);
134 /***************************************************************************
135  *
136  * Global variables
137  *
138  ***************************************************************************/
139
140 LinphoneCore *linphonec;
141 FILE *mylogfile;
142 #ifdef HAVE_READLINE
143 static char *histfile_name=NULL;
144 static char last_in_history[256];
145 #endif
146 //auto answer (-a) option
147 static bool_t auto_answer=FALSE;
148 static bool_t answer_call=FALSE;
149 static bool_t vcap_enabled=FALSE;
150 static bool_t display_enabled=FALSE;
151 static bool_t preview_enabled=FALSE;
152 static bool_t show_general_state=FALSE;
153 static bool_t unix_socket=FALSE;
154 static bool_t linphonec_running=TRUE;
155 LPC_AUTH_STACK auth_stack;
156 static int trace_level = 0;
157 static char *logfile_name = NULL;
158 static char configfile_name[PATH_MAX];
159 static char *sipAddr = NULL; /* for autocall */
160 #if !defined(_WIN32_WCE)
161 static ortp_pipe_t client_sock=ORTP_PIPE_INVALID;
162 #endif /*_WIN32_WCE*/
163 char prompt[PROMPT_MAX_LEN];
164 #if !defined(_WIN32_WCE)
165 static ortp_thread_t pipe_reader_th;
166 static bool_t pipe_reader_run=FALSE;
167 #endif /*_WIN32_WCE*/
168 #if !defined(_WIN32_WCE)
169 static ortp_pipe_t server_sock;
170 #endif /*_WIN32_WCE*/
171
172
173 LinphoneCoreVTable linphonec_vtable
174 #if !defined (_MSC_VER)
175 = {
176         .show =(ShowInterfaceCb) stub,
177         .inv_recv = linphonec_call_received,
178         .bye_recv = linphonec_bye_received,
179         .notify_recv = linphonec_notify_received,
180         .notify_presence_recv = linphonec_notify_presence_received,
181         .new_unknown_subscriber = linphonec_new_unknown_subscriber,
182         .auth_info_requested = linphonec_prompt_for_auth,
183         .display_status = linphonec_display_status,
184         .display_message=linphonec_display_something,
185 #ifdef VINCENT_MAURY_RSVP
186         /* the yes/no dialog box */
187         .display_yes_no= (DisplayMessageCb) stub,
188 #endif
189         .display_warning=linphonec_display_warning,
190         .display_url=linphonec_display_url,
191         .display_question=(DisplayQuestionCb)stub,
192         .text_received=linphonec_text_received,
193         .general_state=linphonec_general_state,
194         .dtmf_received=linphonec_dtmf_received,
195         .refer_received=linphonec_display_refer
196 }
197 #endif /*_WIN32_WCE*/
198 ;
199
200
201
202 /***************************************************************************
203  *
204  * Linphone core callbacks
205  *
206  ***************************************************************************/
207
208 /*
209  * Linphone core callback
210  */
211 static void
212 linphonec_display_refer (LinphoneCore * lc,const char *refer_to)
213 {
214         fprintf (stdout, "The distant end point asked to transfer the call to %s,don't forget to terminate the call if not\n%s", refer_to,prompt);
215         fflush(stdout);
216 }
217
218 /*
219  * Linphone core callback
220  */
221 static void
222 linphonec_display_something (LinphoneCore * lc, const char *something)
223 {
224         fprintf (stdout, "%s\n%s", something,prompt);
225         fflush(stdout);
226 }
227
228 /*
229  * Linphone core callback
230  */
231 static void
232 linphonec_display_status (LinphoneCore * lc, const char *something)
233 {
234         fprintf (stdout, "%s\n%s", something,prompt);
235         fflush(stdout);
236 }
237
238 /*
239  * Linphone core callback
240  */
241 static void
242 linphonec_display_warning (LinphoneCore * lc, const char *something)
243 {
244         fprintf (stdout, "Warning: %s\n%s", something,prompt);
245         fflush(stdout);
246 }
247
248 /*
249  * Linphone core callback
250  */
251 static void
252 linphonec_display_url (LinphoneCore * lc, const char *something, const char *url)
253 {
254         fprintf (stdout, "%s : %s\n", something, url);
255 }
256
257
258 /*
259  * Linphone core callback
260  */
261 static void
262 linphonec_call_received(LinphoneCore *lc, const char *from)
263 {
264         linphonec_set_caller(from);
265         if ( auto_answer)  {
266                 answer_call=TRUE;
267         }
268 }
269
270 /*
271  * Linphone core callback
272  */
273 static void
274 linphonec_prompt_for_auth(LinphoneCore *lc, const char *realm, const char *username)
275 {
276         /* no prompt possible when using pipes or tcp mode*/
277         if (unix_socket){
278                 linphone_core_abort_authentication(lc,NULL);
279         }else{
280                 LinphoneAuthInfo *pending_auth;
281
282                 if ( auth_stack.nitems+1 > MAX_PENDING_AUTH )
283                 {
284                         fprintf(stderr,
285                                 "Can't accept another authentication request.\n"
286                                 "Consider incrementing MAX_PENDING_AUTH macro.\n");
287                         return;
288                 }
289
290                 pending_auth=linphone_auth_info_new(username,NULL,NULL,NULL,realm);
291                 auth_stack.elem[auth_stack.nitems++]=pending_auth;
292         }
293 }
294
295 /*
296  * Linphone core callback
297  */
298 static void
299 linphonec_notify_received(LinphoneCore *lc,const char *from,const char *msg)
300 {
301         printf("Notify type %s from %s\n", msg, from);
302         if(!strcmp(msg,"refer"))
303         {
304                 printf("The distant SIP end point get the refer we can close the call\n");
305                 linphonec_parse_command_line(linphonec, "terminate");
306         }
307 }
308
309 /*
310  * Linphone core callback
311  */
312 static void
313 linphonec_notify_presence_received(LinphoneCore *lc,LinphoneFriend *fid)
314 {
315         char *tmp=linphone_address_as_string(linphone_friend_get_address(fid));
316         printf("Friend %s is %s\n", tmp, linphone_online_status_to_string(linphone_friend_get_status(fid)));
317         ms_free(tmp);
318         // todo: update Friend list state (unimplemented)
319 }
320
321 /*
322  * Linphone core callback
323  */
324 static void
325 linphonec_new_unknown_subscriber(LinphoneCore *lc, LinphoneFriend *lf,
326                 const char *url)
327 {
328         printf("Friend %s requested subscription "
329                 "(accept/deny is not implemented yet)\n", url);
330         // This means that this person wishes to be notified
331         // of your presence information (online, busy, away...).
332
333 }
334
335 /*
336  * Linphone core callback
337  */
338 static void
339 linphonec_bye_received(LinphoneCore *lc, const char *from)
340 {
341         // Should change prompt back to original maybe
342
343         // printing this is unneeded as we'd get a "Communication ended"
344         // message trough display_status callback anyway
345         //printf("Bye received from %s\n", from);
346 }
347
348 /*
349  * Linphone core callback
350  */
351 static void
352 linphonec_text_received(LinphoneCore *lc, LinphoneChatRoom *cr,
353                 const char *from, const char *msg)
354 {
355         printf("%s: %s\n", from, msg);
356         // TODO: provide mechanism for answering.. ('say' command?)
357 }
358
359
360 static void linphonec_dtmf_received(LinphoneCore *lc, int dtmf){
361         fprintf(stdout,"Receiving tone %c\n",dtmf);
362         fflush(stdout);
363 }
364
365 static void
366 linphonec_general_state (LinphoneCore * lc, LinphoneGeneralState *gstate)
367 {
368         if (show_general_state) {
369           switch(gstate->new_state) {
370            case GSTATE_POWER_OFF:
371              printf("GSTATE_POWER_OFF");
372              break;
373            case GSTATE_POWER_STARTUP:
374              printf("GSTATE_POWER_STARTUP");
375              break;
376            case GSTATE_POWER_ON:
377              printf("GSTATE_POWER_ON");
378              break;
379            case GSTATE_POWER_SHUTDOWN:
380              printf("GSTATE_POWER_SHUTDOWN");
381              break;
382            case GSTATE_REG_NONE:
383              printf("GSTATE_REG_NONE");
384              break;
385            case GSTATE_REG_OK:
386              printf("GSTATE_REG_OK");
387              break;
388            case GSTATE_REG_FAILED:
389              printf("GSTATE_REG_FAILED");
390              break;
391            case GSTATE_CALL_IDLE:
392              printf("GSTATE_CALL_IDLE");
393              break;
394            case GSTATE_CALL_OUT_INVITE:
395              printf("GSTATE_CALL_OUT_INVITE");
396              break;
397            case GSTATE_CALL_OUT_CONNECTED:
398              printf("GSTATE_CALL_OUT_CONNECTED");
399              break;
400            case GSTATE_CALL_IN_INVITE:
401              printf("GSTATE_CALL_IN_INVITE");
402              break;
403            case GSTATE_CALL_IN_CONNECTED:
404              printf("GSTATE_CALL_IN_CONNECTED");
405              break;
406            case GSTATE_CALL_END:
407              printf("GSTATE_CALL_END");
408              break;
409            case GSTATE_CALL_ERROR:
410              printf("GSTATE_CALL_ERROR");
411              break;
412            default:
413               printf("GSTATE_UNKNOWN_%d",gstate->new_state);
414           }
415           if (gstate->message) printf(" %s", gstate->message);
416           printf("\n");
417         }
418 }
419
420 static char received_prompt[PROMPT_MAX_LEN];
421 static ms_mutex_t prompt_mutex;
422 static bool_t have_prompt=FALSE;
423
424 static void *prompt_reader_thread(void *arg){
425         char *ret;
426         char tmp[PROMPT_MAX_LEN];
427         while ((ret=fgets(tmp,sizeof(tmp),stdin))!=NULL){
428                 ms_mutex_lock(&prompt_mutex);
429                 strcpy(received_prompt,ret);
430                 have_prompt=TRUE;
431                 ms_mutex_unlock(&prompt_mutex);
432         }
433         return NULL;
434 }
435
436 static void start_prompt_reader(void){
437         ortp_thread_t th;
438         ms_mutex_init(&prompt_mutex,NULL);
439         ortp_thread_create(&th,NULL,prompt_reader_thread,NULL);
440 }
441 #if !defined(_WIN32_WCE)
442 static ortp_pipe_t create_server_socket(void){
443         char path[128];
444 #ifndef WIN32
445         snprintf(path,sizeof(path)-1,"linphonec-%i",getuid());
446 #else
447         {
448                 TCHAR username[128];
449                 DWORD size=sizeof(username)-1;
450                 GetUserName(username,&size);
451                 snprintf(path,sizeof(path)-1,"linphonec-%s",username);
452         }
453 #endif
454         return ortp_server_pipe_create(path);
455 }
456
457
458 static void *pipe_thread(void*p){
459         char tmp[250];
460         server_sock=create_server_socket();
461         if (server_sock==ORTP_PIPE_INVALID) return NULL;
462         while(pipe_reader_run){
463                 while(client_sock!=ORTP_PIPE_INVALID){ /*sleep until the last command is finished*/
464 #ifndef WIN32
465                         usleep(20000);
466 #else
467                         Sleep(20);
468 #endif
469                 }
470                 client_sock=ortp_server_pipe_accept_client(server_sock);
471                 if (client_sock!=ORTP_PIPE_INVALID){
472                         int len;
473                         /*now read from the client */
474                         if ((len=ortp_pipe_read(client_sock,(uint8_t*)tmp,sizeof(tmp)-1))>0){
475                                 ortp_mutex_lock(&prompt_mutex);
476                                 tmp[len]='\0';
477                                 strcpy(received_prompt,tmp);
478                                 printf("Receiving command '%s'\n",received_prompt);fflush(stdout);
479                                 have_prompt=TRUE;
480                                 ortp_mutex_unlock(&prompt_mutex);
481                         }else{
482                                 printf("read nothing\n");fflush(stdout);
483                                 ortp_server_pipe_close_client(client_sock);
484                                 client_sock=ORTP_PIPE_INVALID;
485                         }
486
487                 }else{
488                         if (pipe_reader_run) fprintf(stderr,"accept() failed: %s\n",strerror(errno));
489                 }
490         }
491         ms_message("Exiting pipe_reader_thread.");
492         fflush(stdout);
493         return NULL;
494 }
495
496 static void start_pipe_reader(void){
497         ms_mutex_init(&prompt_mutex,NULL);
498         pipe_reader_run=TRUE;
499         ortp_thread_create(&pipe_reader_th,NULL,pipe_thread,NULL);
500 }
501
502 static void stop_pipe_reader(void){
503         pipe_reader_run=FALSE;
504         linphonec_command_finished();
505         ortp_server_pipe_close(server_sock);
506         ortp_thread_join(pipe_reader_th,NULL);
507 }
508 #endif /*_WIN32_WCE*/
509
510 #ifdef HAVE_READLINE
511 #define BOOL_HAVE_READLINE 1
512 #else
513 #define BOOL_HAVE_READLINE 0
514 #endif
515
516 char *linphonec_readline(char *prompt){
517         if (unix_socket || !BOOL_HAVE_READLINE ){
518                 static bool_t prompt_reader_started=FALSE;
519                 static bool_t pipe_reader_started=FALSE;
520                 if (!prompt_reader_started){
521                         start_prompt_reader();
522                         prompt_reader_started=TRUE;
523                 }
524                 if (unix_socket && !pipe_reader_started){
525 #if !defined(_WIN32_WCE)
526                         start_pipe_reader();
527                         pipe_reader_started=TRUE;
528 #endif /*_WIN32_WCE*/
529                 }
530                 fprintf(stdout,"%s",prompt);
531                 fflush(stdout);
532                 while(1){
533                         ms_mutex_lock(&prompt_mutex);
534                         if (have_prompt){
535                                 char *ret=strdup(received_prompt);
536                                 have_prompt=FALSE;
537                                 ms_mutex_unlock(&prompt_mutex);
538                                 return ret;
539                         }
540                         ms_mutex_unlock(&prompt_mutex);
541                         linphonec_idle_call();
542 #ifdef WIN32
543                         Sleep(20);
544                         /* Following is to get the video window going as it
545                                  should. Maybe should we only have this on when the option -V
546                                  or -D is on? */
547                         MSG msg;
548         
549                         if (PeekMessage(&msg, NULL, 0, 0,1)) {
550                                 TranslateMessage(&msg);
551                                 DispatchMessage(&msg);
552                         }
553 #else
554                         usleep(20000);
555 #endif
556                 }
557         }else{
558 #ifdef HAVE_READLINE
559                 return readline(prompt);
560 #endif
561         }
562 }
563
564 void linphonec_out(const char *fmt,...){
565         char *res;
566         va_list args;
567         va_start (args, fmt);
568         res=ortp_strdup_vprintf(fmt,args);
569         va_end (args);
570         printf("%s",res);
571         fflush(stdout);
572 #if !defined(_WIN32_WCE)
573         if (client_sock!=ORTP_PIPE_INVALID){
574                 if (ortp_pipe_write(client_sock,(uint8_t*)res,strlen(res))==-1){
575                         fprintf(stderr,"Fail to send output via pipe: %s",strerror(errno));
576                 }
577         }
578 #endif /*_WIN32_WCE*/
579         ortp_free(res);
580 }
581
582 void linphonec_command_finished(void){
583 #if !defined(_WIN32_WCE)
584         if (client_sock!=ORTP_PIPE_INVALID){
585                 ortp_server_pipe_close_client(client_sock);
586                 client_sock=ORTP_PIPE_INVALID;
587         }
588 #endif /*_WIN32_WCE*/
589 }
590
591 void linphonec_set_autoanswer(bool_t enabled){
592         auto_answer=enabled;
593 }
594
595 bool_t linphonec_get_autoanswer(){
596         return auto_answer;
597 }
598
599 /***************************************************************************/
600 /*
601  * Main
602  *
603  * Use globals:
604  *
605  *      - char *histfile_name
606  *      - FILE *mylogfile
607  */
608 #if defined (_WIN32_WCE)
609
610 char **convert_args_to_ascii(int argc, _TCHAR **wargv){
611         int i;
612         char **result=malloc(argc*sizeof(char*));
613         char argtmp[128];
614         for(i=0;i<argc;++i){
615                 wcstombs(argtmp,wargv[i],sizeof(argtmp));
616                 result[i]=strdup(argtmp);
617         }
618         return result;
619 }
620
621 int _tmain(int argc, _TCHAR* wargv[]) {
622         char **argv=convert_args_to_ascii(argc,wargv);
623         trace_level=6;
624         linphonec_vtable.show =(ShowInterfaceCb) stub;
625         linphonec_vtable.inv_recv = linphonec_call_received;
626         linphonec_vtable.bye_recv = linphonec_bye_received;
627         linphonec_vtable.notify_presence_recv = linphonec_notify_received;
628         linphonec_vtable.new_unknown_subscriber = linphonec_new_unknown_subscriber;
629         linphonec_vtable.auth_info_requested = linphonec_prompt_for_auth;
630         linphonec_vtable.display_status = linphonec_display_status;
631         linphonec_vtable.display_message=linphonec_display_something;
632 #ifdef VINCENT_MAURY_RSVP
633         /* the yes/no dialog box */
634         linphonec_vtable.display_yes_no= (DisplayMessageCb) stub;
635 #endif
636         linphonec_vtable.display_warning=linphonec_display_warning;
637         linphonec_vtable.display_url=linphonec_display_url;
638         linphonec_vtable.display_question=(DisplayQuestionCb)stub;
639         linphonec_vtable.text_received=linphonec_text_received;
640         linphonec_vtable.general_state=linphonec_general_state;
641         linphonec_vtable.dtmf_received=linphonec_dtmf_received;
642
643 #else
644 int
645 main (int argc, char *argv[]) {
646 #endif
647
648
649         if (! linphonec_init(argc, argv) ) exit(EXIT_FAILURE);
650
651         linphonec_main_loop (linphonec, sipAddr);
652
653         linphonec_finish(EXIT_SUCCESS);
654
655         exit(EXIT_SUCCESS); /* should never reach here */
656 }
657
658 /*
659  * Initialize linphonec
660  */
661 static int
662 linphonec_init(int argc, char **argv)
663 {
664
665         //g_mem_set_vtable(&dbgtable);
666
667         /*
668          * Set initial values for global variables
669          */
670         mylogfile = NULL;
671         
672         
673 #ifndef _WIN32
674         snprintf(configfile_name, PATH_MAX, "%s/.linphonerc",
675                         getenv("HOME"));
676 #elif defined(_WIN32_WCE)
677         strncpy(configfile_name,PACKAGE_DIR "\\linphonerc",PATH_MAX);
678         mylogfile=fopen(PACKAGE_DIR "\\" "linphonec.log","w");
679         printf("Logs are redirected in" PACKAGE_DIR "\\linphonec.log");
680 #else
681         snprintf(configfile_name, PATH_MAX, "%s/Linphone/linphonerc",
682                         getenv("APPDATA"));
683 #endif
684         /* Handle configuration filename changes */
685         switch (handle_configfile_migration())
686         {
687                 case -1: /* error during file copies */
688                         fprintf(stderr,
689                                 "Error in configuration file migration\n");
690                         break;
691
692                 case 0: /* nothing done */
693                 case 1: /* migrated */
694                 default:
695                         break;
696         }
697
698 #ifdef ENABLE_NLS
699         if (NULL == bindtextdomain (GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR))
700                 perror ("bindtextdomain failed");
701 #ifndef __ARM__
702         bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
703 #endif
704         textdomain (GETTEXT_PACKAGE);
705 #else
706         printf ("NLS disabled.\n");
707 #endif
708
709         linphonec_parse_cmdline(argc, argv);
710
711         if (trace_level > 0)
712         {
713                 if (logfile_name != NULL)
714                         mylogfile = fopen (logfile_name, "w+");
715
716                 if (mylogfile == NULL)
717                 {
718                         mylogfile = stdout;
719                         fprintf (stderr,
720                                  "INFO: no logfile, logging to stdout\n");
721                 }
722                 linphone_core_enable_logs(mylogfile);
723         }
724         else
725         {
726                 linphone_core_disable_logs();
727         }
728         /*
729          * Initialize auth stack
730          */
731         auth_stack.nitems=0;
732
733         /*
734          * Initialize linphone core
735          */
736         linphonec=linphone_core_new (&linphonec_vtable, configfile_name, NULL,
737                             NULL);
738         linphone_core_enable_video(linphonec,vcap_enabled,display_enabled);
739         linphone_core_enable_video_preview(linphonec,preview_enabled);
740         if (!(vcap_enabled || display_enabled)) printf("Warning: video is disabled in linphonec, use -V or -C or -D to enable.\n");
741 #ifdef HAVE_READLINE
742         /*
743          * Initialize readline
744          */
745         linphonec_initialize_readline();
746 #endif
747 #if !defined(_WIN32_WCE)
748         /*
749          * Initialize signal handlers
750          */
751         signal(SIGTERM, linphonec_finish);
752         signal(SIGINT, linphonec_finish);
753 #endif /*_WIN32_WCE*/
754         return 1;
755 }
756
757
758 void linphonec_main_loop_exit(void){
759         linphonec_running=FALSE;
760 }
761
762 /*
763  * Close linphonec, cleanly terminating
764  * any pending call
765  */
766 void
767 linphonec_finish(int exit_status)
768 {
769         printf("Terminating...\n");
770
771         /* Terminate any pending call */
772         linphonec_parse_command_line(linphonec, "terminate");
773         linphonec_command_finished();
774 #ifdef HAVE_READLINE
775         linphonec_finish_readline();
776 #endif
777 #if !defined(_WIN32_WCE)
778         if (pipe_reader_run)
779                 stop_pipe_reader();
780 #endif /*_WIN32_WCE*/
781
782         linphone_core_destroy (linphonec);
783
784         if (mylogfile != NULL && mylogfile != stdout)
785         {
786                 fclose (mylogfile);
787         }
788
789         exit(exit_status);
790
791 }
792
793 /*
794  * This is called from idle_call() whenever
795  * pending_auth != NULL.
796  *
797  * It prompts user for a password.
798  * Hitting ^D (EOF) would make this function
799  * return 0 (Cancel).
800  * Any other input would try to set linphone core
801  * auth_password for the pending_auth, add the auth_info
802  * and return 1.
803  */
804 int
805 linphonec_prompt_for_auth_final(LinphoneCore *lc)
806 {
807         char *input, *iptr;
808         char auth_prompt[256];
809 #ifdef HAVE_READLINE
810         rl_hook_func_t *old_event_hook;
811 #endif
812         LinphoneAuthInfo *pending_auth=auth_stack.elem[auth_stack.nitems-1];
813
814         snprintf(auth_prompt, 256, "Password for %s on %s: ",
815                 pending_auth->username, pending_auth->realm);
816
817         printf("\n");
818 #ifdef HAVE_READLINE
819         /*
820          * Disable event hook to avoid entering an
821          * infinite loop. This would prevent idle_call
822          * from being called during authentication reads.
823          * Note that it might be undesiderable...
824          */
825         old_event_hook=rl_event_hook;
826         rl_event_hook=NULL;
827 #endif
828
829         while (1)
830         {
831                 input=linphonec_readline(auth_prompt);
832
833                 /*
834                  * If EOF (^D) is sent you probably don't want
835                  * to provide an auth password... should give up
836                  * the operation, but there's no mechanism to
837                  * send this info back to caller currently...
838                  */
839                 if ( ! input )
840                 {
841                         printf("Cancel requested, but not implemented.\n");
842                         continue;
843                 }
844
845                 /* Strip blanks */
846                 iptr=lpc_strip_blanks(input);
847
848                 /*
849                  * Only blanks, continue asking
850                  */
851                 if ( ! *iptr )
852                 {
853                         free(input);
854                         continue;
855                 }
856
857                 /* Something typed, let's try */
858                 break;
859         }
860
861         /*
862          * No check is done here to ensure password is correct.
863          * I guess password will be asked again later.
864          */
865         linphone_auth_info_set_passwd(pending_auth, input);
866         linphone_core_add_auth_info(lc, pending_auth);
867         linphone_auth_info_destroy(pending_auth);
868         auth_stack.elem[auth_stack.nitems-1]=0;
869         --(auth_stack.nitems);
870 #ifdef HAVE_READLINE
871         /*
872          * Reset line_buffer, to avoid the password
873          * to be used again from outer readline
874          */
875         rl_line_buffer[0]='\0';
876         rl_event_hook=old_event_hook;
877 #endif
878         return 1;
879 }
880
881 void
882 print_usage (int exit_status)
883 {
884         fprintf (stdout, "\n\
885 usage: linphonec [-c file] [-s sipaddr] [-a] [-V] [-d level ] [-l logfile]\n\
886        linphonec -v\n\
887 \n\
888   -c  file             specify path of configuration file.\n\
889   -d  level            be verbose. 0 is no output. 6 is all output\n\
890   -l  logfile          specify the log file for your SIP phone\n\
891   -s  sipaddress       specify the sip call to do at startup\n\
892   -a                   enable auto answering for incoming calls\n\
893   -V                   enable video features globally (disabled by default)\n\
894   -C                   enable video capture only (disabled by default)\n\
895   -D                   enable video display only (disabled by default)\n\
896   -S                   show general state messages (disabled by default)\n\
897   -v or --version      display version and exits.\n");
898
899         exit(exit_status);
900 }
901
902
903 /*
904  *
905  * Called every second from main read loop.
906  *
907  * Will use the following globals:
908  *
909  *  - LinphoneCore linphonec
910  *  - LPC_AUTH_STACK auth_stack;
911  *
912  */
913 static int
914 linphonec_idle_call ()
915 {
916         LinphoneCore *opm=linphonec;
917
918         /* Uncomment the following to verify being called */
919         /* printf(".\n"); */
920
921         linphone_core_iterate(opm);
922         if (answer_call){
923                 fprintf (stdout, "-------auto answering to call-------\n" );
924                 linphone_core_accept_call(opm,NULL);
925                 answer_call=FALSE;
926         }
927
928         if ( auth_stack.nitems )
929         {
930                 /*
931                  * Inhibit command completion
932                  * during password prompts
933                  */
934 #ifdef HAVE_READLINE
935                 rl_inhibit_completion=1;
936 #endif
937                 linphonec_prompt_for_auth_final(opm);
938 #ifdef HAVE_READLINE
939                 rl_inhibit_completion=0;
940 #endif
941         }
942
943         return 0;
944 }
945
946 #ifdef HAVE_READLINE
947 /*
948  * Use globals:
949  *
950  *      - char *histfile_name (also sets this)
951  *      - char *last_in_history (allocates it)
952  */
953 static int
954 linphonec_initialize_readline()
955 {
956         /*rl_bind_key('\t', rl_insert);*/
957
958         /* Allow conditional parsing of ~/.inputrc */
959         rl_readline_name = "linphonec";
960
961         /* Call idle_call() every second */
962         rl_set_keyboard_input_timeout(LPC_READLINE_TIMEOUT);
963         rl_event_hook=linphonec_idle_call;
964
965         /* Set history file and read it */
966         histfile_name = ms_strdup_printf ("%s/.linphonec_history",
967                 getenv("HOME"));
968         read_history(histfile_name);
969
970         /* Initialized last_in_history cache*/
971         last_in_history[0] = '\0';
972
973         /* Register a completion function */
974         rl_attempted_completion_function = linephonec_readline_completion;
975
976         /* printf("Readline initialized.\n"); */
977         setlinebuf(stdout);
978         return 0;
979 }
980
981 /*
982  * Uses globals:
983  *
984  *      - char *histfile_name (writes history to file and frees it)
985  *      - char *last_in_history (frees it)
986  *
987  */
988 static int
989 linphonec_finish_readline()
990 {
991
992         stifle_history(HISTSIZE);
993         write_history(histfile_name);
994         free(histfile_name);
995         histfile_name=NULL;
996         return 0;
997 }
998
999 #endif
1000
1001 static void print_prompt(LinphoneCore *opm){
1002 #ifdef IDENTITY_AS_PROMPT
1003         snprintf(prompt, PROMPT_MAX_LEN, "%s> ",
1004                 linphone_core_get_primary_contact(opm));
1005 #else
1006         snprintf(prompt, PROMPT_MAX_LEN, "linphonec> ");
1007 #endif
1008 }
1009
1010 static int
1011 linphonec_main_loop (LinphoneCore * opm, char * sipAddr)
1012 {
1013         char buf[LINE_MAX_LEN]; /* auto call handling */
1014         char *input;
1015
1016         print_prompt(opm);
1017
1018
1019         /* auto call handling */
1020         if (sipAddr != NULL )
1021         {
1022                 snprintf (buf, sizeof(buf),"call %s", sipAddr);
1023                 linphonec_parse_command_line(linphonec, buf);
1024         }
1025
1026         while (linphonec_running && (input=linphonec_readline(prompt)))
1027         {
1028                 char *iptr; /* input and input pointer */
1029                 size_t input_len;
1030
1031                 /* Strip blanks */
1032                 iptr=lpc_strip_blanks(input);
1033
1034                 input_len = strlen(iptr);
1035
1036                 /*
1037                  * Do nothing but release memory
1038                  * if only blanks are read
1039                  */
1040                 if ( ! input_len )
1041                 {
1042                         free(input);
1043                         continue;
1044                 }
1045
1046 #ifdef HAVE_READLINE
1047                 /*
1048                  * Only add to history if not already
1049                  * last item in it, and only if the command
1050                  * doesn't start with a space (to allow for
1051                  * hiding passwords)
1052                  */
1053                 if ( iptr == input && strcmp(last_in_history, iptr) )
1054                 {
1055                         strncpy(last_in_history,iptr,sizeof(last_in_history));
1056                         last_in_history[sizeof(last_in_history)-1]='\0';
1057                         add_history(iptr);
1058                 }
1059 #endif
1060
1061                 linphonec_parse_command_line(linphonec, iptr);
1062                 linphonec_command_finished();
1063                 free(input);
1064         }
1065
1066         return 0;
1067 }
1068
1069 /*
1070  *  Parse command line switches
1071  *
1072  *  Use globals:
1073  *
1074  *      - int trace_level
1075  *      - char *logfile_name
1076  *      - char *configfile_name
1077  *      - char *sipAddr
1078  */
1079 static int
1080 linphonec_parse_cmdline(int argc, char **argv)
1081 {
1082         int arg_num=1;
1083
1084         while (arg_num < argc)
1085         {
1086                 int old_arg_num = arg_num;
1087                 if (strncmp ("-d", argv[arg_num], 2) == 0)
1088                 {
1089                         arg_num++;
1090                         if (arg_num < argc)
1091                                 trace_level = atoi (argv[arg_num]);
1092                         else
1093                                 trace_level = 1;
1094                 }
1095                 else if (strncmp ("-l", argv[arg_num], 2) == 0)
1096                 {
1097                         arg_num++;
1098                         if (arg_num < argc)
1099                                 logfile_name = argv[arg_num];
1100                 }
1101                 else if (strncmp ("-c", argv[arg_num], 2) == 0)
1102                 {
1103                         if ( ++arg_num >= argc ) print_usage(EXIT_FAILURE);
1104 #if !defined(_WIN32_WCE)
1105                         if (access(argv[arg_num],F_OK)!=0 )
1106                         {
1107                                 fprintf (stderr,
1108                                         "Cannot open config file %s.\n",
1109                                          argv[arg_num]);
1110                                 exit(EXIT_FAILURE);
1111                         }
1112 #endif /*_WIN32_WCE*/
1113                         snprintf(configfile_name, PATH_MAX, "%s", argv[arg_num]);
1114                 }
1115                 else if (strncmp ("-s", argv[arg_num], 2) == 0)
1116                 {
1117                         arg_num++;
1118                         if (arg_num < argc)
1119                                 sipAddr = argv[arg_num];
1120                 }
1121                 else if (strncmp ("-a", argv[arg_num], 2) == 0)
1122                 {
1123                         auto_answer = TRUE;
1124                 }
1125                 else if (strncmp ("-C", argv[arg_num], 2) == 0)
1126                 {
1127                         vcap_enabled = TRUE;
1128                 }
1129                 else if (strncmp ("-D", argv[arg_num], 2) == 0)
1130                 {
1131                         display_enabled = TRUE;
1132                 }
1133                 else if (strncmp ("-V", argv[arg_num], 2) == 0)
1134                 {
1135                         display_enabled = TRUE;
1136                         vcap_enabled = TRUE;
1137                         preview_enabled=TRUE;
1138                 }
1139                 else if ((strncmp ("-v", argv[arg_num], 2) == 0)
1140                          ||
1141                          (strncmp
1142                           ("--version", argv[arg_num],
1143                            strlen ("--version")) == 0))
1144                 {
1145 #if !defined(_WIN32_WCE)
1146                         printf ("version: " LINPHONE_VERSION "\n");
1147 #endif
1148                         exit (EXIT_SUCCESS);
1149                 }
1150                 else if (strncmp ("-S", argv[arg_num], 2) == 0)
1151                 {
1152                         show_general_state = TRUE;
1153                 }
1154                 else if (strncmp ("--pipe", argv[arg_num], 6) == 0)
1155                 {
1156                         unix_socket=1;
1157                 }
1158                 else if (old_arg_num == arg_num)
1159                 {
1160                         fprintf (stderr, "ERROR: bad arguments\n");
1161                         print_usage (EXIT_FAILURE);
1162                 }
1163                 arg_num++;
1164         }
1165
1166         return 1;
1167 }
1168
1169 /*
1170  * Up to version 1.2.1 linphone used ~/.linphonec for
1171  * CLI and ~/.gnome2/linphone for GUI as configuration file.
1172  * In newer version both interfaces will use ~/.linphonerc.
1173  *
1174  * This function helps transparently migrating from one
1175  * to the other layout using the following heuristic:
1176  *
1177  *      IF new_config EXISTS => do nothing
1178  *      ELSE IF old_cli_config EXISTS => copy to new_config
1179  *      ELSE IF old_gui_config EXISTS => copy to new_config
1180  *
1181  * Returns:
1182  *       0 if it did nothing
1183  *       1 if it migrated successfully
1184  *      -1 on error
1185  */
1186 static int
1187 handle_configfile_migration()
1188 {
1189 #if !defined(_WIN32_WCE)
1190         char *old_cfg_gui;
1191         char *old_cfg_cli;
1192         char *new_cfg;
1193 #if !defined(_WIN32_WCE)
1194         const char *home = getenv("HOME");
1195 #else
1196         const char *home = ".";
1197 #endif /*_WIN32_WCE*/
1198         new_cfg = ms_strdup_printf("%s/.linphonerc", home);
1199
1200         /*
1201          * If the *NEW* configuration already exists
1202          * do nothing.
1203          */
1204         if (access(new_cfg,F_OK)==0)
1205         {
1206                 free(new_cfg);
1207                 return 0;
1208         }
1209
1210         old_cfg_cli = ms_strdup_printf("%s/.linphonec", home);
1211
1212         /*
1213          * If the *OLD* CLI configurations exist copy it to
1214          * the new file and make it a symlink.
1215          */
1216         if (access(old_cfg_cli, F_OK)==0)
1217         {
1218                 if ( ! copy_file(old_cfg_cli, new_cfg) )
1219                 {
1220                         free(old_cfg_cli);
1221                         free(new_cfg);
1222                         return -1;
1223                 }
1224                 printf("%s copied to %s\n", old_cfg_cli, new_cfg);
1225                 free(old_cfg_cli);
1226                 free(new_cfg);
1227                 return 1;
1228         }
1229
1230         free(old_cfg_cli);
1231         old_cfg_gui = ms_strdup_printf("%s/.gnome2/linphone", home);
1232
1233         /*
1234          * If the *OLD* GUI configurations exist copy it to
1235          * the new file and make it a symlink.
1236          */
1237         if (access(old_cfg_gui, F_OK)==0)
1238         {
1239                 if ( ! copy_file(old_cfg_gui, new_cfg) )
1240                 {
1241                         exit(EXIT_FAILURE);
1242                         free(old_cfg_gui);
1243                         free(new_cfg);
1244                         return -1;
1245                 }
1246                 printf("%s copied to %s\n", old_cfg_gui, new_cfg);
1247                 free(old_cfg_gui);
1248                 free(new_cfg);
1249                 return 1;
1250         }
1251
1252         free(old_cfg_gui);
1253         free(new_cfg);
1254 #endif /*_WIN32_WCE*/
1255         return 0;
1256 }
1257 #if !defined(_WIN32_WCE)
1258 /*
1259  * Copy file "from" to file "to".
1260  * Destination file is truncated if existing.
1261  * Return 1 on success, 0 on error (printing an error).
1262  */
1263 static int
1264 copy_file(const char *from, const char *to)
1265 {
1266         char message[256];
1267         FILE *in, *out;
1268         char buf[256];
1269         size_t n;
1270
1271         /* Open "from" file for reading */
1272         in=fopen(from, "r");
1273         if ( in == NULL )
1274         {
1275                 snprintf(message, 255, "Can't open %s for reading: %s\n",
1276                         from, strerror(errno));
1277                 fprintf(stderr, "%s", message);
1278                 return 0;
1279         }
1280
1281         /* Open "to" file for writing (will truncate existing files) */
1282         out=fopen(to, "w");
1283         if ( out == NULL )
1284         {
1285                 snprintf(message, 255, "Can't open %s for writing: %s\n",
1286                         to, strerror(errno));
1287                 fprintf(stderr, "%s", message);
1288                 return 0;
1289         }
1290
1291         /* Copy data from "in" to "out" */
1292         while ( (n=fread(buf, 1, sizeof buf, in)) > 0 )
1293         {
1294                 if ( ! fwrite(buf, 1, n, out) )
1295                 {
1296                         return 0;
1297                 }
1298         }
1299
1300         fclose(in);
1301         fclose(out);
1302
1303         return 1;
1304 }
1305 #endif /*_WIN32_WCE*/
1306
1307 #ifdef HAVE_READLINE
1308 static char **
1309 linephonec_readline_completion(const char *text, int start, int end)
1310 {
1311         char **matches = NULL;
1312
1313         /*
1314          * Prevent readline from falling
1315          * back to filename-completion
1316          */
1317         rl_attempted_completion_over=1;
1318
1319         /*
1320          * If this is the start of line we complete with commands
1321          */
1322         if ( ! start )
1323         {
1324                 return rl_completion_matches(text, linphonec_command_generator);
1325         }
1326
1327         /*
1328          * Otherwise, we should peek at command name
1329          * or context to implement a smart completion.
1330          * For example: "call .." could return
1331          * friends' sip-uri as matches
1332          */
1333
1334         return matches;
1335 }
1336
1337 #endif
1338
1339 /*
1340  * Strip blanks from a string.
1341  * Return a pointer into the provided string.
1342  * Modifies input adding a NULL at first
1343  * of trailing blanks.
1344  */
1345 char *
1346 lpc_strip_blanks(char *input)
1347 {
1348         char *iptr;
1349
1350         /* Find first non-blank */
1351         while(*input && isspace(*input)) ++input;
1352
1353         /* Find last non-blank */
1354         iptr=input+strlen(input);
1355         if (iptr > input) {
1356                 while(isspace(*--iptr));
1357                 *(iptr+1)='\0';
1358         }
1359
1360         return input;
1361 }
1362
1363 /****************************************************************************
1364  *
1365  * $Log: linphonec.c,v $
1366  * Revision 1.57  2007/11/14 13:40:27  smorlat
1367  * fix --disable-video build.
1368  *
1369  * Revision 1.56  2007/09/26 14:07:27  fixkowalski
1370  * - ANSI/C++ compilation issues with non-GCC compilers
1371  * - Faster epm-based packaging
1372  * - Ability to build & run on FC6's eXosip/osip
1373  *
1374  * Revision 1.55  2007/09/24 16:01:58  smorlat
1375  * fix bugs.
1376  *
1377  * Revision 1.54  2007/08/22 14:06:11  smorlat
1378  * authentication bugs fixed.
1379  *
1380  * Revision 1.53  2007/02/13 21:31:01  smorlat
1381  * added patch for general state.
1382  * new doxygen for oRTP
1383  * gtk-doc removed.
1384  *
1385  * Revision 1.52  2007/01/10 14:11:24  smorlat
1386  * add --video to linphonec.
1387  *
1388  * Revision 1.51  2006/08/21 12:49:59  smorlat
1389  * merged several little patches.
1390  *
1391  * Revision 1.50  2006/07/26 08:17:28  smorlat
1392  * fix bugs.
1393  *
1394  * Revision 1.49  2006/07/17 18:45:00  smorlat
1395  * support for several event queues in ortp.
1396  * glib dependency removed from coreapi/ and console/
1397  *
1398  * Revision 1.48  2006/04/09 12:45:32  smorlat
1399  * linphonec improvements.
1400  *
1401  * Revision 1.47  2006/04/04 08:04:34  smorlat
1402  * switched to mediastreamer2, most bugs fixed.
1403  *
1404  * Revision 1.46  2006/03/16 17:17:40  smorlat
1405  * fix various bugs.
1406  *
1407  * Revision 1.45  2006/03/12 21:48:31  smorlat
1408  * gcc-2.95 compile error fixed.
1409  * mediastreamer2 in progress
1410  *
1411  * Revision 1.44  2006/03/04 11:17:10  smorlat
1412  * mediastreamer2 in progress.
1413  *
1414  * Revision 1.43  2006/02/13 09:50:50  strk
1415  * fixed unused variable warning.
1416  *
1417  * Revision 1.42  2006/02/02 15:39:18  strk
1418  * - Added 'friend list' and 'friend call' commands
1419  * - Allowed for multiple DTFM send in a single line
1420  * - Added status-specific callback (bare version)
1421  *
1422  * Revision 1.41  2006/02/02 13:30:05  strk
1423  * - Padded vtable with missing callbacks
1424  *   (fixing a segfault on friends subscription)
1425  * - Handled friends notify (bare version)
1426  * - Handled text messages receive (bare version)
1427  * - Printed message on subscription request (bare version)
1428  *
1429  * Revision 1.40  2006/01/26 09:48:05  strk
1430  * Added limits.h include
1431  *
1432  * Revision 1.39  2006/01/26 02:11:01  strk
1433  * Removed unused variables, fixed copyright date
1434  *
1435  * Revision 1.38  2006/01/25 18:33:02  strk
1436  * Removed the -t swich, terminate_on_close made the default behaviour
1437  *
1438  * Revision 1.37  2006/01/20 14:12:34  strk
1439  * Added linphonec_init() and linphonec_finish() functions.
1440  * Handled SIGINT and SIGTERM to invoke linphonec_finish().
1441  * Handling of auto-termination (-t) moved to linphonec_finish().
1442  * Reworked main (input read) loop to not rely on 'terminate'
1443  * and 'run' variable (dropped). configfile_name allocated on stack
1444  * using PATH_MAX limit. Changed print_usage signature to allow
1445  * for an exit_status specification.
1446  *
1447  * Revision 1.36  2006/01/18 09:25:32  strk
1448  * Command completion inhibited in proxy addition and auth request prompts.
1449  * Avoided use of readline's internal filename completion.
1450  *
1451  * Revision 1.35  2006/01/14 13:29:32  strk
1452  * Reworked commands interface to use a table structure,
1453  * used by command line parser and help function.
1454  * Implemented first level of completion (commands).
1455  * Added notification of invalid "answer" and "terminate"
1456  * commands (no incoming call, no active call).
1457  * Forbidden "call" intialization when a call is already active.
1458  * Cleaned up all commands, adding more feedback and error checks.
1459  *
1460  * Revision 1.34  2006/01/13 13:00:29  strk
1461  * Added linphonec.h. Code layout change (added comments, forward decl,
1462  * globals on top, copyright notices and Logs). Handled out-of-memory
1463  * condition on history management. Removed assumption on sizeof(char).
1464  * Fixed bug in authentication prompt (introduced by readline).
1465  * Added support for multiple authentication requests (up to MAX_PENDING_AUTH).
1466  *
1467  *
1468  ****************************************************************************/
1469