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