Do not print extra STRING_CR on successfull command.
[vlc.git] / modules / control / telnet.c
1 /*****************************************************************************
2  * telnet.c: VLM interface plugin
3  *****************************************************************************
4  * Copyright (C) 2000-2005 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Simon Latapie <garf@videolan.org>
8  *          Laurent Aimar <fenrir@videolan.org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #include <stdlib.h>                                      /* malloc(), free() */
29
30 #include <vlc/vlc.h>
31 #include <vlc/intf.h>
32
33 #include <vlc/input.h>
34
35 #include <sys/stat.h>
36
37 #include <errno.h>
38 #include <fcntl.h>
39
40 #ifdef HAVE_SYS_TIME_H
41 #    include <sys/time.h>
42 #endif
43
44 #ifdef HAVE_UNISTD_H
45 #   include <unistd.h>
46 #endif
47
48 #include "network.h"
49 #include "vlc_url.h"
50
51 #include "vlc_vlm.h"
52
53 #define READ_MODE_PWD 1
54 #define READ_MODE_CMD 2
55 #define WRITE_MODE_PWD 3 // when we write the word "Password:"
56 #define WRITE_MODE_CMD 4
57
58 /* telnet commands */
59 #define TEL_WILL    251
60 #define TEL_WONT    252
61 #define TEL_DO      253
62 #define TEL_DONT    254
63 #define TEL_IAC     255
64 #define TEL_ECHO    1
65
66 /*****************************************************************************
67  * Module descriptor
68  *****************************************************************************/
69 static int  Open ( vlc_object_t * );
70 static void Close( vlc_object_t * );
71
72 #define TELNETHOST_TEXT N_( "Telnet Interface host" )
73 #define TELNETHOST_LONGTEXT N_( "Default to listen on all network interfaces" )
74 #define TELNETPORT_TEXT N_( "Telnet Interface port" )
75 #define TELNETPORT_LONGTEXT N_( "Default to 4212" )
76 #define TELNETPORT_DEFAULT 4212
77 #define TELNETPWD_TEXT N_( "Telnet Interface password" )
78 #define TELNETPWD_LONGTEXT N_( "Default to admin" )
79 #define TELNETPWD_DEFAULT "admin"
80
81 vlc_module_begin();
82     set_shortname( "Telnet" );
83     set_category( CAT_INTERFACE );
84     set_subcategory( SUBCAT_INTERFACE_GENERAL );
85     add_string( "telnet-host", "", NULL, TELNETHOST_TEXT,
86                  TELNETHOST_LONGTEXT, VLC_TRUE );
87     add_integer( "telnet-port", TELNETPORT_DEFAULT, NULL, TELNETPORT_TEXT,
88                  TELNETPORT_LONGTEXT, VLC_TRUE );
89     add_string( "telnet-password", TELNETPWD_DEFAULT, NULL, TELNETPWD_TEXT,
90                 TELNETPWD_LONGTEXT, VLC_TRUE );
91     set_description( _("VLM remote control interface") );
92     add_category_hint( "VLM", NULL, VLC_FALSE );
93     set_capability( "interface", 0 );
94     set_callbacks( Open , Close );
95 vlc_module_end();
96
97 /*****************************************************************************
98  * Local prototypes.
99  *****************************************************************************/
100 static void Run( intf_thread_t * );
101
102 typedef struct
103 {
104     int        i_mode; /* read or write */
105     int        fd;
106     char       buffer_read[1000]; // 1000 byte per command should be sufficient
107     char      *buffer_write;
108     char      *p_buffer_read;
109     char      *p_buffer_write; // the position in the buffer
110     int        i_buffer_write; // the number of byte we still have to send
111     int        i_tel_cmd; // for specific telnet commands
112
113 } telnet_client_t;
114
115 static char *MessageToString( vlm_message_t *, int );
116 static void Write_message( telnet_client_t *, vlm_message_t *, char *, int );
117
118 struct intf_sys_t
119 {
120    telnet_client_t **clients;
121    int             i_clients;
122    int             *pi_fd;
123    vlm_t           *mediatheque;
124 };
125
126 /* 
127  * getPort: Decide which port to use. There are two possibilities to
128  * specify a port: integrated in the --telnet-host option with :PORT
129  * or using the --telnet-port option. The --telnet-port option has
130  * precedence. 
131  * This code relies upon the fact the url.i_port is 0 if the :PORT 
132  * option is missing from --telnet-host.
133  */
134 static int getPort(intf_thread_t *p_intf, vlc_url_t url, int i_port)
135     {
136     // Print error if two different ports have been specified
137     if (url.i_port != 0  &&
138         i_port != TELNETPORT_DEFAULT && 
139         url.i_port != i_port )
140     {
141             msg_Err( p_intf, "ignoring port %d and using %d", url.i_port,
142                  i_port);
143     }
144     if (i_port != TELNETPORT_DEFAULT)
145     {
146             return i_port;
147     }
148     if (url.i_port != 0)
149     {
150             return url.i_port;
151     }
152     // return default
153     return i_port;
154 }
155
156 /*****************************************************************************
157  * Open: initialize dummy interface
158  *****************************************************************************/
159 static int Open( vlc_object_t *p_this )
160 {
161     intf_thread_t *p_intf = (intf_thread_t*) p_this;
162     vlm_t *mediatheque;
163     char *psz_address;
164     vlc_url_t url;
165     int i_telnetport;
166
167     if( !(mediatheque = vlm_New( p_intf )) )
168     {
169         msg_Err( p_intf, "cannot start VLM" );
170         return VLC_EGENERIC;
171     }
172
173     msg_Info( p_intf, "Using the VLM interface plugin..." );
174
175     i_telnetport = config_GetInt( p_intf, "telnet-port" );
176     psz_address  = config_GetPsz( p_intf, "telnet-host" );
177
178     vlc_UrlParse(&url, psz_address, 0);
179
180     // There might be two ports given, resolve any potentially
181     // conflict
182     url.i_port = getPort(p_intf, url, i_telnetport);
183
184     p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
185     if( ( p_intf->p_sys->pi_fd = net_ListenTCP( p_intf, url.psz_host, url.i_port ) )
186                 == NULL )
187     {
188         msg_Err( p_intf, "cannot listen for telnet" );
189         vlc_UrlClean(&url);
190         free( psz_address );
191         free( p_intf->p_sys );
192         return VLC_EGENERIC;
193     }
194     msg_Info( p_intf, 
195               "Telnet interface started on interface %s %d",
196               url.psz_host, url.i_port );
197
198     p_intf->p_sys->i_clients   = 0;
199     p_intf->p_sys->clients     = NULL;
200     p_intf->p_sys->mediatheque = mediatheque;
201     p_intf->pf_run = Run;
202
203     vlc_UrlClean(&url);
204     free( psz_address );
205     return VLC_SUCCESS;
206 }
207
208 /*****************************************************************************
209  * Close:
210  *****************************************************************************/
211 static void Close( vlc_object_t *p_this )
212 {
213     intf_thread_t *p_intf = (intf_thread_t*)p_this;
214     intf_sys_t    *p_sys  = p_intf->p_sys;
215     int i;
216
217     for( i = 0; i < p_sys->i_clients; i++ )
218     {
219         telnet_client_t *cl = p_sys->clients[i];
220
221         net_Close( cl->fd );
222         free( cl );
223     }
224     if( p_sys->clients != NULL ) free( p_sys->clients );
225
226     net_ListenClose( p_sys->pi_fd );
227
228     vlm_Delete( p_sys->mediatheque );
229
230     free( p_sys );
231 }
232
233 /*****************************************************************************
234  * Run: main loop
235  *****************************************************************************/
236 static void Run( intf_thread_t *p_intf )
237 {
238     intf_sys_t     *p_sys = p_intf->p_sys;
239     struct timeval  timeout;
240     char           *psz_password;
241
242     psz_password = config_GetPsz( p_intf, "telnet-password" );
243
244     while( !p_intf->b_die )
245     {
246         fd_set fds_read, fds_write;
247         int    i_handle_max = 0;
248         int    i_ret, i_len, fd, i;
249
250         /* if a new client wants to communicate */
251         fd = net_Accept( p_intf, p_sys->pi_fd, p_sys->i_clients > 0 ? 0 : -1 );
252         if( fd > 0 )
253         {
254             telnet_client_t *cl;
255
256             /* to be non blocking */
257 #if defined( WIN32 ) || defined( UNDER_CE )
258             {
259                 unsigned long i_dummy = 1;
260                 ioctlsocket( fd, FIONBIO, &i_dummy );
261             }
262 #else
263             fcntl( fd, F_SETFL, O_NONBLOCK );
264 #endif
265             cl = malloc( sizeof( telnet_client_t ));
266             cl->i_tel_cmd = 0;
267             cl->fd = fd;
268             cl->buffer_write = NULL;
269             cl->p_buffer_write = cl->buffer_write;
270             Write_message( cl, NULL, "Password: \xff\xfb\x01", WRITE_MODE_PWD );
271
272             TAB_APPEND( p_sys->i_clients, p_sys->clients, cl );
273         }
274
275         /* to do a proper select */
276         FD_ZERO( &fds_read );
277         FD_ZERO( &fds_write );
278
279         for( i = 0 ; i < p_sys->i_clients ; i++ )
280         {
281             telnet_client_t *cl = p_sys->clients[i];
282
283             if( cl->i_mode == WRITE_MODE_PWD || cl->i_mode == WRITE_MODE_CMD )
284             {
285                 FD_SET( cl->fd , &fds_write );
286             }
287             else
288             {
289                 FD_SET( cl->fd , &fds_read );
290             }
291             i_handle_max = __MAX( i_handle_max, cl->fd );
292         }
293
294         timeout.tv_sec = 0;
295         timeout.tv_usec = 500*1000;
296
297         i_ret = select( i_handle_max + 1, &fds_read, &fds_write, 0, &timeout );
298         if( i_ret == -1 && errno != EINTR )
299         {
300             msg_Warn( p_intf, "cannot select sockets" );
301             msleep( 1000 );
302             continue;
303         }
304         else if( i_ret <= 0 )
305         {
306             continue;
307         }
308
309         /* check if there is something to do with the socket */
310         for( i = 0 ; i < p_sys->i_clients ; i++ )
311         {
312             telnet_client_t *cl = p_sys->clients[i];
313
314             if( FD_ISSET(cl->fd , &fds_write) && cl->i_buffer_write > 0 )
315             {
316                 i_len = send( cl->fd , cl->p_buffer_write ,
317                               cl->i_buffer_write , 0 );
318                 if( i_len > 0 )
319                 {
320                     cl->p_buffer_write += i_len;
321                     cl->i_buffer_write -= i_len;
322                 }
323             }
324             else if( FD_ISSET( cl->fd, &fds_read) )
325             {
326                 int i_end = 0;
327                 int i_recv;
328
329                 while( (i_recv=recv( cl->fd, cl->p_buffer_read, 1, 0 )) > 0 &&
330                        cl->p_buffer_read - cl->buffer_read < 999 )
331                 {
332                     switch( cl->i_tel_cmd )
333                     {
334                     case 0:
335                         switch( *(uint8_t *)cl->p_buffer_read )
336                         {
337                         case '\r':
338                             break;
339                         case '\n':
340                             *cl->p_buffer_read = '\n';
341                             i_end = 1;
342                             break;
343                         case TEL_IAC: // telnet specific command
344                             cl->i_tel_cmd = 1;
345                             cl->p_buffer_read++;
346                             break;
347                         default:
348                             cl->p_buffer_read++;
349                             break;
350                         }
351                         break;
352                     case 1:
353                         switch( *(uint8_t *)cl->p_buffer_read )
354                         {
355                         case TEL_WILL: case TEL_WONT:
356                         case TEL_DO: case TEL_DONT:
357                             cl->i_tel_cmd++;
358                             cl->p_buffer_read++;
359                             break;
360                         default:
361                             cl->i_tel_cmd = 0;
362                             cl->p_buffer_read--;
363                             break;
364                         }
365                         break;
366                     case 2:
367                         cl->i_tel_cmd = 0;
368                         cl->p_buffer_read -= 2;
369                         break;
370                     }
371
372                     if( i_end != 0 ) break;
373                 }
374
375                 if( cl->p_buffer_read - cl->buffer_read == 999 )
376                 {
377                     Write_message( cl, NULL, "Line too long\r\n",
378                                    cl->i_mode + 2 );
379                 }
380
381                 if (i_recv == 0)
382                 {
383                     net_Close( cl->fd );
384                     TAB_REMOVE( p_intf->p_sys->i_clients ,
385                                 p_intf->p_sys->clients , cl );
386                     free( cl );
387                 }
388             }
389         }
390
391         /* and now we should bidouille the data we received / send */
392         for( i = 0 ; i < p_sys->i_clients ; i++ )
393         {
394             telnet_client_t *cl = p_sys->clients[i];
395
396             if( cl->i_mode >= WRITE_MODE_PWD && cl->i_buffer_write == 0 )
397             {
398                // we have finished to send
399                cl->i_mode -= 2; // corresponding READ MODE
400             }
401             else if( cl->i_mode == READ_MODE_PWD &&
402                      *cl->p_buffer_read == '\n' )
403             {
404                 *cl->p_buffer_read = '\0';
405                 if( strcmp( psz_password, cl->buffer_read ) == 0 )
406                 {
407                     Write_message( cl, NULL, "\xff\xfc\x01\r\nWelcome, "
408                                    "Master\r\n> ", WRITE_MODE_CMD );
409                 }
410                 else
411                 {
412                     /* wrong password */
413                     Write_message( cl, NULL,
414                                    "\r\nWrong password.\r\nPassword: ",
415                                    WRITE_MODE_PWD );
416                 }
417             }
418             else if( cl->i_mode == READ_MODE_CMD &&
419                      *cl->p_buffer_read == '\n' )
420             {
421                 /* ok, here is a command line */
422                 if( !strncmp( cl->buffer_read, "logout", 6 ) ||
423                     !strncmp( cl->buffer_read, "quit", 4 )  ||
424                     !strncmp( cl->buffer_read, "exit", 4 ) )
425                 {
426                     net_Close( cl->fd );
427                     TAB_REMOVE( p_intf->p_sys->i_clients ,
428                                 p_intf->p_sys->clients , cl );
429                     free( cl );
430                 }
431                 else if( !strncmp( cl->buffer_read, "shutdown", 8 ) )
432                 {
433                     msg_Err( p_intf, "shutdown requested" );
434                     p_intf->p_vlc->b_die = VLC_TRUE;
435                 }
436                 else
437                 {
438                     vlm_message_t *message;
439
440                     /* create a standard string */
441                     *cl->p_buffer_read = '\0';
442
443                     vlm_ExecuteCommand( p_sys->mediatheque, cl->buffer_read,
444                                         &message );
445                     Write_message( cl, message, NULL, WRITE_MODE_CMD );
446                     vlm_MessageDelete( message );
447                 }
448             }
449         }
450     }
451 }
452
453 static void Write_message( telnet_client_t *client, vlm_message_t *message,
454                            char *string_message, int i_mode )
455 {
456     char *psz_message;
457
458     client->p_buffer_read = client->buffer_read;
459     (client->p_buffer_read)[0] = 0; // if (cl->p_buffer_read)[0] = '\n'
460     if( client->buffer_write ) free( client->buffer_write );
461
462     /* generate the psz_message string */
463     if( message )
464     {
465         /* ok, look for vlm_message_t */
466         psz_message = MessageToString( message, 0 );
467     }
468     else
469     {
470         /* it is a basic string_message */
471         psz_message = strdup( string_message );
472     }
473
474     client->buffer_write = client->p_buffer_write = psz_message;
475     client->i_buffer_write = strlen( psz_message );
476     client->i_mode = i_mode;
477 }
478
479 /* We need the level of the message to put a beautiful indentation.
480  * first level is 0 */
481 static char *MessageToString( vlm_message_t *message, int i_level )
482 {
483 #define STRING_CR "\r\n"
484 #define STRING_TAIL "> "
485
486     char *psz_message;
487     int i, i_message = sizeof( STRING_TAIL );
488
489     if( !message || !message->psz_name )
490     {
491         return strdup( STRING_CR STRING_TAIL );
492     }
493     else if( !i_level && !message->i_child && !message->psz_value  )
494     {
495         /* A command is successful. Don't write anything */
496         return strdup( /*STRING_CR*/ STRING_TAIL );
497     }
498
499     i_message += strlen( message->psz_name ) + i_level * sizeof( "    " ) + 1;
500     psz_message = malloc( i_message );
501     *psz_message = 0;
502     for( i = 0; i < i_level; i++ ) strcat( psz_message, "    " );
503     strcat( psz_message, message->psz_name );
504
505     if( message->psz_value )
506     {
507         i_message += sizeof( " : " ) + strlen( message->psz_value ) +
508             sizeof( STRING_CR );
509         psz_message = realloc( psz_message, i_message );
510         strcat( psz_message, " : " );
511         strcat( psz_message, message->psz_value );
512         strcat( psz_message, STRING_CR );
513     }
514     else
515     {
516         i_message += sizeof( STRING_CR );
517         psz_message = realloc( psz_message, i_message );
518         strcat( psz_message, STRING_CR );
519     }
520
521     for( i = 0; i < message->i_child; i++ )
522     {
523         char *child_message =
524             MessageToString( message->child[i], i_level + 1 );
525
526         i_message += strlen( child_message );
527         psz_message = realloc( psz_message, i_message );
528         strcat( psz_message, child_message );
529         free( child_message );
530     }
531
532     if( i_level == 0 ) strcat( psz_message, STRING_TAIL );
533
534     return psz_message;
535 }