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