Forward port of 'Telnet: fix win32 work'.
[vlc.git] / modules / control / telnet.c
1 /*****************************************************************************
2  * telnet.c: VLM interface plugin
3  *****************************************************************************
4  * Copyright (C) 2000-2006 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
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <vlc_common.h>
34 #include <vlc_plugin.h>
35 #include <vlc_interface.h>
36 #include <vlc_input.h>
37
38 #include <stdbool.h>
39 #include <sys/stat.h>
40
41 #include <errno.h>
42 #include <fcntl.h>
43
44 #ifdef HAVE_SYS_TIME_H
45 #    include <sys/time.h>
46 #endif
47
48 #ifdef HAVE_UNISTD_H
49 #   include <unistd.h>
50 #endif
51 #ifdef HAVE_POLL
52 #   include <poll.h>
53 #endif
54
55 #include <vlc_network.h>
56 #include <vlc_url.h>
57 #include <vlc_vlm.h>
58
59 #define READ_MODE_PWD 1
60 #define READ_MODE_CMD 2
61 #define WRITE_MODE_PWD 3 // when we write the word "Password:"
62 #define WRITE_MODE_CMD 4
63
64 /* telnet commands */
65 #define TEL_WILL    251
66 #define TEL_WONT    252
67 #define TEL_DO      253
68 #define TEL_DONT    254
69 #define TEL_IAC     255
70 #define TEL_ECHO    1
71
72 /*****************************************************************************
73  * Module descriptor
74  *****************************************************************************/
75 static int  Open ( vlc_object_t * );
76 static void Close( vlc_object_t * );
77
78 #define TELNETHOST_TEXT N_( "Host" )
79 #define TELNETHOST_LONGTEXT N_( "This is the host on which the " \
80     "interface will listen. It defaults to all network interfaces (0.0.0.0)." \
81     " If you want this interface to be available only on the local " \
82     "machine, enter \"127.0.0.1\"." )
83 #define TELNETPORT_TEXT N_( "Port" )
84 #define TELNETPORT_LONGTEXT N_( "This is the TCP port on which this " \
85     "interface will listen. It defaults to 4212." )
86 #define TELNETPORT_DEFAULT 4212
87 #define TELNETPWD_TEXT N_( "Password" )
88 #define TELNETPWD_LONGTEXT N_( "A single administration password is used " \
89     "to protect this interface. The default value is \"admin\"." )
90 #define TELNETPWD_DEFAULT "admin"
91
92 vlc_module_begin ()
93     set_shortname( "Telnet" )
94     set_category( CAT_INTERFACE )
95     set_subcategory( SUBCAT_INTERFACE_CONTROL )
96     add_string( "telnet-host", "", NULL, TELNETHOST_TEXT,
97                  TELNETHOST_LONGTEXT, true );
98     add_integer( "telnet-port", TELNETPORT_DEFAULT, NULL, TELNETPORT_TEXT,
99                  TELNETPORT_LONGTEXT, true );
100     add_password( "telnet-password", TELNETPWD_DEFAULT, NULL, TELNETPWD_TEXT,
101                 TELNETPWD_LONGTEXT, true );
102     set_description( N_("VLM remote control interface") )
103     add_category_hint( "VLM", NULL, false )
104     set_capability( "interface", 0 )
105     set_callbacks( Open , Close )
106 vlc_module_end ()
107
108 /*****************************************************************************
109  * Local prototypes.
110  *****************************************************************************/
111 static void Run( intf_thread_t * );
112
113 typedef struct
114 {
115     int        i_mode; /* read or write */
116     int        fd;
117     char       buffer_read[1000]; // 1000 byte per command should be sufficient
118     char      *buffer_write;
119     char      *p_buffer_read;
120     char      *p_buffer_write; // the position in the buffer
121     int        i_buffer_write; // the number of byte we still have to send
122     int        i_tel_cmd; // for specific telnet commands
123
124 } telnet_client_t;
125
126 static char *MessageToString( vlm_message_t *, int );
127 static void Write_message( telnet_client_t *, vlm_message_t *, const char *, int );
128
129 struct intf_sys_t
130 {
131    telnet_client_t **clients;
132    int             i_clients;
133    int             *pi_fd;
134    vlm_t           *mediatheque;
135 };
136
137 /*
138  * getPort: Decide which port to use. There are two possibilities to
139  * specify a port: integrated in the --telnet-host option with :PORT
140  * or using the --telnet-port option. The --telnet-port option has
141  * precedence.
142  * This code relies upon the fact the url.i_port is 0 if the :PORT
143  * option is missing from --telnet-host.
144  */
145 static int getPort(intf_thread_t *p_intf, const vlc_url_t *url, int i_port)
146 {
147     if (i_port == TELNETPORT_DEFAULT && url->i_port != 0)
148         i_port = url->i_port;
149     if (url->i_port != 0 && url->i_port != i_port)
150         // Print error if two different ports have been specified
151         msg_Warn( p_intf, "ignoring port %d (using %d)", url->i_port, i_port );
152     return i_port;
153 }
154
155 /*****************************************************************************
156  * Open: initialize dummy interface
157  *****************************************************************************/
158 static int Open( vlc_object_t *p_this )
159 {
160     intf_thread_t *p_intf = (intf_thread_t*) p_this;
161     vlm_t *mediatheque;
162     char *psz_address;
163     vlc_url_t url;
164     int i_telnetport;
165
166     if( !(mediatheque = vlm_New( p_intf )) )
167     {
168         msg_Err( p_intf, "cannot start VLM" );
169         return VLC_EGENERIC;
170     }
171
172     msg_Info( p_intf, "using the VLM interface plugin..." );
173
174     i_telnetport = config_GetInt( p_intf, "telnet-port" );
175     psz_address  = config_GetPsz( p_intf, "telnet-host" );
176
177     vlc_UrlParse(&url, psz_address, 0);
178     free( psz_address );
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 )
186     {
187         vlm_Delete( mediatheque );
188         vlc_UrlClean( &url );
189         return VLC_ENOMEM;
190     }
191     if( ( p_intf->p_sys->pi_fd = net_ListenTCP( p_intf, url.psz_host, url.i_port ) ) == NULL )
192     {
193         msg_Err( p_intf, "cannot listen for telnet" );
194         vlm_Delete( mediatheque );
195         vlc_UrlClean( &url );
196         free( p_intf->p_sys );
197         return VLC_EGENERIC;
198     }
199     msg_Info( p_intf,
200               "telnet interface started on interface %s %d",
201               url.psz_host, url.i_port );
202
203     p_intf->p_sys->i_clients   = 0;
204     p_intf->p_sys->clients     = NULL;
205     p_intf->p_sys->mediatheque = mediatheque;
206     p_intf->pf_run = Run;
207
208     vlc_UrlClean( &url );
209     return VLC_SUCCESS;
210 }
211
212 /*****************************************************************************
213  * Close:
214  *****************************************************************************/
215 static void Close( vlc_object_t *p_this )
216 {
217     intf_thread_t *p_intf = (intf_thread_t*)p_this;
218     intf_sys_t    *p_sys  = p_intf->p_sys;
219     int i;
220
221     for( i = 0; i < p_sys->i_clients; i++ )
222     {
223         telnet_client_t *cl = p_sys->clients[i];
224         net_Close( cl->fd );
225         free( cl->buffer_write );
226         free( cl );
227     }
228     free( p_sys->clients );
229
230     net_ListenClose( p_sys->pi_fd );
231
232     vlm_Delete( p_sys->mediatheque );
233
234     free( p_sys );
235 }
236
237 /*****************************************************************************
238  * Run: main loop
239  *****************************************************************************/
240 static void Run( intf_thread_t *p_intf )
241 {
242     intf_sys_t     *p_sys = p_intf->p_sys;
243     char           *psz_password;
244     unsigned        nlisten = 0;
245
246     for (const int *pfd = p_sys->pi_fd; *pfd != -1; pfd++)
247         nlisten++; /* How many listening sockets do we have? */
248
249     /* FIXME: make sure config_* is cancel-safe */
250     psz_password = config_GetPsz( p_intf, "telnet-password" );
251     vlc_cleanup_push( free, psz_password );
252
253     for( ;; )
254     {
255         unsigned ncli = p_sys->i_clients;
256         struct pollfd ufd[ncli + nlisten];
257
258         for (unsigned i = 0; i < ncli; i++)
259         {
260             telnet_client_t *cl = p_sys->clients[i];
261
262             ufd[i].fd = cl->fd;
263             if( (cl->i_mode == WRITE_MODE_PWD) || (cl->i_mode == WRITE_MODE_CMD) )
264                 ufd[i].events = POLLOUT;
265             else
266                 ufd[i].events = POLLIN;
267             ufd[i].revents = 0;
268         }
269
270         for (unsigned i = 0; i < nlisten; i++)
271         {
272             ufd[ncli + i].fd = p_sys->pi_fd[i];
273             ufd[ncli + i].events = POLLIN;
274             ufd[ncli + i].revents = 0;
275         }
276
277         switch (poll (ufd, sizeof (ufd) / sizeof (ufd[0]), -1))
278         {
279             case -1:
280                 if (net_errno != EINTR)
281                 {
282                     msg_Err (p_intf, "network poll error");
283                     msleep (1000);
284                     continue;
285                 }
286             case 0:
287                 continue;
288         }
289
290         int canc = vlc_savecancel ();
291         /* check if there is something to do with the socket */
292         for (unsigned i = 0; i < ncli; i++)
293         {
294             telnet_client_t *cl = p_sys->clients[i];
295
296             if (ufd[i].revents & (POLLERR|POLLHUP))
297             {
298             drop:
299                 net_Close( cl->fd );
300                 TAB_REMOVE( p_intf->p_sys->i_clients ,
301                             p_intf->p_sys->clients , cl );
302                 free( cl->buffer_write );
303                 free( cl );
304                 continue;
305             }
306
307             if (ufd[i].revents & POLLOUT && (cl->i_buffer_write > 0))
308             {
309                 ssize_t i_len;
310
311                 i_len = send( cl->fd, cl->p_buffer_write ,
312                               cl->i_buffer_write, 0 );
313                 if( i_len > 0 )
314                 {
315                     cl->p_buffer_write += i_len;
316                     cl->i_buffer_write -= i_len;
317                 }
318             }
319             if (ufd[i].revents & POLLIN)
320             {
321                 bool end = false;
322                 ssize_t i_recv;
323
324                 while( ((i_recv=recv( cl->fd, cl->p_buffer_read, 1, 0 )) > 0) &&
325                        ((cl->p_buffer_read - cl->buffer_read) < 999) )
326                 {
327                     switch( cl->i_tel_cmd )
328                     {
329                     case 0:
330                         switch( *(uint8_t *)cl->p_buffer_read )
331                         {
332                         case '\r':
333                             break;
334                         case '\n':
335                             *cl->p_buffer_read = '\n';
336                             end = true;
337                             break;
338                         case TEL_IAC: // telnet specific command
339                             cl->i_tel_cmd = 1;
340                             cl->p_buffer_read++;
341                             break;
342                         default:
343                             cl->p_buffer_read++;
344                             break;
345                         }
346                         break;
347                     case 1:
348                         switch( *(uint8_t *)cl->p_buffer_read )
349                         {
350                         case TEL_WILL: case TEL_WONT:
351                         case TEL_DO: case TEL_DONT:
352                             cl->i_tel_cmd++;
353                             cl->p_buffer_read++;
354                             break;
355                         default:
356                             cl->i_tel_cmd = 0;
357                             cl->p_buffer_read--;
358                             break;
359                         }
360                         break;
361                     case 2:
362                         cl->i_tel_cmd = 0;
363                         cl->p_buffer_read -= 2;
364                         break;
365                     }
366
367                     if( end ) break;
368                 }
369
370                 if( (cl->p_buffer_read - cl->buffer_read) == 999 )
371                 {
372                     Write_message( cl, NULL, "Line too long\r\n",
373                                    cl->i_mode + 2 );
374                 }
375
376 #ifdef WIN32
377                 if( i_recv <= 0 && WSAGetLastError() == WSAEWOULDBLOCK )
378                 {
379                     errno = EAGAIN;
380                 }
381 #endif
382                 if (i_recv <= 0 && ( end || errno != EAGAIN ) )
383                     goto drop;
384             }
385         }
386
387         /* and now we should bidouille the data we received / send */
388         for(int i = 0 ; i < p_sys->i_clients ; i++ )
389         {
390             telnet_client_t *cl = p_sys->clients[i];
391
392             if( cl->i_mode >= WRITE_MODE_PWD && cl->i_buffer_write == 0 )
393             {
394                // we have finished to send
395                cl->i_mode -= 2; // corresponding READ MODE
396             }
397             else if( cl->i_mode == READ_MODE_PWD &&
398                      *cl->p_buffer_read == '\n' )
399             {
400                 *cl->p_buffer_read = '\0';
401                 if( !psz_password || !strcmp( psz_password, cl->buffer_read ) )
402                 {
403                     Write_message( cl, NULL, "\xff\xfc\x01\r\nWelcome, "
404                                    "Master\r\n> ", WRITE_MODE_CMD );
405                 }
406                 else
407                 {
408                     /* wrong password */
409                     Write_message( cl, NULL,
410                                    "\r\nWrong password.\r\nPassword: ",
411                                    WRITE_MODE_PWD );
412                 }
413             }
414             else if( cl->i_mode == READ_MODE_CMD &&
415                      *cl->p_buffer_read == '\n' )
416             {
417                 /* ok, here is a command line */
418                 if( !strncmp( cl->buffer_read, "logout", 6 ) ||
419                     !strncmp( cl->buffer_read, "quit", 4 )  ||
420                     !strncmp( cl->buffer_read, "exit", 4 ) )
421                 {
422                     net_Close( cl->fd );
423                     TAB_REMOVE( p_intf->p_sys->i_clients ,
424                                 p_intf->p_sys->clients , cl );
425                     free( cl->buffer_write );
426                     free( cl );
427                 }
428                 else if( !strncmp( cl->buffer_read, "shutdown", 8 ) )
429                 {
430                     msg_Err( p_intf, "shutdown requested" );
431                     vlc_object_kill( p_intf->p_libvlc );
432                 }
433                 else if( *cl->buffer_read == '@'
434                           && strchr( cl->buffer_read, ' ' ) )
435                 {
436                     /* Module specific commands (use same syntax as in the
437                      * rc interface) */
438                     char *psz_name = cl->buffer_read + 1;
439                     char *psz_cmd, *psz_arg, *psz_msg;
440                     int i_ret;
441
442                     psz_cmd = strchr( cl->buffer_read, ' ' );
443                     *psz_cmd = '\0';  psz_cmd++;
444                     if( ( psz_arg = strchr( psz_cmd, '\n' ) ) ) *psz_arg = '\0';
445                     if( ( psz_arg = strchr( psz_cmd, '\r' ) ) ) *psz_arg = '\0';
446                     if( ( psz_arg = strchr( psz_cmd, ' ' ) )
447                         && *psz_arg )
448                     {
449                         *psz_arg = '\0';
450                         psz_arg++;
451                     }
452
453                     i_ret = var_Command( p_intf, psz_name, psz_cmd, psz_arg,
454                                          &psz_msg );
455
456                     if( psz_msg )
457                     {
458                         vlm_message_t *message;
459                         message = vlm_MessageNew( "Module command", psz_msg );
460                         Write_message( cl, message, NULL, WRITE_MODE_CMD );
461                         vlm_MessageDelete( message );
462                         free( psz_msg );
463                     }
464                 }
465                 else
466                 {
467                     vlm_message_t *message;
468
469                     /* create a standard string */
470                     *cl->p_buffer_read = '\0';
471
472                     vlm_ExecuteCommand( p_sys->mediatheque, cl->buffer_read,
473                                         &message );
474                     if( !strncmp( cl->buffer_read, "help", 4 ) )
475                     {
476                         vlm_message_t *p_my_help =
477                             vlm_MessageNew( "Telnet Specific Commands:", NULL );
478                         vlm_MessageAdd( p_my_help,
479                             vlm_MessageNew( "logout, quit, exit" , NULL ) );
480                         vlm_MessageAdd( p_my_help,
481                             vlm_MessageNew( "shutdown" , NULL ) );
482                         vlm_MessageAdd( p_my_help,
483                             vlm_MessageNew( "@moduleinstance command argument",
484                                              NULL) );
485                         vlm_MessageAdd( message, p_my_help );
486                     }
487                     Write_message( cl, message, NULL, WRITE_MODE_CMD );
488                     vlm_MessageDelete( message );
489                 }
490             }
491         }
492
493         /* handle new connections */
494         for (unsigned i = 0; i < nlisten; i++)
495         {
496             int fd;
497
498             if (ufd[ncli + i].revents == 0)
499                 continue;
500
501             fd = net_AcceptSingle (VLC_OBJECT(p_intf), ufd[ncli + i].fd);
502             if (fd == -1)
503                 continue;
504
505             telnet_client_t *cl = malloc( sizeof( telnet_client_t ));
506             if (cl == NULL)
507             {
508                 net_Close (fd);
509                 continue;
510             }
511
512             memset( cl, 0, sizeof(telnet_client_t) );
513             cl->i_tel_cmd = 0;
514             cl->fd = fd;
515             cl->buffer_write = NULL;
516             cl->p_buffer_write = cl->buffer_write;
517             Write_message( cl, NULL,
518                            "Password: \xff\xfb\x01" , WRITE_MODE_PWD );
519             TAB_APPEND( p_sys->i_clients, p_sys->clients, cl );
520         }
521         vlc_restorecancel( canc );
522     }
523     vlc_cleanup_run ();
524 }
525
526 static void Write_message( telnet_client_t *client, vlm_message_t *message,
527                            const char *string_message, int i_mode )
528 {
529     char *psz_message;
530
531     client->p_buffer_read = client->buffer_read;
532     (client->p_buffer_read)[0] = 0; // if (cl->p_buffer_read)[0] = '\n'
533     free( client->buffer_write );
534
535     /* generate the psz_message string */
536     if( message )
537     {
538         /* ok, look for vlm_message_t */
539         psz_message = MessageToString( message, 0 );
540     }
541     else
542     {
543         /* it is a basic string_message */
544         psz_message = strdup( string_message );
545     }
546
547     client->buffer_write = client->p_buffer_write = psz_message;
548     client->i_buffer_write = strlen( psz_message );
549     client->i_mode = i_mode;
550 }
551
552 /* We need the level of the message to put a beautiful indentation.
553  * first level is 0 */
554 static char *MessageToString( vlm_message_t *message, int i_level )
555 {
556 #define STRING_CR "\r\n"
557 #define STRING_TAIL "> "
558
559     char *psz_message;
560     int i, i_message = sizeof( STRING_TAIL );
561
562     if( !message || !message->psz_name )
563     {
564         return strdup( STRING_CR STRING_TAIL );
565     }
566     else if( !i_level && !message->i_child && !message->psz_value  )
567     {
568         /* A command is successful. Don't write anything */
569         return strdup( /*STRING_CR*/ STRING_TAIL );
570     }
571
572     i_message += strlen( message->psz_name ) + i_level * sizeof( "    " ) + 1;
573     psz_message = malloc( i_message );
574     *psz_message = 0;
575     for( i = 0; i < i_level; i++ ) strcat( psz_message, "    " );
576     strcat( psz_message, message->psz_name );
577
578     if( message->psz_value )
579     {
580         i_message += sizeof( " : " ) + strlen( message->psz_value ) +
581             sizeof( STRING_CR );
582         psz_message = realloc( psz_message, i_message );
583         strcat( psz_message, " : " );
584         strcat( psz_message, message->psz_value );
585         strcat( psz_message, STRING_CR );
586     }
587     else
588     {
589         i_message += sizeof( STRING_CR );
590         psz_message = realloc( psz_message, i_message );
591         strcat( psz_message, STRING_CR );
592     }
593
594     for( i = 0; i < message->i_child; i++ )
595     {
596         char *child_message =
597             MessageToString( message->child[i], i_level + 1 );
598
599         i_message += strlen( child_message );
600         psz_message = realloc( psz_message, i_message );
601         strcat( psz_message, child_message );
602         free( child_message );
603     }
604
605     if( i_level == 0 ) strcat( psz_message, STRING_TAIL );
606
607     return psz_message;
608 }