]> sjero.net Git - linphone/blob - linphone/console/linphonec.c
81fccea1423bee5dc8d193e76d1e78c37b78be05
[linphone] / 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                 const char *from, const char *status, const char *img);
124 static void linphonec_new_unknown_subscriber(LinphoneCore *lc,
125                 LinphoneFriend *lf, const char *url);
126 static void linphonec_bye_received(LinphoneCore *lc, const char *from);
127 static void linphonec_text_received(LinphoneCore *lc, LinphoneChatRoom *cr,
128                 const char *from, const char *msg);
129 static void linphonec_display_status (LinphoneCore * lc, const char *something);
130 static void linphonec_general_state (LinphoneCore * lc, LinphoneGeneralState *gstate);
131 static void linphonec_dtmf_received(LinphoneCore *lc, int dtmf);
132 static void print_prompt(LinphoneCore *opm);
133 /***************************************************************************
134  *
135  * Global variables
136  *
137  ***************************************************************************/
138
139 LinphoneCore *linphonec;
140 FILE *mylogfile;
141 #ifdef HAVE_READLINE
142 static char *histfile_name=NULL;
143 static char last_in_history[256];
144 #endif
145 //auto answer (-a) option
146 static bool_t auto_answer=FALSE;
147 static bool_t answer_call=FALSE;
148 static bool_t vcap_enabled=FALSE;
149 static bool_t display_enabled=FALSE;
150 static bool_t preview_enabled=FALSE;
151 static bool_t show_general_state=FALSE;
152 static bool_t unix_socket=FALSE;
153 static bool_t linphonec_running=TRUE;
154 LPC_AUTH_STACK auth_stack;
155 static int trace_level = 0;
156 static char *logfile_name = NULL;
157 static char configfile_name[PATH_MAX];
158 static char *sipAddr = NULL; /* for autocall */
159 #if !defined(_WIN32_WCE)
160 static ortp_pipe_t client_sock=ORTP_PIPE_INVALID;
161 #endif /*_WIN32_WCE*/
162 char prompt[PROMPT_MAX_LEN];
163 #if !defined(_WIN32_WCE)
164 static ortp_thread_t pipe_reader_th;
165 static bool_t pipe_reader_run=FALSE;
166 #endif /*_WIN32_WCE*/
167 #if !defined(_WIN32_WCE)
168 static ortp_pipe_t server_sock;
169 #endif /*_WIN32_WCE*/
170
171
172 LinphoneCoreVTable linphonec_vtable
173 #if !defined (_MSC_VER)
174 = {
175         .show =(ShowInterfaceCb) stub,
176         .inv_recv = linphonec_call_received,
177         .bye_recv = linphonec_bye_received,
178         .notify_recv = linphonec_notify_received,
179         .new_unknown_subscriber = linphonec_new_unknown_subscriber,
180         .auth_info_requested = linphonec_prompt_for_auth,
181         .display_status = linphonec_display_status,
182         .display_message=linphonec_display_something,
183 #ifdef VINCENT_MAURY_RSVP
184         /* the yes/no dialog box */
185         .display_yes_no= (DisplayMessageCb) stub,
186 #endif
187         .display_warning=linphonec_display_warning,
188         .display_url=linphonec_display_url,
189         .display_question=(DisplayQuestionCb)stub,
190         .text_received=linphonec_text_received,
191         .general_state=linphonec_general_state,
192         .dtmf_received=linphonec_dtmf_received
193 }
194 #endif /*_WIN32_WCE*/
195 ;
196
197
198
199 /***************************************************************************
200  *
201  * Linphone core callbacks
202  *
203  ***************************************************************************/
204
205 /*
206  * Linphone core callback
207  */
208 static void
209 linphonec_display_something (LinphoneCore * lc, const char *something)
210 {
211         fprintf (stdout, "%s\n%s", something,prompt);
212         fflush(stdout);
213 }
214
215 /*
216  * Linphone core callback
217  */
218 static void
219 linphonec_display_status (LinphoneCore * lc, const char *something)
220 {
221         fprintf (stdout, "%s\n%s", something,prompt);
222         fflush(stdout);
223 }
224
225 /*
226  * Linphone core callback
227  */
228 static void
229 linphonec_display_warning (LinphoneCore * lc, const char *something)
230 {
231         fprintf (stdout, "Warning: %s\n%s", something,prompt);
232         fflush(stdout);
233 }
234
235 /*
236  * Linphone core callback
237  */
238 static void
239 linphonec_display_url (LinphoneCore * lc, const char *something, const char *url)
240 {
241         fprintf (stdout, "%s : %s\n", something, url);
242 }
243
244
245 /*
246  * Linphone core callback
247  */
248 static void
249 linphonec_call_received(LinphoneCore *lc, const char *from)
250 {
251         linphonec_set_caller(from);
252         if ( auto_answer)  {
253                 answer_call=TRUE;
254         }
255 }
256
257 /*
258  * Linphone core callback
259  */
260 static void
261 linphonec_prompt_for_auth(LinphoneCore *lc, const char *realm, const char *username)
262 {
263         /* no prompt possible when using pipes or tcp mode*/
264         if (unix_socket){
265                 linphone_core_abort_authentication(lc,NULL);
266         }else{
267                 LinphoneAuthInfo *pending_auth;
268
269                 if ( auth_stack.nitems+1 > MAX_PENDING_AUTH )
270                 {
271                         fprintf(stderr,
272                                 "Can't accept another authentication request.\n"
273                                 "Consider incrementing MAX_PENDING_AUTH macro.\n");
274                         return;
275                 }
276
277                 pending_auth=linphone_auth_info_new(username,NULL,NULL,NULL,realm);
278                 auth_stack.elem[auth_stack.nitems++]=pending_auth;
279         }
280 }
281
282 /*
283  * Linphone core callback
284  */
285 static void
286 linphonec_notify_received(LinphoneCore *lc,LinphoneFriend *fid,
287                 const char *from, const char *status, const char *img)
288 {
289         printf("Friend %s is %s\n", from, status);
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         --(auth_stack.nitems);
831 #ifdef HAVE_READLINE
832         /*
833          * Reset line_buffer, to avoid the password
834          * to be used again from outer readline
835          */
836         rl_line_buffer[0]='\0';
837         rl_event_hook=old_event_hook;
838 #endif
839         return 1;
840 }
841
842 void
843 print_usage (int exit_status)
844 {
845         fprintf (stdout, "\n\
846 usage: linphonec [-c file] [-s sipaddr] [-a] [-V] [-d level ] [-l logfile]\n\
847        linphonec -v\n\
848 \n\
849   -c  file             specify path of configuration file.\n\
850   -d  level            be verbose. 0 is no output. 6 is all output\n\
851   -l  logfile          specify the log file for your SIP phone\n\
852   -s  sipaddress       specify the sip call to do at startup\n\
853   -a                   enable auto answering for incoming calls\n\
854   -V                   enable video features globally (disabled by default)\n\
855   -C                   enable video capture only (disabled by default)\n\
856   -D                   enable video display only (disabled by default)\n\
857   -S                   show general state messages (disabled by default)\n\
858   -v or --version      display version and exits.\n");
859
860         exit(exit_status);
861 }
862
863
864 /*
865  *
866  * Called every second from main read loop.
867  *
868  * Will use the following globals:
869  *
870  *  - LinphoneCore linphonec
871  *  - LPC_AUTH_STACK auth_stack;
872  *
873  */
874 static int
875 linphonec_idle_call ()
876 {
877         LinphoneCore *opm=linphonec;
878
879         /* Uncomment the following to verify being called */
880         /* printf(".\n"); */
881
882         linphone_core_iterate(opm);
883         if (answer_call){
884                 fprintf (stdout, "-------auto answering to call-------\n" );
885                 linphone_core_accept_call(opm,NULL);
886                 answer_call=FALSE;
887         }
888
889         if ( auth_stack.nitems )
890         {
891                 /*
892                  * Inhibit command completion
893                  * during password prompts
894                  */
895 #ifdef HAVE_READLINE
896                 rl_inhibit_completion=1;
897 #endif
898                 linphonec_prompt_for_auth_final(opm);
899 #ifdef HAVE_READLINE
900                 rl_inhibit_completion=0;
901 #endif
902         }
903
904         return 0;
905 }
906
907 #ifdef HAVE_READLINE
908 /*
909  * Use globals:
910  *
911  *      - char *histfile_name (also sets this)
912  *      - char *last_in_history (allocates it)
913  */
914 static int
915 linphonec_initialize_readline()
916 {
917         /*rl_bind_key('\t', rl_insert);*/
918
919         /* Allow conditional parsing of ~/.inputrc */
920         rl_readline_name = "linphonec";
921
922         /* Call idle_call() every second */
923         rl_set_keyboard_input_timeout(LPC_READLINE_TIMEOUT);
924         rl_event_hook=linphonec_idle_call;
925
926         /* Set history file and read it */
927         histfile_name = ms_strdup_printf ("%s/.linphonec_history",
928                 getenv("HOME"));
929         read_history(histfile_name);
930
931         /* Initialized last_in_history cache*/
932         last_in_history[0] = '\0';
933
934         /* Register a completion function */
935         rl_attempted_completion_function = linephonec_readline_completion;
936
937         /* printf("Readline initialized.\n"); */
938         setlinebuf(stdout);
939         return 0;
940 }
941
942 /*
943  * Uses globals:
944  *
945  *      - char *histfile_name (writes history to file and frees it)
946  *      - char *last_in_history (frees it)
947  *
948  */
949 static int
950 linphonec_finish_readline()
951 {
952
953         stifle_history(HISTSIZE);
954         write_history(histfile_name);
955         free(histfile_name);
956         histfile_name=NULL;
957         return 0;
958 }
959
960 #endif
961
962 static void print_prompt(LinphoneCore *opm){
963 #ifdef IDENTITY_AS_PROMPT
964         snprintf(prompt, PROMPT_MAX_LEN, "%s> ",
965                 linphone_core_get_primary_contact(opm));
966 #else
967         snprintf(prompt, PROMPT_MAX_LEN, "linphonec> ");
968 #endif
969 }
970
971 static int
972 linphonec_main_loop (LinphoneCore * opm, char * sipAddr)
973 {
974         char buf[LINE_MAX_LEN]; /* auto call handling */
975         char *input;
976
977         print_prompt(opm);
978
979
980         /* auto call handling */
981         if (sipAddr != NULL )
982         {
983                 snprintf (buf, sizeof(buf),"call %s", sipAddr);
984                 linphonec_parse_command_line(linphonec, buf);
985         }
986
987         while (linphonec_running && (input=linphonec_readline(prompt)))
988         {
989                 char *iptr; /* input and input pointer */
990                 size_t input_len;
991
992                 /* Strip blanks */
993                 iptr=lpc_strip_blanks(input);
994
995                 input_len = strlen(iptr);
996
997                 /*
998                  * Do nothing but release memory
999                  * if only blanks are read
1000                  */
1001                 if ( ! input_len )
1002                 {
1003                         free(input);
1004                         continue;
1005                 }
1006
1007 #ifdef HAVE_READLINE
1008                 /*
1009                  * Only add to history if not already
1010                  * last item in it, and only if the command
1011                  * doesn't start with a space (to allow for
1012                  * hiding passwords)
1013                  */
1014                 if ( iptr == input && strcmp(last_in_history, iptr) )
1015                 {
1016                         strncpy(last_in_history,iptr,sizeof(last_in_history));
1017                         last_in_history[sizeof(last_in_history)-1]='\0';
1018                         add_history(iptr);
1019                 }
1020 #endif
1021
1022                 linphonec_parse_command_line(linphonec, iptr);
1023                 linphonec_command_finished();
1024                 free(input);
1025         }
1026
1027         return 0;
1028 }
1029
1030 /*
1031  *  Parse command line switches
1032  *
1033  *  Use globals:
1034  *
1035  *      - int trace_level
1036  *      - char *logfile_name
1037  *      - char *configfile_name
1038  *      - char *sipAddr
1039  */
1040 static int
1041 linphonec_parse_cmdline(int argc, char **argv)
1042 {
1043         int arg_num=1;
1044
1045         while (arg_num < argc)
1046         {
1047                 int old_arg_num = arg_num;
1048                 if (strncmp ("-d", argv[arg_num], 2) == 0)
1049                 {
1050                         arg_num++;
1051                         if (arg_num < argc)
1052                                 trace_level = atoi (argv[arg_num]);
1053                         else
1054                                 trace_level = 1;
1055                 }
1056                 else if (strncmp ("-l", argv[arg_num], 2) == 0)
1057                 {
1058                         arg_num++;
1059                         if (arg_num < argc)
1060                                 logfile_name = argv[arg_num];
1061                 }
1062                 else if (strncmp ("-c", argv[arg_num], 2) == 0)
1063                 {
1064                         if ( ++arg_num >= argc ) print_usage(EXIT_FAILURE);
1065 #if !defined(_WIN32_WCE)
1066                         if (access(argv[arg_num],F_OK)!=0 )
1067                         {
1068                                 fprintf (stderr,
1069                                         "Cannot open config file %s.\n",
1070                                          argv[arg_num]);
1071                                 exit(EXIT_FAILURE);
1072                         }
1073 #endif /*_WIN32_WCE*/
1074                         snprintf(configfile_name, PATH_MAX, "%s", argv[arg_num]);
1075                 }
1076                 else if (strncmp ("-s", argv[arg_num], 2) == 0)
1077                 {
1078                         arg_num++;
1079                         if (arg_num < argc)
1080                                 sipAddr = argv[arg_num];
1081                 }
1082                 else if (strncmp ("-a", argv[arg_num], 2) == 0)
1083                 {
1084                         auto_answer = TRUE;
1085                 }
1086                 else if (strncmp ("-C", argv[arg_num], 2) == 0)
1087                 {
1088                         vcap_enabled = TRUE;
1089                 }
1090                 else if (strncmp ("-D", argv[arg_num], 2) == 0)
1091                 {
1092                         display_enabled = TRUE;
1093                 }
1094                 else if (strncmp ("-V", argv[arg_num], 2) == 0)
1095                 {
1096                         display_enabled = TRUE;
1097                         vcap_enabled = TRUE;
1098                         preview_enabled=TRUE;
1099                 }
1100                 else if ((strncmp ("-v", argv[arg_num], 2) == 0)
1101                          ||
1102                          (strncmp
1103                           ("--version", argv[arg_num],
1104                            strlen ("--version")) == 0))
1105                 {
1106 #if !defined(_WIN32_WCE)
1107                         printf ("version: " LINPHONE_VERSION "\n");
1108 #endif
1109                         exit (EXIT_SUCCESS);
1110                 }
1111                 else if (strncmp ("-S", argv[arg_num], 2) == 0)
1112                 {
1113                         show_general_state = TRUE;
1114                 }
1115                 else if (strncmp ("--pipe", argv[arg_num], 6) == 0)
1116                 {
1117                         unix_socket=1;
1118                 }
1119                 else if (old_arg_num == arg_num)
1120                 {
1121                         fprintf (stderr, "ERROR: bad arguments\n");
1122                         print_usage (EXIT_FAILURE);
1123                 }
1124                 arg_num++;
1125         }
1126
1127         return 1;
1128 }
1129
1130 /*
1131  * Up to version 1.2.1 linphone used ~/.linphonec for
1132  * CLI and ~/.gnome2/linphone for GUI as configuration file.
1133  * In newer version both interfaces will use ~/.linphonerc.
1134  *
1135  * This function helps transparently migrating from one
1136  * to the other layout using the following heuristic:
1137  *
1138  *      IF new_config EXISTS => do nothing
1139  *      ELSE IF old_cli_config EXISTS => copy to new_config
1140  *      ELSE IF old_gui_config EXISTS => copy to new_config
1141  *
1142  * Returns:
1143  *       0 if it did nothing
1144  *       1 if it migrated successfully
1145  *      -1 on error
1146  */
1147 static int
1148 handle_configfile_migration()
1149 {
1150 #if !defined(_WIN32_WCE)
1151         char *old_cfg_gui;
1152         char *old_cfg_cli;
1153         char *new_cfg;
1154 #if !defined(_WIN32_WCE)
1155         const char *home = getenv("HOME");
1156 #else
1157         const char *home = ".";
1158 #endif /*_WIN32_WCE*/
1159         new_cfg = ms_strdup_printf("%s/.linphonerc", home);
1160
1161         /*
1162          * If the *NEW* configuration already exists
1163          * do nothing.
1164          */
1165         if (access(new_cfg,F_OK)==0)
1166         {
1167                 free(new_cfg);
1168                 return 0;
1169         }
1170
1171         old_cfg_cli = ms_strdup_printf("%s/.linphonec", home);
1172
1173         /*
1174          * If the *OLD* CLI configurations exist copy it to
1175          * the new file and make it a symlink.
1176          */
1177         if (access(old_cfg_cli, F_OK)==0)
1178         {
1179                 if ( ! copy_file(old_cfg_cli, new_cfg) )
1180                 {
1181                         free(old_cfg_cli);
1182                         free(new_cfg);
1183                         return -1;
1184                 }
1185                 printf("%s copied to %s\n", old_cfg_cli, new_cfg);
1186                 free(old_cfg_cli);
1187                 free(new_cfg);
1188                 return 1;
1189         }
1190
1191         free(old_cfg_cli);
1192         old_cfg_gui = ms_strdup_printf("%s/.gnome2/linphone", home);
1193
1194         /*
1195          * If the *OLD* GUI configurations exist copy it to
1196          * the new file and make it a symlink.
1197          */
1198         if (access(old_cfg_gui, F_OK)==0)
1199         {
1200                 if ( ! copy_file(old_cfg_gui, new_cfg) )
1201                 {
1202                         exit(EXIT_FAILURE);
1203                         free(old_cfg_gui);
1204                         free(new_cfg);
1205                         return -1;
1206                 }
1207                 printf("%s copied to %s\n", old_cfg_gui, new_cfg);
1208                 free(old_cfg_gui);
1209                 free(new_cfg);
1210                 return 1;
1211         }
1212
1213         free(old_cfg_gui);
1214         free(new_cfg);
1215 #endif /*_WIN32_WCE*/
1216         return 0;
1217 }
1218 #if !defined(_WIN32_WCE)
1219 /*
1220  * Copy file "from" to file "to".
1221  * Destination file is truncated if existing.
1222  * Return 1 on success, 0 on error (printing an error).
1223  */
1224 static int
1225 copy_file(const char *from, const char *to)
1226 {
1227         char message[256];
1228         FILE *in, *out;
1229         char buf[256];
1230         size_t n;
1231
1232         /* Open "from" file for reading */
1233         in=fopen(from, "r");
1234         if ( in == NULL )
1235         {
1236                 snprintf(message, 255, "Can't open %s for reading: %s\n",
1237                         from, strerror(errno));
1238                 fprintf(stderr, "%s", message);
1239                 return 0;
1240         }
1241
1242         /* Open "to" file for writing (will truncate existing files) */
1243         out=fopen(to, "w");
1244         if ( out == NULL )
1245         {
1246                 snprintf(message, 255, "Can't open %s for writing: %s\n",
1247                         to, strerror(errno));
1248                 fprintf(stderr, "%s", message);
1249                 return 0;
1250         }
1251
1252         /* Copy data from "in" to "out" */
1253         while ( (n=fread(buf, 1, sizeof buf, in)) > 0 )
1254         {
1255                 if ( ! fwrite(buf, 1, n, out) )
1256                 {
1257                         return 0;
1258                 }
1259         }
1260
1261         fclose(in);
1262         fclose(out);
1263
1264         return 1;
1265 }
1266 #endif /*_WIN32_WCE*/
1267
1268 #ifdef HAVE_READLINE
1269 static char **
1270 linephonec_readline_completion(const char *text, int start, int end)
1271 {
1272         char **matches = NULL;
1273
1274         /*
1275          * Prevent readline from falling
1276          * back to filename-completion
1277          */
1278         rl_attempted_completion_over=1;
1279
1280         /*
1281          * If this is the start of line we complete with commands
1282          */
1283         if ( ! start )
1284         {
1285                 return rl_completion_matches(text, linphonec_command_generator);
1286         }
1287
1288         /*
1289          * Otherwise, we should peek at command name
1290          * or context to implement a smart completion.
1291          * For example: "call .." could return
1292          * friends' sip-uri as matches
1293          */
1294
1295         return matches;
1296 }
1297
1298 #endif
1299
1300 /*
1301  * Strip blanks from a string.
1302  * Return a pointer into the provided string.
1303  * Modifies input adding a NULL at first
1304  * of trailing blanks.
1305  */
1306 char *
1307 lpc_strip_blanks(char *input)
1308 {
1309         char *iptr;
1310
1311         /* Find first non-blank */
1312         while(*input && isspace(*input)) ++input;
1313
1314         /* Find last non-blank */
1315         iptr=input+strlen(input);
1316         if (iptr > input) {
1317                 while(isspace(*--iptr));
1318                 *(iptr+1)='\0';
1319         }
1320
1321         return input;
1322 }
1323
1324 /****************************************************************************
1325  *
1326  * $Log: linphonec.c,v $
1327  * Revision 1.57  2007/11/14 13:40:27  smorlat
1328  * fix --disable-video build.
1329  *
1330  * Revision 1.56  2007/09/26 14:07:27  fixkowalski
1331  * - ANSI/C++ compilation issues with non-GCC compilers
1332  * - Faster epm-based packaging
1333  * - Ability to build & run on FC6's eXosip/osip
1334  *
1335  * Revision 1.55  2007/09/24 16:01:58  smorlat
1336  * fix bugs.
1337  *
1338  * Revision 1.54  2007/08/22 14:06:11  smorlat
1339  * authentication bugs fixed.
1340  *
1341  * Revision 1.53  2007/02/13 21:31:01  smorlat
1342  * added patch for general state.
1343  * new doxygen for oRTP
1344  * gtk-doc removed.
1345  *
1346  * Revision 1.52  2007/01/10 14:11:24  smorlat
1347  * add --video to linphonec.
1348  *
1349  * Revision 1.51  2006/08/21 12:49:59  smorlat
1350  * merged several little patches.
1351  *
1352  * Revision 1.50  2006/07/26 08:17:28  smorlat
1353  * fix bugs.
1354  *
1355  * Revision 1.49  2006/07/17 18:45:00  smorlat
1356  * support for several event queues in ortp.
1357  * glib dependency removed from coreapi/ and console/
1358  *
1359  * Revision 1.48  2006/04/09 12:45:32  smorlat
1360  * linphonec improvements.
1361  *
1362  * Revision 1.47  2006/04/04 08:04:34  smorlat
1363  * switched to mediastreamer2, most bugs fixed.
1364  *
1365  * Revision 1.46  2006/03/16 17:17:40  smorlat
1366  * fix various bugs.
1367  *
1368  * Revision 1.45  2006/03/12 21:48:31  smorlat
1369  * gcc-2.95 compile error fixed.
1370  * mediastreamer2 in progress
1371  *
1372  * Revision 1.44  2006/03/04 11:17:10  smorlat
1373  * mediastreamer2 in progress.
1374  *
1375  * Revision 1.43  2006/02/13 09:50:50  strk
1376  * fixed unused variable warning.
1377  *
1378  * Revision 1.42  2006/02/02 15:39:18  strk
1379  * - Added 'friend list' and 'friend call' commands
1380  * - Allowed for multiple DTFM send in a single line
1381  * - Added status-specific callback (bare version)
1382  *
1383  * Revision 1.41  2006/02/02 13:30:05  strk
1384  * - Padded vtable with missing callbacks
1385  *   (fixing a segfault on friends subscription)
1386  * - Handled friends notify (bare version)
1387  * - Handled text messages receive (bare version)
1388  * - Printed message on subscription request (bare version)
1389  *
1390  * Revision 1.40  2006/01/26 09:48:05  strk
1391  * Added limits.h include
1392  *
1393  * Revision 1.39  2006/01/26 02:11:01  strk
1394  * Removed unused variables, fixed copyright date
1395  *
1396  * Revision 1.38  2006/01/25 18:33:02  strk
1397  * Removed the -t swich, terminate_on_close made the default behaviour
1398  *
1399  * Revision 1.37  2006/01/20 14:12:34  strk
1400  * Added linphonec_init() and linphonec_finish() functions.
1401  * Handled SIGINT and SIGTERM to invoke linphonec_finish().
1402  * Handling of auto-termination (-t) moved to linphonec_finish().
1403  * Reworked main (input read) loop to not rely on 'terminate'
1404  * and 'run' variable (dropped). configfile_name allocated on stack
1405  * using PATH_MAX limit. Changed print_usage signature to allow
1406  * for an exit_status specification.
1407  *
1408  * Revision 1.36  2006/01/18 09:25:32  strk
1409  * Command completion inhibited in proxy addition and auth request prompts.
1410  * Avoided use of readline's internal filename completion.
1411  *
1412  * Revision 1.35  2006/01/14 13:29:32  strk
1413  * Reworked commands interface to use a table structure,
1414  * used by command line parser and help function.
1415  * Implemented first level of completion (commands).
1416  * Added notification of invalid "answer" and "terminate"
1417  * commands (no incoming call, no active call).
1418  * Forbidden "call" intialization when a call is already active.
1419  * Cleaned up all commands, adding more feedback and error checks.
1420  *
1421  * Revision 1.34  2006/01/13 13:00:29  strk
1422  * Added linphonec.h. Code layout change (added comments, forward decl,
1423  * globals on top, copyright notices and Logs). Handled out-of-memory
1424  * condition on history management. Removed assumption on sizeof(char).
1425  * Fixed bug in authentication prompt (introduced by readline).
1426  * Added support for multiple authentication requests (up to MAX_PENDING_AUTH).
1427  *
1428  *
1429  ****************************************************************************/
1430