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