]> git.sesse.net Git - vlc/blob - modules/misc/audioscrobbler.c
audioscrobbler.c: fix for format string exploit
[vlc] / modules / misc / audioscrobbler.c
1 /*****************************************************************************
2  * audioscrobbler.c : audioscrobbler submission plugin
3  *****************************************************************************
4  * Copyright (C) 2006 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Rafaël Carré <funman at videolan org>
8  *          Kenneth Ostby <kenneo -at- idi -dot- ntnu -dot- no>
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 /* audioscrobbler protocol version: 1.1 
26  * http://audioscrobbler.net/wiki/Protocol1.1
27  * */
28
29 /*****************************************************************************
30  * Preamble
31  *****************************************************************************/
32
33 #define _GNU_SOURCE
34 #include <string.h>
35
36 #if defined( WIN32 )
37 #include <time.h>
38 #endif
39
40 #include <vlc/vlc.h>
41 #include <vlc_interface.h>
42 #include <vlc_meta.h>
43 #include <vlc_md5.h>
44 #include <vlc_block.h>
45 #include <vlc_stream.h>
46 #include <vlc_url.h>
47 #include <vlc_network.h>
48 #include <vlc_interface.h>
49 #include <vlc_playlist.h>
50
51 /*****************************************************************************
52  * Local prototypes
53  *****************************************************************************/
54
55 /* Keeps track of metadata to be submitted */
56 typedef struct audioscrobbler_song_t
57 {
58     char        *psz_a;                /* track artist     */
59     char        *psz_t;                /* track title      */
60     char        *psz_b;                /* track album      */
61     int         i_l;                   /* track length     */
62     char        *psz_m;                /* musicbrainz id   */
63     char        *psz_i;                /* date             */
64     time_t      time_playing;          /* date (epoch)     */
65 } audioscrobbler_song_t;
66
67
68 /* Queue to be submitted to server, 10 songs max */
69 typedef struct audioscrobbler_queue_t
70 {
71     audioscrobbler_song_t   **p_queue;      /* contains up to 10 songs        */
72     int                     i_songs_nb;     /* number of songs                */
73     void                    *p_next_queue;  /* if queue full, pointer to next */
74 } audioscrobbler_queue_t;
75
76 struct intf_sys_t
77 {
78     audioscrobbler_queue_t  *p_first_queue;     /* 1st queue              */
79     vlc_mutex_t             lock;               /* p_sys mutex            */
80
81     /* data about audioscrobbler session */
82     time_t                  time_next_exchange; /* when can we send data? */
83     char                    *psz_submit_host;   /* where to submit data ? */
84     int                     i_submit_port;      /* at which port ?        */
85     char                    *psz_submit_file;   /* in which file ?        */
86     char                    *psz_username;      /* last.fm username       */
87     vlc_bool_t              b_handshaked;       /* did we handshake ?     */
88     char                    *psz_response_md5;  /* md5 response to use    */
89
90     /* data about song currently playing */
91     audioscrobbler_song_t   *p_current_song;    /* song being played      */
92     time_t                  time_pause;         /* time when vlc paused   */
93     time_t                  time_total_pauses;  /* sum of time in pause   */
94     vlc_bool_t              b_queued;           /* has it been queud ?    */
95     vlc_bool_t              b_metadata_read;    /* did we read metadata ? */
96     vlc_bool_t              b_paused;           /* is vlc paused ?        */
97     vlc_bool_t              b_waiting_meta;     /* we need fetched data?  */
98 };
99
100 intf_sys_t *p_sys_global;     /* to retrieve p_sys in Run() thread */
101
102 static int  Open        ( vlc_object_t * );
103 static void Close       ( vlc_object_t * );
104 static void Run         ( intf_thread_t * );
105 static int ItemChange   ( vlc_object_t *, const char *, vlc_value_t,
106                                 vlc_value_t, void * );
107 static int PlayingChange( vlc_object_t *, const char *, vlc_value_t,
108                                 vlc_value_t, void * );
109 static int AddToQueue   ( intf_thread_t *p_this );
110 static int Handshake    ( intf_thread_t *p_sd );
111 static int ReadMetaData ( intf_thread_t *p_this );
112 void DeleteQueue        ( audioscrobbler_queue_t *p_queue );
113
114 /*****************************************************************************
115  * Module descriptor
116  ****************************************************************************/
117
118 #define USERNAME_TEXT       N_("Username")
119 #define USERNAME_LONGTEXT   N_("The username of your last.fm account")
120 #define PASSWORD_TEXT       N_("Password")
121 #define PASSWORD_LONGTEXT   N_("The password of your last.fm account")
122
123 /* if something goes wrong, we wait at least one minute before trying again */
124 #define DEFAULT_INTERVAL 60
125
126 /* last.fm client identifier */
127 #define CLIENT_NAME     PACKAGE
128 #define CLIENT_VERSION  VERSION
129
130 /* HTTP POST request : to submit data */
131 #define    POST_REQUEST "POST /%s HTTP/1.1\n"                               \
132                         "Accept-Encoding: identity\n"                       \
133                         "Content-length: %d\n"                              \
134                         "Connection: close\n"                               \
135                         "Content-type: application/x-www-form-urlencoded\n" \
136                         "Host: %s\n"                                        \
137                         "User-agent: VLC Media Player/%s\r\n"               \
138                         "\r\n"                                              \
139                         "%s\r\n"                                            \
140                         "\r\n"
141
142 /* data to submit */
143 #define POST_DATA       "&a%%5B%d%%5D=%s&t%%5B%d%%5D=%s&b%%5B%d%%5D=%s" \
144                         "&m%%5B%d%%5D=%s&l%%5B%d%%5D=%d&i%%5B%d%%5D=%s"
145 #define HTTPPOST_MAXLEN 2048
146
147 vlc_module_begin();
148     set_category( CAT_INTERFACE );
149     set_subcategory( SUBCAT_INTERFACE_CONTROL );
150     set_shortname( N_( "Audioscrobbler" ) );
151     set_description( N_("Audioscrobbler submission Plugin") );
152     add_string( "lastfm-username", "", NULL,
153                 USERNAME_TEXT, USERNAME_LONGTEXT, VLC_FALSE );
154     add_string( "lastfm-password", "", NULL,
155                 PASSWORD_TEXT, PASSWORD_LONGTEXT, VLC_FALSE );
156     set_capability( "interface", 0 );
157     set_callbacks( Open, Close );
158 vlc_module_end();
159
160 /*****************************************************************************
161  * Open: initialize and create stuff
162  *****************************************************************************/
163
164 static int Open( vlc_object_t *p_this )
165 {
166     playlist_t      *p_playlist;
167     intf_thread_t   *p_intf     = ( intf_thread_t* ) p_this;
168     intf_sys_t      *p_sys      = malloc( sizeof( intf_sys_t ) );
169
170 #define MEM_ERROR \
171     free( p_sys->p_current_song ); \
172     free( p_sys->p_first_queue ); \
173     free( p_sys->psz_response_md5 ); \
174     free( p_sys ); \
175     return VLC_ENOMEM;
176
177
178     if( !p_sys )
179     {
180         MEM_ERROR
181     }
182
183     p_intf->p_sys = p_sys;
184
185     vlc_mutex_init( p_this, &p_sys->lock );
186
187     p_sys_global = p_sys;
188     p_sys->psz_submit_host = NULL;
189     p_sys->psz_submit_file = NULL;
190     p_sys->b_handshaked = VLC_FALSE;
191     p_sys->time_next_exchange = time( NULL );
192     p_sys->psz_username = NULL;
193     p_sys->b_paused = VLC_FALSE;
194
195 #define MALLOC_CHECK( a ) \
196     if( !a ) { \
197         vlc_mutex_destroy( &p_sys->lock ); \
198         MEM_ERROR \
199     }
200
201     /* md5 response is 32 chars, + final \0 */
202     p_sys->psz_response_md5 = malloc( 33 );
203     MALLOC_CHECK( p_sys->psz_response_md5 )
204
205     p_sys->p_first_queue = malloc( sizeof( audioscrobbler_queue_t ) );
206     MALLOC_CHECK( p_sys->p_first_queue )
207
208     p_sys->p_current_song = malloc( sizeof( audioscrobbler_song_t ) );
209     MALLOC_CHECK( p_sys->p_current_song )
210     time( &p_sys->p_current_song->time_playing );
211
212     /* queues can't contain more than 10 songs */
213     p_sys->p_first_queue->p_queue =
214         malloc( 10 * sizeof( audioscrobbler_song_t ) );
215     MALLOC_CHECK( p_sys->p_current_song )
216
217     p_sys->p_first_queue->i_songs_nb = 0;
218     p_sys->p_first_queue->p_next_queue = NULL;
219
220     p_playlist = pl_Yield( p_intf );
221     PL_LOCK;
222     var_AddCallback( p_playlist, "playlist-current", ItemChange, p_intf );
223     PL_UNLOCK;
224     pl_Release( p_playlist );
225
226     p_intf->pf_run = Run;
227
228     return VLC_SUCCESS;
229 #undef MEM_ERROR
230 #undef MALLOC_CHECK
231 }
232
233 /*****************************************************************************
234  * Close: destroy interface stuff
235  *****************************************************************************/
236 static void Close( vlc_object_t *p_this )
237 {
238     audioscrobbler_queue_t      *p_current_queue, *p_next_queue;
239     playlist_t                  *p_playlist;
240     input_thread_t              *p_input;
241     intf_thread_t               *p_intf = ( intf_thread_t* ) p_this;
242     intf_sys_t                  *p_sys  = p_intf->p_sys;
243
244     p_playlist = pl_Yield( p_intf );
245     PL_LOCK;
246     var_DelCallback( p_playlist, "playlist-current", ItemChange, p_intf );
247
248     p_input = p_playlist->p_input;
249     if ( p_input )
250     {
251         vlc_object_yield( p_input );
252         var_DelCallback( p_input, "state", PlayingChange, p_intf );
253         vlc_object_release( p_input );
254     }
255
256     PL_UNLOCK;
257     pl_Release( p_playlist );
258
259     vlc_mutex_lock ( &p_sys->lock );
260     p_current_queue = p_sys->p_first_queue;
261     vlc_mutex_unlock ( &p_sys->lock );
262
263     while( ( p_current_queue->i_songs_nb == 10 ) &&
264         ( p_current_queue->p_next_queue != NULL ) )
265     {
266         p_next_queue = p_current_queue->p_next_queue;
267         DeleteQueue( p_current_queue );
268         free( p_current_queue );
269         p_current_queue = p_next_queue;
270     }
271
272     DeleteQueue( p_current_queue );
273     free( p_current_queue );
274
275     vlc_mutex_lock ( &p_sys->lock );
276     free( p_sys->psz_username );
277     free( p_sys->p_current_song );
278     free( p_sys->psz_submit_host );
279     free( p_sys->psz_submit_file );
280     free( p_sys->psz_response_md5 );
281     vlc_mutex_unlock ( &p_sys->lock );
282     vlc_mutex_destroy( &p_sys->lock );
283     free( p_sys );
284 }
285
286 /*****************************************************************************
287  * Run : call Handshake() then submit songs
288  *****************************************************************************/
289 static void Run( intf_thread_t *p_this )
290 {
291     char                    *psz_submit         = NULL;
292     char                    *psz_submit_song    = NULL;
293     int                     i_net_ret;
294     int                     i_song;
295     playlist_t              *p_playlist;
296     uint8_t                 *p_buffer           = NULL;
297     char                    *p_buffer_pos       = NULL;
298     audioscrobbler_queue_t  *p_first_queue;
299     int                     i_post_socket;
300     time_t                  played_time;
301
302     p_this->p_sys = p_sys_global;
303     intf_sys_t *p_sys = p_this->p_sys;
304
305     #define MEM_ERROR \
306         free( psz_submit ); \
307         free( psz_submit_song ); \
308         free( p_buffer ); \
309         msg_Err( p_this, "Out of memory" ); \
310         return;
311
312     psz_submit = malloc( HTTPPOST_MAXLEN );
313     psz_submit_song = malloc( HTTPPOST_MAXLEN );
314     p_buffer = ( uint8_t* ) malloc( 1024 );
315
316     if( !psz_submit || !psz_submit_song || !p_buffer )
317     {
318         MEM_ERROR
319     }
320
321     /* main loop */
322     while( !p_this->b_die )
323     {
324         /* verify if there is data to submit 
325          * and if waiting interval is elapsed */
326         if ( ( p_sys->p_first_queue->i_songs_nb > 0 ) &&
327             ( time( NULL ) >= p_sys->time_next_exchange ) )
328         {
329             /* handshake if needed */
330             if( p_sys->b_handshaked == VLC_FALSE )
331             {
332                 msg_Dbg( p_this, "Handshaking with last.fm ..." );
333  
334                 switch( Handshake( p_this ) )
335                 {
336                     case VLC_ENOMEM:
337                         MEM_ERROR
338                         break;
339
340                     case VLC_ENOVAR:
341                         /* username not set */
342                         vlc_mutex_unlock ( &p_sys->lock );
343                         intf_UserFatal( p_this, VLC_FALSE,
344                             _("Last.fm username not set"),
345                             _("Please set an username or disable "
346                             "audioscrobbler plugin, and then restart VLC.\n"
347                             "Visit https://www.last.fm/join/ to get an account")
348                         );
349                         free( psz_submit );
350                         free( psz_submit_song );
351                         free( p_buffer );
352                         return;
353                         break;
354
355                     case VLC_SUCCESS:
356                         msg_Dbg( p_this, "Handshake successfull :)" );
357                         vlc_mutex_lock ( &p_sys->lock );
358                         p_sys->b_handshaked = VLC_TRUE;
359                         vlc_mutex_unlock ( &p_sys->lock );
360                         break;
361
362                     case VLC_EGENERIC:
363                     default:
364                         /* protocol error : we'll try later */
365                         vlc_mutex_lock ( &p_sys->lock );
366                         time( &p_sys->time_next_exchange );
367                         p_sys->time_next_exchange += DEFAULT_INTERVAL;
368                         vlc_mutex_unlock ( &p_sys->lock );
369                         break;
370                 }
371             }
372
373             msg_Dbg( p_this, "Going to submit some data..." );
374             vlc_mutex_lock ( &p_sys->lock );
375
376             snprintf( psz_submit, HTTPPOST_MAXLEN, "u=%s&s=%s",
377                 p_sys->psz_username, p_sys->psz_response_md5 );
378
379             /* forge the HTTP POST request */
380             for (i_song = 0 ; i_song < p_sys->p_first_queue->i_songs_nb ;
381                 i_song++ )
382             {
383                 snprintf( psz_submit_song, HTTPPOST_MAXLEN -1, POST_DATA,
384                     i_song, p_sys->p_first_queue->p_queue[i_song]->psz_a,
385                     i_song, p_sys->p_first_queue->p_queue[i_song]->psz_t,
386                     i_song, p_sys->p_first_queue->p_queue[i_song]->psz_b,
387                     i_song, p_sys->p_first_queue->p_queue[i_song]->psz_m,
388                     i_song, p_sys->p_first_queue->p_queue[i_song]->i_l,
389                     i_song, p_sys->p_first_queue->p_queue[i_song]->psz_i
390                 );
391                 strncat( psz_submit, psz_submit_song, HTTPPOST_MAXLEN - 1 );
392             }
393
394             i_post_socket = net_ConnectTCP( p_this,
395                 p_sys->psz_submit_host, p_sys->i_submit_port);
396
397             /* we transmit the data */
398             i_net_ret = net_Printf(
399                 VLC_OBJECT(p_this), i_post_socket, NULL,
400                 POST_REQUEST, p_sys->psz_submit_file,
401                 strlen( psz_submit ), p_sys->psz_submit_file,
402                 VERSION, psz_submit
403             );
404
405             if ( i_net_ret == -1 )
406             {
407                 /* If connection fails, we assume we must handshake again */
408                 time( &p_sys->time_next_exchange );
409                 p_sys->time_next_exchange += DEFAULT_INTERVAL;
410                 p_sys->b_handshaked = VLC_FALSE;
411                 vlc_mutex_unlock( &p_sys->lock );
412                 continue;
413             }
414
415             memset( p_buffer, '\0', 1024 );
416
417             i_net_ret = net_Read( p_this, i_post_socket, NULL,
418                         p_buffer, 1024, VLC_FALSE );
419             if ( i_net_ret <= 0 )
420             {
421                 /* if we get no answer, something went wrong : try again */
422                 vlc_mutex_unlock( &p_sys->lock );
423                 continue;
424             }
425
426             net_Close( i_post_socket );
427
428             /* record interval */
429             p_buffer_pos = strstr( ( char * ) p_buffer, "INTERVAL" );
430             if ( p_buffer_pos )
431             {
432                 time( &p_sys->time_next_exchange );
433                 p_sys->time_next_exchange += atoi( p_buffer_pos +
434                                             strlen( "INTERVAL " ) );
435             }
436
437             p_buffer_pos = strstr( ( char * ) p_buffer, "FAILED" );
438             if ( p_buffer_pos )
439             {
440                 /* woops, submission failed */
441                 msg_Dbg( p_this, "%s", p_buffer_pos );
442                 vlc_mutex_unlock ( &p_sys->lock );
443                 continue;
444             }
445
446             p_buffer_pos = strstr( ( char * ) p_buffer, "BADAUTH" );
447             if ( p_buffer_pos )
448             {
449                 msg_Dbg( p_this, "Authentification failed, handshaking again" );
450                 p_sys->b_handshaked = VLC_FALSE;
451                 vlc_mutex_unlock ( &p_sys->lock );
452                 continue;
453             }
454
455             p_buffer_pos = strstr( ( char * ) p_buffer, "OK" );
456             if ( p_buffer_pos )
457             {
458                 if ( p_sys->p_first_queue->i_songs_nb == 10 )
459                 {
460                     /* if there are more than one queue, delete the 1st */
461                     p_first_queue = p_sys->p_first_queue->p_next_queue;
462                     DeleteQueue( p_sys->p_first_queue );
463                     free( p_sys->p_first_queue );
464                     p_sys->p_first_queue = p_first_queue;
465                 }
466                 else
467                 {
468                     DeleteQueue( p_sys->p_first_queue );
469                     p_sys->p_first_queue->i_songs_nb = 0;
470                 }
471                 msg_Dbg( p_this, "Submission successfull!" );
472             }
473             vlc_mutex_unlock ( &p_sys->lock );
474         } /* data transmission finished or skipped */
475
476         msleep( INTF_IDLE_SLEEP );
477
478         p_playlist = pl_Yield( p_this );
479         PL_LOCK;
480         if( p_playlist->request.i_status == PLAYLIST_STOPPED )
481         {
482             /* if we stopped, we won't submit playing song */
483             vlc_mutex_lock( &p_sys->lock );
484             p_sys->b_queued = VLC_TRUE;
485             p_sys->b_metadata_read = VLC_TRUE;
486             vlc_mutex_unlock( &p_sys->lock );
487         }
488         PL_UNLOCK;
489         pl_Release( p_playlist );
490
491         vlc_mutex_lock( &p_sys->lock );
492         if( p_sys->b_metadata_read == VLC_FALSE )
493         {
494             /* we read the metadata of the playing song */
495             time( &played_time );
496             played_time -= p_sys->p_current_song->time_playing;
497             played_time -= p_sys->time_total_pauses;
498
499             vlc_mutex_unlock( &p_sys->lock );
500
501             if( played_time > 20 )
502             /* wait at least 20 secondes before reading the meta data
503              * since the songs must be at least 30s */
504             {
505                 if ( ReadMetaData( p_this ) == VLC_ENOMEM )
506                 {
507                     MEM_ERROR
508                 }
509             }
510         }
511         else
512         {
513             /* we add the playing song into the queue */
514             if( ( p_sys->b_queued == VLC_FALSE )
515                 && ( p_sys->b_paused == VLC_FALSE ) )
516             {
517                 vlc_mutex_unlock( &p_sys->lock );
518                 if( AddToQueue( p_this ) == VLC_ENOMEM )
519                 {
520                     MEM_ERROR
521                 }
522             }
523             else
524             {
525                 vlc_mutex_unlock( &p_sys->lock );
526             }
527         }
528     }
529 #undef MEM_ERROR
530 }
531
532 /*****************************************************************************
533  * PlayingChange: Playing status change callback
534  *****************************************************************************/
535 static int PlayingChange( vlc_object_t *p_this, const char *psz_var,
536                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
537 {
538     intf_thread_t   *p_intf = ( intf_thread_t* ) p_data;
539     intf_sys_t      *p_sys  = p_intf->p_sys;
540
541     (void)p_this; (void)psz_var; (void)oldval;
542
543     /* don't bother if song has already been queued */
544     if( p_sys->b_queued == VLC_TRUE )
545         return VLC_SUCCESS;
546
547     vlc_mutex_lock( &p_sys->lock );
548
549     if( newval.i_int == PAUSE_S )
550     {
551         time( &p_sys->time_pause );
552         p_sys->b_paused = VLC_TRUE;
553     }
554
555     else if( newval.i_int == PLAYING_S )
556     {
557         p_sys->time_total_pauses += time( NULL ) - p_sys->time_pause;
558         p_sys->b_paused = VLC_FALSE;
559     }
560
561     vlc_mutex_unlock( &p_sys->lock );
562
563     return VLC_SUCCESS;
564 }
565
566 /*****************************************************************************
567  * ItemChange: Playlist item change callback
568  *****************************************************************************/
569 static int ItemChange( vlc_object_t *p_this, const char *psz_var,
570                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
571 {
572     playlist_t          *p_playlist;
573     input_thread_t      *p_input    = NULL;
574     time_t              epoch;
575     struct tm           *epoch_tm;
576     char                psz_date[20];
577     intf_thread_t       *p_intf     = ( intf_thread_t* ) p_data;
578     intf_sys_t          *p_sys      = p_intf->p_sys;
579     (void)p_this; (void)psz_var; (void)oldval; (void)newval;
580
581     p_playlist = pl_Yield( p_intf );
582     PL_LOCK;
583     p_input = p_playlist->p_input;
584
585     if( !p_input )
586     {
587         PL_UNLOCK;
588         pl_Release( p_playlist );
589
590         vlc_mutex_lock( &p_sys->lock );
591
592         p_sys->b_queued = VLC_TRUE;
593         p_sys->b_metadata_read = VLC_TRUE;
594
595         vlc_mutex_unlock( &p_sys->lock );
596
597         return VLC_SUCCESS;
598     }
599
600     vlc_object_yield( p_input );
601     PL_UNLOCK;
602     pl_Release( p_playlist );
603
604     var_AddCallback( p_input, "state", PlayingChange, p_intf );
605
606     vlc_mutex_lock ( &p_sys->lock );
607
608     /* reset pause counter */
609     p_sys->time_total_pauses = 0;
610
611     /* we'll read metadata when it's present */
612     p_sys->b_metadata_read = VLC_FALSE;
613     p_sys->b_waiting_meta = VLC_FALSE;
614
615     time( &epoch );
616     epoch_tm = gmtime( &epoch );
617     snprintf( psz_date, 20, "%.4d-%.2d-%.2d %.2d:%.2d:%.2d",
618         epoch_tm->tm_year+1900, epoch_tm->tm_mon+1, epoch_tm->tm_mday,
619         epoch_tm->tm_hour, epoch_tm->tm_min, epoch_tm->tm_sec );
620
621     p_sys->p_current_song->psz_i = encode_URI_component( psz_date );
622     p_sys->p_current_song->time_playing = epoch;
623
624     p_sys->b_paused = ( p_input->b_dead || !input_GetItem(p_input)->psz_name )
625                       ? VLC_TRUE : VLC_FALSE;
626
627     vlc_mutex_unlock( &p_sys->lock );
628
629     vlc_object_release( p_input );
630     return VLC_SUCCESS;
631 }
632
633 /*****************************************************************************
634  * AddToQueue: Add the played song to the queue to be submitted
635  *****************************************************************************/
636 static int AddToQueue ( intf_thread_t *p_this )
637 {
638     int                         i_songs_nb;
639     time_t                      played_time;
640     audioscrobbler_queue_t      *p_queue        = NULL,
641                                 *p_next_queue   = NULL;
642     intf_sys_t                  *p_sys          = p_this->p_sys;
643
644     /* wait for the user to listen enough before submitting */
645     time ( &played_time );
646     vlc_mutex_lock( &p_sys->lock );
647
648     played_time -= p_sys->p_current_song->time_playing;
649     played_time -= p_sys->time_total_pauses;
650
651     #define NO_SUBMISSION \
652         p_sys->b_queued = VLC_TRUE; \
653         vlc_mutex_unlock( &p_sys->lock ); \
654         return VLC_SUCCESS;
655
656     if( ( played_time < 240 ) &&
657         ( played_time < ( p_sys->p_current_song->i_l / 2 ) ) )
658     {
659         //msg_Dbg( p_this, "Song not listened long enough -> waiting" );
660         vlc_mutex_unlock( &p_sys->lock );
661         return VLC_SUCCESS;
662     }
663
664     if( p_sys->p_current_song->i_l < 30 )
665     {
666         msg_Dbg( p_this, "Song too short (< 30s) -> not submitting" );
667         NO_SUBMISSION
668     }
669
670     if( !*p_sys->p_current_song->psz_a || !*p_sys->p_current_song->psz_t )
671     {
672         msg_Dbg( p_this, "Missing artist or title -> not submitting" );
673         NO_SUBMISSION
674     }
675
676     msg_Dbg( p_this, "Ok. We'll put it in the queue for submission" );
677
678     /* go to last queue */
679     p_queue = p_sys->p_first_queue;
680     while( ( p_queue->i_songs_nb == 10 ) && ( p_queue->p_next_queue != NULL ) )
681         p_queue = p_queue->p_next_queue;
682
683     i_songs_nb = p_queue->i_songs_nb;
684
685     #define MALLOC_CHECK( a ) \
686         if( !a ) { \
687             vlc_mutex_unlock( &p_sys->lock ); \
688             return VLC_ENOMEM; \
689         }
690
691     if( i_songs_nb == 10 )
692     {
693         p_next_queue = malloc( sizeof( audioscrobbler_queue_t ) );
694         MALLOC_CHECK( p_next_queue );
695         p_queue->p_next_queue = p_next_queue;
696         p_queue = p_next_queue;
697         i_songs_nb = 0;
698         p_queue->i_songs_nb = i_songs_nb;
699     }
700
701     p_queue->p_queue[i_songs_nb] = malloc( sizeof( audioscrobbler_song_t ) );
702     MALLOC_CHECK( p_queue->p_queue[i_songs_nb] );
703
704     #define QUEUE_COPY( a ) \
705         p_queue->p_queue[i_songs_nb]->a = p_sys->p_current_song->a
706
707     QUEUE_COPY(i_l);
708     QUEUE_COPY(psz_a);
709     QUEUE_COPY(psz_t);
710     QUEUE_COPY(psz_b);
711     QUEUE_COPY(psz_m);
712     QUEUE_COPY(psz_i);
713
714     p_queue->i_songs_nb++;
715     p_sys->b_queued = VLC_TRUE;
716
717     vlc_mutex_unlock( &p_sys->lock );
718
719     return VLC_SUCCESS;
720 #undef QUEUE_COPY
721 #undef MALLOC_CHECK
722 #undef NO_SUBMISSION
723 }
724
725 /*****************************************************************************
726  * Handshake : Init audioscrobbler connection
727  *****************************************************************************/
728 static int Handshake( intf_thread_t *p_this )
729 {
730     char                *psz_password           = NULL;
731     struct md5_s        *p_struct_md5           = NULL;
732     char                *psz_password_md5       = NULL;
733     char                *ps_challenge_md5       = NULL;
734     stream_t            *p_stream;
735     char                *psz_handshake_url      = NULL;
736     uint8_t             *p_buffer               = NULL;
737     char                *p_buffer_pos           = NULL; 
738     char                *psz_url_parser         = NULL;
739     char                *psz_buffer_substring;
740     int                 i_url_pos, i;
741
742     intf_thread_t       *p_intf                 = ( intf_thread_t* ) p_this;
743     intf_sys_t          *p_sys                  = p_this->p_sys;
744
745     vlc_mutex_lock ( &p_sys->lock );
746
747     #define MEM_ERROR \
748         free( p_buffer ); \
749         free( p_struct_md5 ); \
750         free( ps_challenge_md5 ); \
751         vlc_mutex_unlock( &p_sys->lock ); \
752         return VLC_ENOMEM;
753
754     #define PROTOCOL_ERROR \
755         free( p_buffer ); \
756         vlc_mutex_unlock( &p_sys->lock ); \
757         return VLC_EGENERIC;
758
759     #define MALLOC_CHECK( a ) \
760         if( !a ) \
761         { \
762             MEM_ERROR \
763         }
764
765     p_sys->psz_username = config_GetPsz(p_this, "lastfm-username");
766     MALLOC_CHECK( p_sys->psz_username )
767
768     /* username has not been setup, ignoring */
769     if ( !*p_sys->psz_username )
770         return VLC_ENOVAR;
771
772     psz_handshake_url = malloc( 1024 );
773     MALLOC_CHECK( p_sys->psz_username )
774
775     snprintf( psz_handshake_url, 1024,
776         "http://post.audioscrobbler.com/?hs=true&p=1.1&c=%s&v=%s&u=%s",
777         CLIENT_NAME, CLIENT_VERSION, p_sys->psz_username );
778
779     /* send the http handshake request */
780     p_stream = stream_UrlNew( p_intf, psz_handshake_url);
781
782     free( psz_handshake_url );
783
784     if( !p_stream )
785     {
786         vlc_mutex_unlock ( &p_sys->lock );
787         return VLC_EGENERIC;
788     }
789
790     p_buffer = ( uint8_t* ) calloc( 1, 1024 );
791     if ( !p_buffer )
792     {
793         stream_Delete( p_stream );
794         MEM_ERROR
795     }
796
797     /* read answer */
798     if ( stream_Read( p_stream, p_buffer, 1024 ) == 0 )
799     {
800         stream_Delete( p_stream );
801         PROTOCOL_ERROR
802     }
803
804     stream_Delete( p_stream );
805
806     /* record interval before next submission */
807     p_buffer_pos = strstr( ( char* ) p_buffer, "INTERVAL" );
808     if ( p_buffer_pos )
809     {
810         time( &p_sys->time_next_exchange );
811         p_sys->time_next_exchange +=
812                 atoi( p_buffer_pos + strlen( "INTERVAL " ) );
813     }
814
815     p_buffer_pos = strstr( ( char* ) p_buffer, "FAILED" );
816     if ( p_buffer_pos )
817     {
818         /* handshake request failed, sorry */
819         msg_Dbg( p_this, "%s", p_buffer_pos );
820         PROTOCOL_ERROR
821     }
822
823     p_buffer_pos = strstr( ( char* ) p_buffer, "BADUSER" );
824     if ( p_buffer_pos )
825     {
826         /* username does not exist on the server */
827         intf_UserFatal( p_this, VLC_FALSE, _("Bad last.fm Username"),
828             _("last.fm username is incorrect, please verify your settings")
829         );
830         PROTOCOL_ERROR
831     }
832
833     p_buffer_pos = strstr( ( char* ) p_buffer, "UPDATE" );
834     if ( p_buffer_pos )
835     {
836         /* protocol has been updated, time to update the code */
837         msg_Dbg( p_intf, "Protocol updated : plugin may be outdated" );
838         msg_Dbg( p_intf, "%s", p_buffer_pos );
839     }
840
841     else
842     {
843         p_buffer_pos = strstr( ( char* ) p_buffer, "UPTODATE" );
844         if ( !p_buffer_pos )
845         {
846             msg_Dbg( p_intf, "Can't recognize server protocol" );
847             PROTOCOL_ERROR
848         }
849     }
850
851     psz_buffer_substring = strstr( p_buffer_pos, "\n" );
852     if( ( psz_buffer_substring == NULL ) || \
853             ( strlen( psz_buffer_substring + 1 ) < 32 ) )
854     {
855         msg_Dbg( p_intf, "Can't recognize server protocol" );
856         PROTOCOL_ERROR
857     }
858     else
859     {
860         ps_challenge_md5 = malloc( 32 );
861         MALLOC_CHECK( ps_challenge_md5 )
862         memcpy( ps_challenge_md5, psz_buffer_substring + 1, 32 );
863     }
864
865     p_buffer_pos = ( void* ) strstr( ( char* ) p_buffer, "http://" );
866
867     /* free old information */
868     free( p_sys->psz_submit_host );
869     free( p_sys->psz_submit_file );
870
871     psz_url_parser = p_buffer_pos + strlen( "http://" );
872     i_url_pos = strcspn( psz_url_parser, ":" );
873
874     p_sys->psz_submit_host = strndup( psz_url_parser, i_url_pos );
875     MALLOC_CHECK( p_sys->psz_submit_host )
876
877     p_sys->i_submit_port = atoi( psz_url_parser + i_url_pos + 1 );
878
879     psz_url_parser += strcspn( psz_url_parser , "/" ) + 1;
880     i_url_pos = strcspn( psz_url_parser, "\n" );
881     p_sys->psz_submit_file = strndup( psz_url_parser, i_url_pos );
882     MALLOC_CHECK( p_sys->psz_submit_file )
883
884     free(p_buffer);
885
886     p_struct_md5 = malloc( sizeof( struct md5_s ) );
887     MALLOC_CHECK( p_struct_md5 )
888
889     psz_password = config_GetPsz(p_this, "lastfm-password");
890     MALLOC_CHECK( psz_password )
891
892     /* generates a md5 hash of the password */
893     InitMD5( p_struct_md5 );
894     AddMD5( p_struct_md5, ( uint8_t* ) psz_password, strlen( psz_password ) );
895     EndMD5( p_struct_md5 );
896
897     free( psz_password );
898
899     psz_password_md5 = malloc ( 33 );
900     MALLOC_CHECK( psz_password_md5 )
901
902     for ( i = 0; i < 4; i++ )
903     {
904         sprintf( &psz_password_md5[8*i], "%02x%02x%02x%02x",
905             p_struct_md5->p_digest[i] & 0xff,
906             ( p_struct_md5->p_digest[i] >> 8 ) & 0xff,
907             ( p_struct_md5->p_digest[i] >> 16 ) & 0xff,
908             p_struct_md5->p_digest[i] >> 24
909         );
910     }
911
912     /* generates a md5 hash of :
913      * - md5 hash of the password, plus
914      * - md5 challenge sent by last.fm server
915      */
916     InitMD5( p_struct_md5 );
917     AddMD5( p_struct_md5, ( uint8_t* ) psz_password_md5, 32 );
918     AddMD5( p_struct_md5, ( uint8_t* ) ps_challenge_md5, 32 );
919     EndMD5( p_struct_md5 );
920
921     free( ps_challenge_md5 );
922     free( psz_password_md5 );
923
924     for ( i = 0; i < 4; i++ )
925     {
926         sprintf( &p_sys->psz_response_md5[8*i], "%02x%02x%02x%02x",
927             p_struct_md5->p_digest[i] & 0xff,
928             ( p_struct_md5->p_digest[i] >> 8 ) & 0xff,
929             ( p_struct_md5->p_digest[i] >> 16 ) & 0xff,
930             p_struct_md5->p_digest[i] >> 24
931         );
932     }
933
934     p_sys->psz_response_md5[32] = '\0';
935
936     vlc_mutex_unlock ( &p_sys->lock );
937
938     return VLC_SUCCESS;
939 #undef MEM_ERROR
940 #undef PROTOCOL_ERROR
941 #undef MALLOC_CHECK
942 }
943
944 /*****************************************************************************
945  * DeleteQueue : Free all songs from an audioscrobbler_queue_t
946  *****************************************************************************/
947 void DeleteQueue( audioscrobbler_queue_t *p_queue )
948 {
949     int     i;
950
951     for( i = 0; i < p_queue->i_songs_nb; i++ )
952     {
953         free( p_queue->p_queue[i]->psz_a );
954         free( p_queue->p_queue[i]->psz_b );
955         free( p_queue->p_queue[i]->psz_t );
956         free( p_queue->p_queue[i]->psz_i );
957         free( p_queue->p_queue[i] );
958     }
959 }
960
961 /*****************************************************************************
962  * ReadMetaData : Read meta data when parsed by vlc
963  * or wait for fetching if unavailable
964  *****************************************************************************/
965 static int ReadMetaData( intf_thread_t *p_this )
966 {
967     playlist_t          *p_playlist;
968     input_thread_t      *p_input        = NULL;
969     vlc_value_t         video_val;
970
971     char                *psz_title      = NULL;
972     char                *psz_artist     = NULL;
973     char                *psz_album      = NULL;
974     char                *psz_trackid    = NULL;
975     int                 i_length        = -1;
976     vlc_bool_t          b_waiting;
977     intf_sys_t          *p_sys          = p_this->p_sys;
978     int                 i_status;
979
980     p_playlist = pl_Yield( p_this );
981     PL_LOCK;
982     p_input = p_playlist->p_input;
983
984     if( !p_input )
985     {
986         PL_UNLOCK;
987         pl_Release( p_playlist );
988         return( VLC_SUCCESS );
989     }
990
991     vlc_object_yield( p_input );
992     PL_UNLOCK;
993     pl_Release( p_playlist );
994
995     var_Change( p_input, "video-es", VLC_VAR_CHOICESCOUNT, &video_val, NULL );
996     if( ( video_val.i_int > 0 ) || \
997         ( input_GetItem(p_input)->i_type == ITEM_TYPE_NET ) )
998     {
999         msg_Dbg( p_this, "Not an audio only local file -> no submission");
1000         vlc_object_release( p_input );
1001
1002         vlc_mutex_lock( &p_sys->lock );
1003         p_sys->b_queued = VLC_TRUE;
1004         p_sys->b_metadata_read = VLC_TRUE;
1005         vlc_mutex_unlock( &p_sys->lock );
1006
1007         return VLC_SUCCESS;
1008     }
1009
1010     #define FREE_INPUT_AND_CHARS \
1011         vlc_object_release( p_input ); \
1012         free( psz_title ); \
1013         free( psz_artist ); \
1014         free( psz_album ); \
1015         free( psz_trackid );
1016
1017     #define WAIT_METADATA_FETCHING( a ) \
1018         if ( b_waiting == VLC_TRUE ) \
1019         { \
1020             a = calloc( 1, 1 ); \
1021         } \
1022         else \
1023         { \
1024             vlc_object_release( p_input ); \
1025             vlc_mutex_lock( &p_sys->lock ); \
1026             p_sys->b_waiting_meta = VLC_TRUE; \
1027             vlc_mutex_unlock( &p_sys->lock ); \
1028             free( psz_artist ); \
1029             return VLC_SUCCESS; \
1030         }
1031
1032     #define ALLOC_ITEM_META( a, b ) \
1033         if ( input_GetItem(p_input)->b ) \
1034         { \
1035             a = encode_URI_component( \
1036                 input_GetItem(p_input)->b ); \
1037             if( !a ) \
1038             { \
1039                 FREE_INPUT_AND_CHARS \
1040                 return VLC_ENOMEM; \
1041             } \
1042         }
1043
1044     i_status = input_GetItem(p_input)->p_meta->i_status;
1045
1046     b_waiting = VLC_TRUE;
1047 /*  TODO: meta data fetching doesn't work atm
1048     vlc_mutex_lock( &p_sys->lock );
1049     b_waiting = p_sys->b_waiting_meta;
1050     vlc_mutex_unlock( &p_sys->lock );
1051 */
1052
1053     /* TODO: item preparsing is buggy on drag&drop and command line arguments
1054     if( i_status & ( !b_waiting ? ITEM_PREPARSED : ITEM_META_FETCHED ) )
1055     */
1056     if( 1 )
1057     {
1058         ALLOC_ITEM_META( psz_artist, p_meta->psz_artist )
1059         else
1060         {
1061             msg_Dbg( p_this, "No artist.." );
1062             WAIT_METADATA_FETCHING( psz_artist )
1063         }
1064
1065         ALLOC_ITEM_META( psz_title, psz_name )
1066         else
1067         {
1068             msg_Dbg( p_this, "No track name.." );
1069             WAIT_METADATA_FETCHING( psz_title );
1070         }
1071
1072         ALLOC_ITEM_META( psz_album, p_meta->psz_album )
1073         else
1074             psz_album = calloc( 1, 1 );
1075
1076         ALLOC_ITEM_META( psz_trackid, p_meta->psz_trackid )
1077         else
1078             psz_trackid = calloc( 1, 1 );
1079
1080         i_length = input_GetItem(p_input)->i_duration / 1000000;
1081
1082         vlc_mutex_lock ( &p_sys->lock );
1083
1084         p_sys->p_current_song->psz_a    = strdup( psz_artist );
1085         p_sys->p_current_song->psz_t    = strdup( psz_title );
1086         p_sys->p_current_song->psz_b    = strdup( psz_album );
1087         p_sys->p_current_song->psz_m    = strdup( psz_trackid );
1088         p_sys->p_current_song->i_l      = i_length;
1089         p_sys->b_queued                 = VLC_FALSE;
1090         p_sys->b_metadata_read          = VLC_TRUE;
1091
1092         vlc_mutex_unlock( &p_sys->lock );
1093
1094         msg_Dbg( p_this, "Meta data registered, waiting to be queued" );
1095     }
1096    
1097     FREE_INPUT_AND_CHARS 
1098     return VLC_SUCCESS;
1099 #undef FREE_INPUT_AND_CHARS
1100 #undef ALLOC_ITEM_META
1101 #undef WAIT_METADATA_FETCHING
1102 }