]> git.sesse.net Git - vlc/blob - src/misc/messages.c
Use var_Inherit* instead of var_CreateGet*.
[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 #ifdef __APPLE__
39 # include <xlocale.h>
40 #elif defined(HAVE_LOCALE_H)
41 # include <locale.h>
42 #endif
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 static inline msg_bank_t *libvlc_bank (libvlc_int_t *inst)
86 {
87     return (libvlc_priv (inst))->msg_bank;
88 }
89
90 /*****************************************************************************
91  * Local prototypes
92  *****************************************************************************/
93 static void PrintMsg ( vlc_object_t *, msg_item_t * );
94
95 static vlc_mutex_t msg_stack_lock = VLC_STATIC_MUTEX;
96
97 /**
98  * Store all data required by messages interfaces.
99  */
100 struct msg_bank_t
101 {
102     /** Message queue lock */
103     vlc_rwlock_t lock;
104
105     /* Subscribers */
106     int i_sub;
107     msg_subscription_t **pp_sub;
108
109     locale_t locale; /**< C locale for error messages */
110     vlc_dictionary_t enabled_objects; ///< Enabled objects
111     bool all_objects_enabled; ///< Should we print all objects?
112 };
113
114 /**
115  * Initialize messages queues
116  * This function initializes all message queues
117  */
118 msg_bank_t *msg_Create (void)
119 {
120     msg_bank_t *bank = malloc (sizeof (*bank));
121
122     vlc_rwlock_init (&bank->lock);
123     vlc_dictionary_init (&bank->enabled_objects, 0);
124     bank->all_objects_enabled = true;
125
126     bank->i_sub = 0;
127     bank->pp_sub = NULL;
128
129     /* C locale to get error messages in English in the logs */
130     bank->locale = newlocale (LC_MESSAGES_MASK, "C", (locale_t)0);
131
132     vlc_mutex_lock( &msg_stack_lock );
133     if( banks++ == 0 )
134         vlc_threadvar_create( &msg_context, cleanup_msg_context );
135     vlc_mutex_unlock( &msg_stack_lock );
136     return bank;
137 }
138
139 /**
140  * Object Printing selection
141  */
142 static void const * kObjectPrintingEnabled = &kObjectPrintingEnabled;
143 static void const * kObjectPrintingDisabled = &kObjectPrintingDisabled;
144
145
146 #undef msg_EnableObjectPrinting
147 void msg_EnableObjectPrinting (vlc_object_t *obj, const char * psz_object)
148 {
149     msg_bank_t *bank = libvlc_bank (obj->p_libvlc);
150
151     vlc_rwlock_wrlock (&bank->lock);
152     if( !strcmp(psz_object, "all") )
153         bank->all_objects_enabled = true;
154     else
155         vlc_dictionary_insert (&bank->enabled_objects, psz_object,
156                                (void *)kObjectPrintingEnabled);
157     vlc_rwlock_unlock (&bank->lock);
158 }
159
160 #undef msg_DisableObjectPrinting
161 void msg_DisableObjectPrinting (vlc_object_t *obj, const char * psz_object)
162 {
163     msg_bank_t *bank = libvlc_bank (obj->p_libvlc);
164
165     vlc_rwlock_wrlock (&bank->lock);
166     if( !strcmp(psz_object, "all") )
167         bank->all_objects_enabled = false;
168     else
169         vlc_dictionary_insert (&bank->enabled_objects, psz_object,
170                                (void *)kObjectPrintingDisabled);
171     vlc_rwlock_unlock (&bank->lock);
172 }
173
174 /**
175  * Destroy the message queues
176  *
177  * This functions prints all messages remaining in the queues,
178  * then frees all the allocated resources
179  * No other messages interface functions should be called after this one.
180  */
181 void msg_Destroy (msg_bank_t *bank)
182 {
183     if (unlikely(bank->i_sub != 0))
184         fputs ("stale interface subscribers (LibVLC might crash)\n", stderr);
185
186     vlc_mutex_lock( &msg_stack_lock );
187     assert(banks > 0);
188     if( --banks == 0 )
189         vlc_threadvar_delete( &msg_context );
190     vlc_mutex_unlock( &msg_stack_lock );
191
192     if (bank->locale != (locale_t)0)
193        freelocale (bank->locale);
194
195     vlc_dictionary_clear (&bank->enabled_objects, NULL, NULL);
196
197     vlc_rwlock_destroy (&bank->lock);
198     free (bank);
199 }
200
201 struct msg_subscription_t
202 {
203     libvlc_int_t   *instance;
204     msg_callback_t  func;
205     msg_cb_data_t  *opaque;
206     int             verbosity;
207 };
208
209 /**
210  * Subscribe to the message queue.
211  * Whenever a message is emitted, a callback will be called.
212  * Callback invocation are serialized within a subscription.
213  *
214  * @param instance LibVLC instance to get messages from
215  * @param cb callback function
216  * @param opaque data for the callback function
217  * @return a subscription pointer, or NULL in case of failure
218  */
219 msg_subscription_t *msg_Subscribe (libvlc_int_t *instance, msg_callback_t cb,
220                                    msg_cb_data_t *opaque)
221 {
222     msg_subscription_t *sub = malloc (sizeof (*sub));
223     if (sub == NULL)
224         return NULL;
225
226     sub->instance = instance;
227     sub->func = cb;
228     sub->opaque = opaque;
229     sub->verbosity = 2; /* by default, give all the messages */
230
231     msg_bank_t *bank = libvlc_bank (instance);
232     vlc_rwlock_wrlock (&bank->lock);
233     TAB_APPEND (bank->i_sub, bank->pp_sub, sub);
234     vlc_rwlock_unlock (&bank->lock);
235
236     return sub;
237 }
238
239 /**
240  * Unsubscribe from the message queue.
241  * This function waits for the message callback to return if needed.
242  */
243 void msg_Unsubscribe (msg_subscription_t *sub)
244 {
245     msg_bank_t *bank = libvlc_bank (sub->instance);
246
247     vlc_rwlock_wrlock (&bank->lock);
248     TAB_REMOVE (bank->i_sub, bank->pp_sub, sub);
249     vlc_rwlock_unlock (&bank->lock);
250     free (sub);
251 }
252
253 void msg_SubscriptionSetVerbosity( msg_subscription_t *sub, const int i_verbosity )
254 {
255     if( i_verbosity < 0 || i_verbosity > 2 ) return;
256
257     msg_bank_t *bank = libvlc_bank ( sub->instance );
258
259     vlc_rwlock_wrlock (&bank->lock);
260
261     sub->verbosity = i_verbosity;
262
263     vlc_rwlock_unlock (&bank->lock);
264 }
265 /*****************************************************************************
266  * msg_*: print a message
267  *****************************************************************************
268  * These functions queue a message for later printing.
269  *****************************************************************************/
270 void msg_Generic( vlc_object_t *p_this, int i_type, const char *psz_module,
271                     const char *psz_format, ... )
272 {
273     va_list args;
274
275     va_start( args, psz_format );
276     msg_GenericVa (p_this, i_type, psz_module, psz_format, args);
277     va_end( args );
278 }
279
280 /**
281  * Destroys a message.
282  */
283 static void msg_Free (gc_object_t *gc)
284 {
285     msg_item_t *msg = vlc_priv (gc, msg_item_t);
286
287     free (msg->psz_module);
288     free (msg->psz_msg);
289     free (msg->psz_header);
290     free (msg);
291 }
292
293 #undef msg_GenericVa
294 /**
295  * Add a message to a queue
296  *
297  * This function provides basic functionnalities to other msg_* functions.
298  * It adds a message to a queue (after having printed all stored messages if it
299  * is full). If the message can't be converted to string in memory, it issues
300  * a warning.
301  */
302 void msg_GenericVa (vlc_object_t *p_this, int i_type,
303                            const char *psz_module,
304                            const char *psz_format, va_list _args)
305 {
306     size_t      i_header_size;             /* Size of the additionnal header */
307     vlc_object_t *p_obj;
308     char *       psz_str = NULL;                 /* formatted message string */
309     char *       psz_header = NULL;
310     va_list      args;
311
312     assert (p_this);
313
314     if( p_this->i_flags & OBJECT_FLAGS_QUIET ||
315         (p_this->i_flags & OBJECT_FLAGS_NODBG && i_type == VLC_MSG_DBG) )
316         return;
317
318     msg_bank_t *bank = libvlc_bank (p_this->p_libvlc);
319     locale_t locale = uselocale (bank->locale);
320
321 #ifndef __GLIBC__
322     /* Expand %m to strerror(errno) - only once */
323     char buf[strlen( psz_format ) + 2001], *ptr;
324     strcpy( buf, psz_format );
325     ptr = (char*)buf;
326     psz_format = (const char*) buf;
327
328     for( ;; )
329     {
330         ptr = strchr( ptr, '%' );
331         if( ptr == NULL )
332             break;
333
334         if( ptr[1] == 'm' )
335         {
336             char errbuf[2001];
337             size_t errlen;
338
339 #ifndef WIN32
340             strerror_r( errno, errbuf, 1001 );
341 #else
342             int sockerr = WSAGetLastError( );
343             if( sockerr )
344             {
345                 strncpy( errbuf, net_strerror( sockerr ), 1001 );
346                 WSASetLastError( sockerr );
347             }
348             if ((sockerr == 0)
349              || (strcmp ("Unknown network stack error", errbuf) == 0))
350                 strncpy( errbuf, strerror( errno ), 1001 );
351 #endif
352             errbuf[1000] = 0;
353
354             /* Escape '%' from the error string */
355             for( char *percent = strchr( errbuf, '%' );
356                  percent != NULL;
357                  percent = strchr( percent + 2, '%' ) )
358             {
359                 memmove( percent + 1, percent, strlen( percent ) + 1 );
360             }
361
362             errlen = strlen( errbuf );
363             memmove( ptr + errlen, ptr + 2, strlen( ptr + 2 ) + 1 );
364             memcpy( ptr, errbuf, errlen );
365             break; /* Only once, so we don't overflow */
366         }
367
368         /* Looks for conversion specifier... */
369         do
370             ptr++;
371         while( *ptr && ( strchr( "diouxXeEfFgGaAcspn%", *ptr ) == NULL ) );
372         if( *ptr )
373             ptr++; /* ...and skip it */
374     }
375 #endif
376
377     /* Convert message to string  */
378     vlc_va_copy( args, _args );
379     if( vasprintf( &psz_str, psz_format, args ) == -1 )
380         psz_str = NULL;
381     va_end( args );
382
383     if( psz_str == NULL )
384     {
385         int canc = vlc_savecancel (); /* Do not print half of a message... */
386 #ifdef __GLIBC__
387         fprintf( stderr, "main warning: can't store message (%m): " );
388 #else
389         char psz_err[1001];
390 #ifndef WIN32
391         /* we're not using GLIBC, so we are sure that the error description
392          * will be stored in the buffer we provide to strerror_r() */
393         strerror_r( errno, psz_err, 1001 );
394 #else
395         strncpy( psz_err, strerror( errno ), 1001 );
396 #endif
397         psz_err[1000] = '\0';
398         fprintf( stderr, "main warning: can't store message (%s): ", psz_err );
399 #endif
400         vlc_va_copy( args, _args );
401         /* We should use utf8_vfprintf - but it calls malloc()... */
402         vfprintf( stderr, psz_format, args );
403         va_end( args );
404         fputs( "\n", stderr );
405         vlc_restorecancel (canc);
406         uselocale (locale);
407         return;
408     }
409     uselocale (locale);
410
411     msg_item_t * p_item = malloc (sizeof (*p_item));
412     if (p_item == NULL)
413         return; /* Uho! */
414
415     vlc_gc_init (p_item, msg_Free);
416     p_item->psz_module = p_item->psz_msg = p_item->psz_header = NULL;
417
418
419
420     i_header_size = 0;
421     p_obj = p_this;
422     while( p_obj != NULL )
423     {
424         char *psz_old = NULL;
425         if( p_obj->psz_header )
426         {
427             i_header_size += strlen( p_obj->psz_header ) + 4;
428             if( psz_header )
429             {
430                 psz_old = strdup( psz_header );
431                 psz_header = xrealloc( psz_header, i_header_size );
432                 snprintf( psz_header, i_header_size , "[%s] %s",
433                           p_obj->psz_header, psz_old );
434             }
435             else
436             {
437                 psz_header = xmalloc( i_header_size );
438                 snprintf( psz_header, i_header_size, "[%s]",
439                           p_obj->psz_header );
440             }
441         }
442         free( psz_old );
443         p_obj = p_obj->p_parent;
444     }
445
446     /* Fill message information fields */
447     p_item->i_type =        i_type;
448     p_item->i_object_id =   (uintptr_t)p_this;
449     p_item->psz_object_type = p_this->psz_object_type;
450     p_item->psz_module =    strdup( psz_module );
451     p_item->psz_msg =       psz_str;
452     p_item->psz_header =    psz_header;
453
454     PrintMsg( p_this, p_item );
455
456     vlc_rwlock_rdlock (&bank->lock);
457     for (int i = 0; i < bank->i_sub; i++)
458     {
459         msg_subscription_t *sub = bank->pp_sub[i];
460         libvlc_priv_t *priv = libvlc_priv( sub->instance );
461         msg_bank_t *bank = priv->msg_bank;
462         void *val = vlc_dictionary_value_for_key( &bank->enabled_objects,
463                                                   p_item->psz_module );
464         if( val == kObjectPrintingDisabled ) continue;
465         if( val != kObjectPrintingEnabled  ) /*if not allowed */
466         {
467             val = vlc_dictionary_value_for_key( &bank->enabled_objects,
468                                                  p_item->psz_object_type );
469             if( val == kObjectPrintingDisabled ) continue;
470             if( val == kObjectPrintingEnabled  ); /* Allowed */
471             else if( !bank->all_objects_enabled ) continue;
472         }
473         switch( p_item->i_type )
474         {
475             case VLC_MSG_INFO:
476             case VLC_MSG_ERR:
477                 if( sub->verbosity < 0 ) continue;
478                 break;
479             case VLC_MSG_WARN:
480                 if( sub->verbosity < 1 ) continue;
481                 break;
482             case VLC_MSG_DBG:
483                 if( sub->verbosity < 2 ) continue;
484                 break;
485         }
486
487         sub->func (sub->opaque, p_item, 0);
488     }
489     vlc_rwlock_unlock (&bank->lock);
490     msg_Release (p_item);
491 }
492
493 /*****************************************************************************
494  * PrintMsg: output a standard message item to stderr
495  *****************************************************************************
496  * Print a message to stderr, with colour formatting if needed.
497  *****************************************************************************/
498 static void PrintMsg ( vlc_object_t * p_this, msg_item_t * p_item )
499 {
500 #   define COL(x,y)  "\033[" #x ";" #y "m"
501 #   define RED     COL(31,1)
502 #   define GREEN   COL(32,1)
503 #   define YELLOW  COL(0,33)
504 #   define WHITE   COL(0,1)
505 #   define GRAY    "\033[0m"
506
507     static const char ppsz_type[4][9] = { "", " error", " warning", " debug" };
508     static const char ppsz_color[4][8] = { WHITE, RED, YELLOW, GRAY };
509     const char *psz_object;
510     libvlc_priv_t *priv = libvlc_priv (p_this->p_libvlc);
511     msg_bank_t *bank = priv->msg_bank;
512     int i_type = p_item->i_type;
513
514     switch( i_type )
515     {
516         case VLC_MSG_ERR:
517             if( priv->i_verbose < 0 ) return;
518             break;
519         case VLC_MSG_INFO:
520             if( priv->i_verbose < 0 ) return;
521             break;
522         case VLC_MSG_WARN:
523             if( priv->i_verbose < 1 ) return;
524             break;
525         case VLC_MSG_DBG:
526             if( priv->i_verbose < 2 ) return;
527             break;
528     }
529
530     psz_object = p_item->psz_object_type;
531     void * val = vlc_dictionary_value_for_key (&bank->enabled_objects,
532                                                p_item->psz_module);
533     if( val == kObjectPrintingDisabled )
534         return;
535     if( val == kObjectPrintingEnabled )
536         /* Allowed */;
537     else
538     {
539         val = vlc_dictionary_value_for_key (&bank->enabled_objects,
540                                             psz_object);
541         if( val == kObjectPrintingDisabled )
542             return;
543         if( val == kObjectPrintingEnabled )
544             /* Allowed */;
545         else if( !bank->all_objects_enabled )
546             return;
547     }
548
549     int canc = vlc_savecancel ();
550     /* Send the message to stderr */
551     utf8_fprintf( stderr, "[%s%p%s] %s%s%s %s%s: %s%s%s\n",
552                   priv->b_color ? GREEN : "",
553                   (void *)p_item->i_object_id,
554                   priv->b_color ? GRAY : "",
555                   p_item->psz_header ? p_item->psz_header : "",
556                   p_item->psz_header ? " " : "",
557                   p_item->psz_module, psz_object,
558                   ppsz_type[i_type],
559                   priv->b_color ? ppsz_color[i_type] : "",
560                   p_item->psz_msg,
561                   priv->b_color ? GRAY : "" );
562
563 #ifdef WIN32
564     fflush( stderr );
565 #endif
566     vlc_restorecancel (canc);
567 }
568
569 static msg_context_t* GetContext(void)
570 {
571     msg_context_t *p_ctx = vlc_threadvar_get( msg_context );
572     if( p_ctx == NULL )
573     {
574         p_ctx = malloc( sizeof( msg_context_t ) );
575         if( !p_ctx )
576             return NULL;
577         p_ctx->psz_message = NULL;
578         vlc_threadvar_set( msg_context, p_ctx );
579     }
580     return p_ctx;
581 }
582
583 void msg_StackSet( int i_code, const char *psz_message, ... )
584 {
585     va_list ap;
586     msg_context_t *p_ctx = GetContext();
587
588     if( p_ctx == NULL )
589         return;
590     free( p_ctx->psz_message );
591
592     va_start( ap, psz_message );
593     if( vasprintf( &p_ctx->psz_message, psz_message, ap ) == -1 )
594         p_ctx->psz_message = NULL;
595     va_end( ap );
596
597     p_ctx->i_code = i_code;
598 }
599
600 void msg_StackAdd( const char *psz_message, ... )
601 {
602     char *psz_tmp;
603     va_list ap;
604     msg_context_t *p_ctx = GetContext();
605
606     if( p_ctx == NULL )
607         return;
608
609     va_start( ap, psz_message );
610     if( vasprintf( &psz_tmp, psz_message, ap ) == -1 )
611         psz_tmp = NULL;
612     va_end( ap );
613
614     if( !p_ctx->psz_message )
615         p_ctx->psz_message = psz_tmp;
616     else
617     {
618         char *psz_new;
619         if( asprintf( &psz_new, "%s: %s", psz_tmp, p_ctx->psz_message ) == -1 )
620             psz_new = NULL;
621
622         free( p_ctx->psz_message );
623         p_ctx->psz_message = psz_new;
624         free( psz_tmp );
625     }
626 }
627
628 const char* msg_StackMsg( void )
629 {
630     msg_context_t *p_ctx = GetContext();
631     assert( p_ctx );
632     return p_ctx->psz_message;
633 }