]> git.sesse.net Git - vlc/blob - src/misc/messages.c
Deliver log messages synchronously to subscribers
[vlc] / src / misc / messages.c
1 /*****************************************************************************
2  * messages.c: messages interface
3  * This library provides an interface to the message queue to be used by other
4  * modules, especially intf modules. See vlc_config.h for output configuration.
5  *****************************************************************************
6  * Copyright (C) 1998-2005 the VideoLAN team
7  * $Id$
8  *
9  * Authors: Vincent Seguin <seguin@via.ecp.fr>
10  *          Samuel Hocevar <sam@zoy.org>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30
31 #ifdef HAVE_CONFIG_H
32 # include "config.h"
33 #endif
34
35 #include <vlc_common.h>
36
37 #include <stdarg.h>                                       /* va_list for BSD */
38
39 #ifdef HAVE_FCNTL_H
40 #   include <fcntl.h>                  /* O_CREAT, O_TRUNC, O_WRONLY, O_SYNC */
41 #endif
42
43 #include <errno.h>                                                  /* errno */
44
45 #ifdef WIN32
46 #   include <vlc_network.h>          /* 'net_strerror' and 'WSAGetLastError' */
47 #endif
48
49 #ifdef HAVE_UNISTD_H
50 #   include <unistd.h>                                   /* close(), write() */
51 #endif
52
53 #include <assert.h>
54
55 #include <vlc_charset.h>
56 #include "../libvlc.h"
57
58 typedef struct
59 {
60     int i_code;
61     char * psz_message;
62 } msg_context_t;
63
64 static void cleanup_msg_context (void *data)
65 {
66     msg_context_t *ctx = data;
67     free (ctx->psz_message);
68     free (ctx);
69 }
70
71 static vlc_threadvar_t msg_context;
72 static uintptr_t banks = 0;
73
74 /*****************************************************************************
75  * Local macros
76  *****************************************************************************/
77 #if defined(HAVE_VA_COPY)
78 #   define vlc_va_copy(dest,src) va_copy(dest,src)
79 #elif defined(HAVE___VA_COPY)
80 #   define vlc_va_copy(dest,src) __va_copy(dest,src)
81 #else
82 #   define vlc_va_copy(dest,src) (dest)=(src)
83 #endif
84
85 #define QUEUE priv->msg_bank
86 static inline msg_bank_t *libvlc_bank (libvlc_int_t *inst)
87 {
88     return &(libvlc_priv (inst))->msg_bank;
89 }
90
91 /*****************************************************************************
92  * Local prototypes
93  *****************************************************************************/
94 static void QueueMsg ( vlc_object_t *, int, const char *,
95                        const char *, va_list );
96 static void PrintMsg ( vlc_object_t *, msg_item_t * );
97
98 static vlc_mutex_t msg_stack_lock = VLC_STATIC_MUTEX;
99
100 /**
101  * Initialize messages queues
102  * This function initializes all message queues
103  */
104 void msg_Create (libvlc_int_t *p_libvlc)
105 {
106     libvlc_priv_t *priv = libvlc_priv (p_libvlc);
107     msg_bank_t *bank = libvlc_bank (p_libvlc);
108
109     vlc_rwlock_init (&bank->lock);
110     vlc_dictionary_init( &priv->msg_enabled_objects, 0 );
111     priv->msg_all_objects_enabled = true;
112
113     QUEUE.i_sub = 0;
114     QUEUE.pp_sub = NULL;
115
116 #ifdef UNDER_CE
117     QUEUE.logfile =
118         CreateFile( L"vlc-log.txt", GENERIC_WRITE,
119                     FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
120                     CREATE_ALWAYS, 0, NULL );
121     SetFilePointer( QUEUE.logfile, 0, NULL, FILE_END );
122 #endif
123
124     vlc_mutex_lock( &msg_stack_lock );
125     if( banks++ == 0 )
126         vlc_threadvar_create( &msg_context, cleanup_msg_context );
127     vlc_mutex_unlock( &msg_stack_lock );
128 }
129
130 /**
131  * Object Printing selection
132  */
133 static void const * kObjectPrintingEnabled = &kObjectPrintingEnabled;
134 static void const * kObjectPrintingDisabled = &kObjectPrintingDisabled;
135
136 void __msg_EnableObjectPrinting (vlc_object_t *p_this, char * psz_object)
137 {
138     libvlc_priv_t *priv = libvlc_priv (p_this->p_libvlc);
139     vlc_rwlock_wrlock( &QUEUE.lock );
140     if( !strcmp(psz_object, "all") )
141         priv->msg_all_objects_enabled = true;
142     else
143         vlc_dictionary_insert( &priv->msg_enabled_objects, psz_object, (void *)kObjectPrintingEnabled );
144     vlc_rwlock_unlock( &QUEUE.lock );
145 }
146
147 void __msg_DisableObjectPrinting (vlc_object_t *p_this, char * psz_object)
148 {
149     libvlc_priv_t *priv = libvlc_priv (p_this->p_libvlc);
150     vlc_rwlock_wrlock( &QUEUE.lock );
151     if( !strcmp(psz_object, "all") )
152         priv->msg_all_objects_enabled = false;
153     else
154         vlc_dictionary_insert( &priv->msg_enabled_objects, psz_object, (void *)kObjectPrintingDisabled );
155     vlc_rwlock_unlock( &QUEUE.lock );
156 }
157
158 /**
159  * Destroy the message queues
160  *
161  * This functions prints all messages remaining in the queues,
162  * then frees all the allocated resources
163  * No other messages interface functions should be called after this one.
164  */
165 void msg_Destroy (libvlc_int_t *p_libvlc)
166 {
167     libvlc_priv_t *priv = libvlc_priv (p_libvlc);
168     msg_bank_t *bank = libvlc_bank (p_libvlc);
169
170     if( QUEUE.i_sub )
171         msg_Err( p_libvlc, "stale interface subscribers (VLC might crash)" );
172
173     vlc_mutex_lock( &msg_stack_lock );
174     assert(banks > 0);
175     if( --banks == 0 )
176         vlc_threadvar_delete( &msg_context );
177     vlc_mutex_unlock( &msg_stack_lock );
178
179 #ifdef UNDER_CE
180     CloseHandle( QUEUE.logfile );
181 #endif
182
183     vlc_dictionary_clear( &priv->msg_enabled_objects, NULL, NULL );
184
185     vlc_rwlock_destroy (&bank->lock);
186 }
187
188 struct msg_subscription_t
189 {
190     vlc_thread_t    thread;
191     libvlc_int_t   *instance;
192     msg_callback_t  func;
193     msg_cb_data_t  *opaque;
194 };
195
196 /**
197  * Subscribe to the message queue.
198  * Whenever a message is emitted, a callback will be called.
199  * Callback invocation are serialized within a subscription.
200  *
201  * @param instance LibVLC instance to get messages from
202  * @param cb callback function
203  * @param opaque data for the callback function
204  * @return a subscription pointer, or NULL in case of failure
205  */
206 msg_subscription_t *msg_Subscribe (libvlc_int_t *instance, msg_callback_t cb,
207                                    msg_cb_data_t *opaque)
208 {
209     msg_subscription_t *sub = malloc (sizeof (*sub));
210     if (sub == NULL)
211         return NULL;
212
213     sub->instance = instance;
214     sub->func = cb;
215     sub->opaque = opaque;
216
217     msg_bank_t *bank = libvlc_bank (instance);
218     vlc_rwlock_wrlock (&bank->lock);
219     TAB_APPEND (bank->i_sub, bank->pp_sub, sub);
220     vlc_rwlock_unlock (&bank->lock);
221
222     return sub;
223 }
224
225 /**
226  * Unsubscribe from the message queue.
227  * This function waits for the message callback to return if needed.
228  */
229 void msg_Unsubscribe (msg_subscription_t *sub)
230 {
231     msg_bank_t *bank = libvlc_bank (sub->instance);
232
233     vlc_rwlock_wrlock (&bank->lock);
234     TAB_REMOVE (bank->i_sub, bank->pp_sub, sub);
235     vlc_rwlock_unlock (&bank->lock);
236     free (sub);
237 }
238
239 /*****************************************************************************
240  * __msg_*: print a message
241  *****************************************************************************
242  * These functions queue a message for later printing.
243  *****************************************************************************/
244 void __msg_Generic( vlc_object_t *p_this, int i_type, const char *psz_module,
245                     const char *psz_format, ... )
246 {
247     va_list args;
248
249     va_start( args, psz_format );
250     QueueMsg( p_this, i_type, psz_module, psz_format, args );
251     va_end( args );
252 }
253
254 void __msg_GenericVa( vlc_object_t *p_this, int i_type, const char *psz_module,
255                       const char *psz_format, va_list args )
256 {
257     QueueMsg( p_this, i_type, psz_module, psz_format, args );
258 }
259
260 /**
261  * Destroys a message.
262  */
263 static void msg_Free (gc_object_t *gc)
264 {
265     msg_item_t *msg = vlc_priv (gc, msg_item_t);
266
267     free (msg->psz_module);
268     free (msg->psz_msg);
269     free (msg->psz_header);
270     free (msg);
271 }
272
273 /**
274  * Add a message to a queue
275  *
276  * This function provides basic functionnalities to other msg_* functions.
277  * It adds a message to a queue (after having printed all stored messages if it
278  * is full). If the message can't be converted to string in memory, it issues
279  * a warning.
280  */
281 static void QueueMsg( vlc_object_t *p_this, int i_type, const char *psz_module,
282                       const char *psz_format, va_list _args )
283 {
284     assert (p_this);
285     libvlc_priv_t *priv = libvlc_priv (p_this->p_libvlc);
286     int         i_header_size;             /* Size of the additionnal header */
287     vlc_object_t *p_obj;
288     char *       psz_str = NULL;                 /* formatted message string */
289     char *       psz_header = NULL;
290     va_list      args;
291
292     if( p_this->i_flags & OBJECT_FLAGS_QUIET ||
293         (p_this->i_flags & OBJECT_FLAGS_NODBG && i_type == VLC_MSG_DBG) )
294         return;
295
296 #ifndef __GLIBC__
297     /* Expand %m to strerror(errno) - only once */
298     char buf[strlen( psz_format ) + 2001], *ptr;
299     strcpy( buf, psz_format );
300     ptr = (char*)buf;
301     psz_format = (const char*) buf;
302
303     for( ;; )
304     {
305         ptr = strchr( ptr, '%' );
306         if( ptr == NULL )
307             break;
308
309         if( ptr[1] == 'm' )
310         {
311             char errbuf[2001];
312             size_t errlen;
313
314 #ifndef WIN32
315             strerror_r( errno, errbuf, 1001 );
316 #else
317             int sockerr = WSAGetLastError( );
318             if( sockerr )
319             {
320                 strncpy( errbuf, net_strerror( sockerr ), 1001 );
321                 WSASetLastError( sockerr );
322             }
323             if ((sockerr == 0)
324              || (strcmp ("Unknown network stack error", errbuf) == 0))
325                 strncpy( errbuf, strerror( errno ), 1001 );
326 #endif
327             errbuf[1000] = 0;
328
329             /* Escape '%' from the error string */
330             for( char *percent = strchr( errbuf, '%' );
331                  percent != NULL;
332                  percent = strchr( percent + 2, '%' ) )
333             {
334                 memmove( percent + 1, percent, strlen( percent ) + 1 );
335             }
336
337             errlen = strlen( errbuf );
338             memmove( ptr + errlen, ptr + 2, strlen( ptr + 2 ) + 1 );
339             memcpy( ptr, errbuf, errlen );
340             break; /* Only once, so we don't overflow */
341         }
342
343         /* Looks for conversion specifier... */
344         do
345             ptr++;
346         while( *ptr && ( strchr( "diouxXeEfFgGaAcspn%", *ptr ) == NULL ) );
347         if( *ptr )
348             ptr++; /* ...and skip it */
349     }
350 #endif
351
352     /* Convert message to string  */
353     vlc_va_copy( args, _args );
354     if( vasprintf( &psz_str, psz_format, args ) == -1 )
355         psz_str = NULL;
356     va_end( args );
357
358     if( psz_str == NULL )
359     {
360         int canc = vlc_savecancel (); /* Do not print half of a message... */
361 #ifdef __GLIBC__
362         fprintf( stderr, "main warning: can't store message (%m): " );
363 #else
364         char psz_err[1001];
365 #ifndef WIN32
366         /* we're not using GLIBC, so we are sure that the error description
367          * will be stored in the buffer we provide to strerror_r() */
368         strerror_r( errno, psz_err, 1001 );
369 #else
370         strncpy( psz_err, strerror( errno ), 1001 );
371 #endif
372         psz_err[1000] = '\0';
373         fprintf( stderr, "main warning: can't store message (%s): ", psz_err );
374 #endif
375         vlc_va_copy( args, _args );
376         /* We should use utf8_vfprintf - but it calls malloc()... */
377         vfprintf( stderr, psz_format, args );
378         va_end( args );
379         fputs( "\n", stderr );
380         vlc_restorecancel (canc);
381         return;
382     }
383
384     msg_item_t * p_item = malloc (sizeof (*p_item));
385
386     if (p_item == NULL)
387         return; /* Uho! */
388
389     vlc_gc_init (p_item, msg_Free);
390     p_item->psz_module = p_item->psz_msg = p_item->psz_header = NULL;
391
392
393
394     i_header_size = 0;
395     p_obj = p_this;
396     while( p_obj != NULL )
397     {
398         char *psz_old = NULL;
399         if( p_obj->psz_header )
400         {
401             i_header_size += strlen( p_obj->psz_header ) + 4;
402             if( psz_header )
403             {
404                 psz_old = strdup( psz_header );
405                 psz_header = (char*)realloc( psz_header, i_header_size );
406                 snprintf( psz_header, i_header_size , "[%s] %s",
407                           p_obj->psz_header, psz_old );
408             }
409             else
410             {
411                 psz_header = (char *)malloc( i_header_size );
412                 snprintf( psz_header, i_header_size, "[%s]",
413                           p_obj->psz_header );
414             }
415         }
416         free( psz_old );
417         p_obj = p_obj->p_parent;
418     }
419
420     /* Fill message information fields */
421     p_item->i_type =        i_type;
422     p_item->i_object_id =   (uintptr_t)p_this;
423     p_item->psz_object_type = p_this->psz_object_type;
424     p_item->psz_module =    strdup( psz_module );
425     p_item->psz_msg =       psz_str;
426     p_item->psz_header =    psz_header;
427
428     PrintMsg( p_this, p_item );
429
430     msg_bank_t *bank = &QUEUE;
431     vlc_rwlock_rdlock (&bank->lock);
432     for (int i = 0; i < bank->i_sub; i++)
433     {
434         msg_subscription_t *sub = bank->pp_sub[i];
435         sub->func (sub->opaque, p_item, 0);
436     }
437     vlc_rwlock_unlock (&bank->lock);
438     msg_Release (p_item);
439 }
440
441 /*****************************************************************************
442  * PrintMsg: output a standard message item to stderr
443  *****************************************************************************
444  * Print a message to stderr, with colour formatting if needed.
445  *****************************************************************************/
446 static void PrintMsg ( vlc_object_t * p_this, msg_item_t * p_item )
447 {
448 #   define COL(x)  "\033[" #x ";1m"
449 #   define RED     COL(31)
450 #   define GREEN   COL(32)
451 #   define YELLOW  COL(33)
452 #   define WHITE   COL(0)
453 #   define GRAY    "\033[0m"
454
455 #ifdef UNDER_CE
456     int i_dummy;
457 #endif
458     static const char ppsz_type[4][9] = { "", " error", " warning", " debug" };
459     static const char ppsz_color[4][8] = { WHITE, RED, YELLOW, GRAY };
460     const char *psz_object;
461     libvlc_priv_t *priv = libvlc_priv (p_this->p_libvlc);
462     int i_type = p_item->i_type;
463
464     switch( i_type )
465     {
466         case VLC_MSG_ERR:
467             if( priv->i_verbose < 0 ) return;
468             break;
469         case VLC_MSG_INFO:
470             if( priv->i_verbose < 0 ) return;
471             break;
472         case VLC_MSG_WARN:
473             if( priv->i_verbose < 1 ) return;
474             break;
475         case VLC_MSG_DBG:
476             if( priv->i_verbose < 2 ) return;
477             break;
478     }
479
480     psz_object = p_item->psz_object_type;
481     void * val = vlc_dictionary_value_for_key( &priv->msg_enabled_objects,
482                                                p_item->psz_module );
483     if( val == kObjectPrintingDisabled )
484         return;
485     if( val == kObjectPrintingEnabled )
486         /* Allowed */;
487     else
488     {
489         val = vlc_dictionary_value_for_key( &priv->msg_enabled_objects,
490                                             psz_object );
491         if( val == kObjectPrintingDisabled )
492             return;
493         if( val == kObjectPrintingEnabled )
494             /* Allowed */;
495         else if( !priv->msg_all_objects_enabled )
496             return;
497     }
498
499 #ifdef UNDER_CE
500 #   define CE_WRITE(str) WriteFile( QUEUE.logfile, \
501                                     str, strlen(str), &i_dummy, NULL );
502     CE_WRITE( p_item->psz_module );
503     CE_WRITE( " " );
504     CE_WRITE( psz_object );
505     CE_WRITE( ppsz_type[i_type] );
506     CE_WRITE( ": " );
507     CE_WRITE( p_item->psz_msg );
508     CE_WRITE( "\r\n" );
509     FlushFileBuffers( QUEUE.logfile );
510
511 #else
512     int canc = vlc_savecancel ();
513     /* Send the message to stderr */
514     utf8_fprintf( stderr, "[%s%p%s] %s%s%s %s%s: %s%s%s\n",
515                   priv->b_color ? GREEN : "",
516                   (void *)p_item->i_object_id,
517                   priv->b_color ? GRAY : "",
518                   p_item->psz_header ? p_item->psz_header : "",
519                   p_item->psz_header ? " " : "",
520                   p_item->psz_module, psz_object,
521                   ppsz_type[i_type],
522                   priv->b_color ? ppsz_color[i_type] : "",
523                   p_item->psz_msg,
524                   priv->b_color ? GRAY : "" );
525
526 #   if defined(WIN32)
527     fflush( stderr );
528 #   endif
529     vlc_restorecancel (canc);
530 #endif
531 }
532
533 static msg_context_t* GetContext(void)
534 {
535     msg_context_t *p_ctx = vlc_threadvar_get( msg_context );
536     if( p_ctx == NULL )
537     {
538         p_ctx = malloc( sizeof( msg_context_t ) );
539         if( !p_ctx )
540             return NULL;
541         p_ctx->psz_message = NULL;
542         vlc_threadvar_set( msg_context, p_ctx );
543     }
544     return p_ctx;
545 }
546
547 void msg_StackDestroy (void *data)
548 {
549     msg_context_t *p_ctx = data;
550
551     free (p_ctx->psz_message);
552     free (p_ctx);
553 }
554
555 void msg_StackSet( int i_code, const char *psz_message, ... )
556 {
557     va_list ap;
558     msg_context_t *p_ctx = GetContext();
559
560     if( p_ctx == NULL )
561         return;
562     free( p_ctx->psz_message );
563
564     va_start( ap, psz_message );
565     if( vasprintf( &p_ctx->psz_message, psz_message, ap ) == -1 )
566         p_ctx->psz_message = NULL;
567     va_end( ap );
568
569     p_ctx->i_code = i_code;
570 }
571
572 void msg_StackAdd( const char *psz_message, ... )
573 {
574     char *psz_tmp;
575     va_list ap;
576     msg_context_t *p_ctx = GetContext();
577
578     if( p_ctx == NULL )
579         return;
580
581     va_start( ap, psz_message );
582     if( vasprintf( &psz_tmp, psz_message, ap ) == -1 )
583         psz_tmp = NULL;
584     va_end( ap );
585
586     if( !p_ctx->psz_message )
587         p_ctx->psz_message = psz_tmp;
588     else
589     {
590         char *psz_new;
591         if( asprintf( &psz_new, "%s: %s", psz_tmp, p_ctx->psz_message ) == -1 )
592             psz_new = NULL;
593
594         free( p_ctx->psz_message );
595         p_ctx->psz_message = psz_new;
596         free( psz_tmp );
597     }
598 }
599
600 const char* msg_StackMsg( void )
601 {
602     msg_context_t *p_ctx = GetContext();
603     assert( p_ctx );
604     return p_ctx->psz_message;
605 }