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