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