]> git.sesse.net Git - vlc/blob - src/misc/messages.c
Use C locale when formatting error messages in the log
[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 #define QUEUE priv->msg_bank
82 static inline msg_bank_t *libvlc_bank (libvlc_int_t *inst)
83 {
84     return &(libvlc_priv (inst))->msg_bank;
85 }
86
87 /*****************************************************************************
88  * Local prototypes
89  *****************************************************************************/
90 static void QueueMsg ( vlc_object_t *, int, const char *,
91                        const char *, va_list );
92 static void PrintMsg ( vlc_object_t *, msg_item_t * );
93
94 static vlc_mutex_t msg_stack_lock = VLC_STATIC_MUTEX;
95
96 /**
97  * Initialize messages queues
98  * This function initializes all message queues
99  */
100 void msg_Create (libvlc_int_t *p_libvlc)
101 {
102     libvlc_priv_t *priv = libvlc_priv (p_libvlc);
103     msg_bank_t *bank = libvlc_bank (p_libvlc);
104
105     vlc_rwlock_init (&bank->lock);
106     vlc_dictionary_init( &priv->msg_enabled_objects, 0 );
107     priv->msg_all_objects_enabled = true;
108
109     QUEUE.i_sub = 0;
110     QUEUE.pp_sub = NULL;
111
112     /* C locale to get error messages in English in the logs */
113     bank->locale = newlocale (LC_MESSAGES_MASK, "C", (locale_t)0);
114
115 #ifdef UNDER_CE
116     QUEUE.logfile =
117         CreateFile( L"vlc-log.txt", GENERIC_WRITE,
118                     FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
119                     CREATE_ALWAYS, 0, NULL );
120     SetFilePointer( QUEUE.logfile, 0, NULL, FILE_END );
121 #endif
122
123     vlc_mutex_lock( &msg_stack_lock );
124     if( banks++ == 0 )
125         vlc_threadvar_create( &msg_context, cleanup_msg_context );
126     vlc_mutex_unlock( &msg_stack_lock );
127 }
128
129 /**
130  * Object Printing selection
131  */
132 static void const * kObjectPrintingEnabled = &kObjectPrintingEnabled;
133 static void const * kObjectPrintingDisabled = &kObjectPrintingDisabled;
134
135 void __msg_EnableObjectPrinting (vlc_object_t *p_this, const char * psz_object)
136 {
137     libvlc_priv_t *priv = libvlc_priv (p_this->p_libvlc);
138     vlc_rwlock_wrlock( &QUEUE.lock );
139     if( !strcmp(psz_object, "all") )
140         priv->msg_all_objects_enabled = true;
141     else
142         vlc_dictionary_insert( &priv->msg_enabled_objects, psz_object, (void *)kObjectPrintingEnabled );
143     vlc_rwlock_unlock( &QUEUE.lock );
144 }
145
146 void __msg_DisableObjectPrinting (vlc_object_t *p_this, const char * psz_object)
147 {
148     libvlc_priv_t *priv = libvlc_priv (p_this->p_libvlc);
149     vlc_rwlock_wrlock( &QUEUE.lock );
150     if( !strcmp(psz_object, "all") )
151         priv->msg_all_objects_enabled = false;
152     else
153         vlc_dictionary_insert( &priv->msg_enabled_objects, psz_object, (void *)kObjectPrintingDisabled );
154     vlc_rwlock_unlock( &QUEUE.lock );
155 }
156
157 /**
158  * Destroy the message queues
159  *
160  * This functions prints all messages remaining in the queues,
161  * then frees all the allocated resources
162  * No other messages interface functions should be called after this one.
163  */
164 void msg_Destroy (libvlc_int_t *p_libvlc)
165 {
166     libvlc_priv_t *priv = libvlc_priv (p_libvlc);
167     msg_bank_t *bank = libvlc_bank (p_libvlc);
168
169     if( QUEUE.i_sub )
170         msg_Err( p_libvlc, "stale interface subscribers (VLC might crash)" );
171
172     vlc_mutex_lock( &msg_stack_lock );
173     assert(banks > 0);
174     if( --banks == 0 )
175         vlc_threadvar_delete( &msg_context );
176     vlc_mutex_unlock( &msg_stack_lock );
177
178 #ifdef UNDER_CE
179     CloseHandle( QUEUE.logfile );
180 #endif
181     if (bank->locale != (locale_t)0)
182        freelocale (bank->locale);
183
184     vlc_dictionary_clear( &priv->msg_enabled_objects, NULL, NULL );
185
186     vlc_rwlock_destroy (&bank->lock);
187 }
188
189 struct msg_subscription_t
190 {
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     msg_bank_t *bank = &QUEUE;
297     locale_t locale = uselocale (bank->locale);
298
299 #ifndef __GLIBC__
300     /* Expand %m to strerror(errno) - only once */
301     char buf[strlen( psz_format ) + 2001], *ptr;
302     strcpy( buf, psz_format );
303     ptr = (char*)buf;
304     psz_format = (const char*) buf;
305
306     for( ;; )
307     {
308         ptr = strchr( ptr, '%' );
309         if( ptr == NULL )
310             break;
311
312         if( ptr[1] == 'm' )
313         {
314             char errbuf[2001];
315             size_t errlen;
316
317 #ifndef WIN32
318             strerror_r( errno, errbuf, 1001 );
319 #else
320             int sockerr = WSAGetLastError( );
321             if( sockerr )
322             {
323                 strncpy( errbuf, net_strerror( sockerr ), 1001 );
324                 WSASetLastError( sockerr );
325             }
326             if ((sockerr == 0)
327              || (strcmp ("Unknown network stack error", errbuf) == 0))
328                 strncpy( errbuf, strerror( errno ), 1001 );
329 #endif
330             errbuf[1000] = 0;
331
332             /* Escape '%' from the error string */
333             for( char *percent = strchr( errbuf, '%' );
334                  percent != NULL;
335                  percent = strchr( percent + 2, '%' ) )
336             {
337                 memmove( percent + 1, percent, strlen( percent ) + 1 );
338             }
339
340             errlen = strlen( errbuf );
341             memmove( ptr + errlen, ptr + 2, strlen( ptr + 2 ) + 1 );
342             memcpy( ptr, errbuf, errlen );
343             break; /* Only once, so we don't overflow */
344         }
345
346         /* Looks for conversion specifier... */
347         do
348             ptr++;
349         while( *ptr && ( strchr( "diouxXeEfFgGaAcspn%", *ptr ) == NULL ) );
350         if( *ptr )
351             ptr++; /* ...and skip it */
352     }
353 #endif
354
355     /* Convert message to string  */
356     vlc_va_copy( args, _args );
357     if( vasprintf( &psz_str, psz_format, args ) == -1 )
358         psz_str = NULL;
359     va_end( args );
360
361     if( psz_str == NULL )
362     {
363         int canc = vlc_savecancel (); /* Do not print half of a message... */
364 #ifdef __GLIBC__
365         fprintf( stderr, "main warning: can't store message (%m): " );
366 #else
367         char psz_err[1001];
368 #ifndef WIN32
369         /* we're not using GLIBC, so we are sure that the error description
370          * will be stored in the buffer we provide to strerror_r() */
371         strerror_r( errno, psz_err, 1001 );
372 #else
373         strncpy( psz_err, strerror( errno ), 1001 );
374 #endif
375         psz_err[1000] = '\0';
376         fprintf( stderr, "main warning: can't store message (%s): ", psz_err );
377 #endif
378         vlc_va_copy( args, _args );
379         /* We should use utf8_vfprintf - but it calls malloc()... */
380         vfprintf( stderr, psz_format, args );
381         va_end( args );
382         fputs( "\n", stderr );
383         vlc_restorecancel (canc);
384         uselocale (locale);
385         return;
386     }
387     uselocale (locale);
388
389     msg_item_t * p_item = malloc (sizeof (*p_item));
390     if (p_item == NULL)
391         return; /* Uho! */
392
393     vlc_gc_init (p_item, msg_Free);
394     p_item->psz_module = p_item->psz_msg = p_item->psz_header = NULL;
395
396
397
398     i_header_size = 0;
399     p_obj = p_this;
400     while( p_obj != NULL )
401     {
402         char *psz_old = NULL;
403         if( p_obj->psz_header )
404         {
405             i_header_size += strlen( p_obj->psz_header ) + 4;
406             if( psz_header )
407             {
408                 psz_old = strdup( psz_header );
409                 psz_header = xrealloc( psz_header, i_header_size );
410                 snprintf( psz_header, i_header_size , "[%s] %s",
411                           p_obj->psz_header, psz_old );
412             }
413             else
414             {
415                 psz_header = xmalloc( i_header_size );
416                 snprintf( psz_header, i_header_size, "[%s]",
417                           p_obj->psz_header );
418             }
419         }
420         free( psz_old );
421         p_obj = p_obj->p_parent;
422     }
423
424     /* Fill message information fields */
425     p_item->i_type =        i_type;
426     p_item->i_object_id =   (uintptr_t)p_this;
427     p_item->psz_object_type = p_this->psz_object_type;
428     p_item->psz_module =    strdup( psz_module );
429     p_item->psz_msg =       psz_str;
430     p_item->psz_header =    psz_header;
431
432     PrintMsg( p_this, p_item );
433
434     vlc_rwlock_rdlock (&bank->lock);
435     for (int i = 0; i < bank->i_sub; i++)
436     {
437         msg_subscription_t *sub = bank->pp_sub[i];
438         sub->func (sub->opaque, p_item, 0);
439     }
440     vlc_rwlock_unlock (&bank->lock);
441     msg_Release (p_item);
442 }
443
444 /*****************************************************************************
445  * PrintMsg: output a standard message item to stderr
446  *****************************************************************************
447  * Print a message to stderr, with colour formatting if needed.
448  *****************************************************************************/
449 static void PrintMsg ( vlc_object_t * p_this, msg_item_t * p_item )
450 {
451 #   define COL(x)  "\033[" #x ";1m"
452 #   define RED     COL(31)
453 #   define GREEN   COL(32)
454 #   define YELLOW  COL(33)
455 #   define WHITE   COL(0)
456 #   define GRAY    "\033[0m"
457
458 #ifdef UNDER_CE
459     int i_dummy;
460 #endif
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     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( &priv->msg_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( &priv->msg_enabled_objects,
493                                             psz_object );
494         if( val == kObjectPrintingDisabled )
495             return;
496         if( val == kObjectPrintingEnabled )
497             /* Allowed */;
498         else if( !priv->msg_all_objects_enabled )
499             return;
500     }
501
502 #ifdef UNDER_CE
503 #   define CE_WRITE(str) WriteFile( QUEUE.logfile, \
504                                     str, strlen(str), &i_dummy, NULL );
505     CE_WRITE( p_item->psz_module );
506     CE_WRITE( " " );
507     CE_WRITE( psz_object );
508     CE_WRITE( ppsz_type[i_type] );
509     CE_WRITE( ": " );
510     CE_WRITE( p_item->psz_msg );
511     CE_WRITE( "\r\n" );
512     FlushFileBuffers( QUEUE.logfile );
513
514 #else
515     int canc = vlc_savecancel ();
516     /* Send the message to stderr */
517     utf8_fprintf( stderr, "[%s%p%s] %s%s%s %s%s: %s%s%s\n",
518                   priv->b_color ? GREEN : "",
519                   (void *)p_item->i_object_id,
520                   priv->b_color ? GRAY : "",
521                   p_item->psz_header ? p_item->psz_header : "",
522                   p_item->psz_header ? " " : "",
523                   p_item->psz_module, psz_object,
524                   ppsz_type[i_type],
525                   priv->b_color ? ppsz_color[i_type] : "",
526                   p_item->psz_msg,
527                   priv->b_color ? GRAY : "" );
528
529 #   if defined(WIN32)
530     fflush( stderr );
531 #   endif
532     vlc_restorecancel (canc);
533 #endif
534 }
535
536 static msg_context_t* GetContext(void)
537 {
538     msg_context_t *p_ctx = vlc_threadvar_get( msg_context );
539     if( p_ctx == NULL )
540     {
541         p_ctx = malloc( sizeof( msg_context_t ) );
542         if( !p_ctx )
543             return NULL;
544         p_ctx->psz_message = NULL;
545         vlc_threadvar_set( msg_context, p_ctx );
546     }
547     return p_ctx;
548 }
549
550 void msg_StackDestroy (void *data)
551 {
552     msg_context_t *p_ctx = data;
553
554     free (p_ctx->psz_message);
555     free (p_ctx);
556 }
557
558 void msg_StackSet( int i_code, const char *psz_message, ... )
559 {
560     va_list ap;
561     msg_context_t *p_ctx = GetContext();
562
563     if( p_ctx == NULL )
564         return;
565     free( p_ctx->psz_message );
566
567     va_start( ap, psz_message );
568     if( vasprintf( &p_ctx->psz_message, psz_message, ap ) == -1 )
569         p_ctx->psz_message = NULL;
570     va_end( ap );
571
572     p_ctx->i_code = i_code;
573 }
574
575 void msg_StackAdd( const char *psz_message, ... )
576 {
577     char *psz_tmp;
578     va_list ap;
579     msg_context_t *p_ctx = GetContext();
580
581     if( p_ctx == NULL )
582         return;
583
584     va_start( ap, psz_message );
585     if( vasprintf( &psz_tmp, psz_message, ap ) == -1 )
586         psz_tmp = NULL;
587     va_end( ap );
588
589     if( !p_ctx->psz_message )
590         p_ctx->psz_message = psz_tmp;
591     else
592     {
593         char *psz_new;
594         if( asprintf( &psz_new, "%s: %s", psz_tmp, p_ctx->psz_message ) == -1 )
595             psz_new = NULL;
596
597         free( p_ctx->psz_message );
598         p_ctx->psz_message = psz_new;
599         free( psz_tmp );
600     }
601 }
602
603 const char* msg_StackMsg( void )
604 {
605     msg_context_t *p_ctx = GetContext();
606     assert( p_ctx );
607     return p_ctx->psz_message;
608 }