• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * libusb strerror code
3  * Copyright © 2013 Hans de Goede <hdegoede@redhat.com>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18  */
19 
20 #include "libusbi.h"
21 
22 #include <ctype.h>
23 #include <string.h>
24 
25 /** \ingroup libusb_misc
26  * How to add a new \ref libusb_strerror() translation:
27  * <ol>
28  * <li> Download the latest \c strerror.c from:<br>
29  *      https://raw.github.com/libusb/libusb/master/libusb/strerror.c </li>
30  * <li> Open the file in an UTF-8 capable editor </li>
31  * <li> Add the 2 letter <a href="http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes">ISO 639-1</a>
32  *      code for your locale at the end of \c usbi_locale_supported[]<br>
33  *    Eg. for Chinese, you would add "zh" so that:
34  *    \code... usbi_locale_supported[] = { "en", "nl", "fr" };\endcode
35  *    becomes:
36  *    \code... usbi_locale_supported[] = { "en", "nl", "fr", "zh" };\endcode </li>
37  * <li> Copy the <tt>{ / * English (en) * / ... }</tt> section and add it at the end of \c usbi_localized_errors<br>
38  *    Eg. for Chinese, the last section of \c usbi_localized_errors could look like:
39  *    \code
40  *     }, { / * Chinese (zh) * /
41  *         "Success",
42  *         ...
43  *         "Other error",
44  *     },
45  * };\endcode </li>
46  * <li> Translate each of the English messages from the section you copied into your language </li>
47  * <li> Save the file (in UTF-8 format) and send it to \c libusb-devel\@lists.sourceforge.net </li>
48  * </ol>
49  */
50 
51 static const char * const usbi_locale_supported[] = { "en", "nl", "fr", "ru", "de", "hu" };
52 static const char * const usbi_localized_errors[ARRAYSIZE(usbi_locale_supported)][LIBUSB_ERROR_COUNT] = {
53 	{ /* English (en) */
54 		"Success",
55 		"Input/Output Error",
56 		"Invalid parameter",
57 		"Access denied (insufficient permissions)",
58 		"No such device (it may have been disconnected)",
59 		"Entity not found",
60 		"Resource busy",
61 		"Operation timed out",
62 		"Overflow",
63 		"Pipe error",
64 		"System call interrupted (perhaps due to signal)",
65 		"Insufficient memory",
66 		"Operation not supported or unimplemented on this platform",
67 		"Other error",
68 	}, { /* Dutch (nl) */
69 		"Gelukt",
70 		"Invoer-/uitvoerfout",
71 		"Ongeldig argument",
72 		"Toegang geweigerd (onvoldoende toegangsrechten)",
73 		"Apparaat bestaat niet (verbinding met apparaat verbroken?)",
74 		"Niet gevonden",
75 		"Apparaat of hulpbron is bezig",
76 		"Bewerking verlopen",
77 		"Waarde is te groot",
78 		"Gebroken pijp",
79 		"Onderbroken systeemaanroep",
80 		"Onvoldoende geheugen beschikbaar",
81 		"Bewerking wordt niet ondersteund",
82 		"Andere fout",
83 	}, { /* French (fr) */
84 		"Succès",
85 		"Erreur d'entrée/sortie",
86 		"Paramètre invalide",
87 		"Accès refusé (permissions insuffisantes)",
88 		"Périphérique introuvable (peut-être déconnecté)",
89 		"Elément introuvable",
90 		"Resource déjà occupée",
91 		"Operation expirée",
92 		"Débordement",
93 		"Erreur de pipe",
94 		"Appel système abandonné (peut-être à cause d’un signal)",
95 		"Mémoire insuffisante",
96 		"Opération non supportée or non implémentée sur cette plateforme",
97 		"Autre erreur",
98 	}, { /* Russian (ru) */
99 		"Успех",
100 		"Ошибка ввода/вывода",
101 		"Неверный параметр",
102 		"Доступ запрещён (не хватает прав)",
103 		"Устройство отсутствует (возможно, оно было отсоединено)",
104 		"Элемент не найден",
105 		"Ресурс занят",
106 		"Истекло время ожидания операции",
107 		"Переполнение",
108 		"Ошибка канала",
109 		"Системный вызов прерван (возможно, сигналом)",
110 		"Память исчерпана",
111 		"Операция не поддерживается данной платформой",
112 		"Неизвестная ошибка"
113 	}, { /* German (de) */
114 		"Erfolgreich",
115 		"Eingabe-/Ausgabefehler",
116 		"Ungültiger Parameter",
117 		"Keine Berechtigung (Zugriffsrechte fehlen)",
118 		"Kein passendes Gerät gefunden (es könnte entfernt worden sein)",
119 		"Entität nicht gefunden",
120 		"Die Ressource ist belegt",
121 		"Die Wartezeit für die Operation ist abgelaufen",
122 		"Mehr Daten empfangen als erwartet",
123 		"Datenübergabe unterbrochen (broken pipe)",
124 		"Unterbrechung während des Betriebssystemaufrufs",
125 		"Nicht genügend Hauptspeicher verfügbar",
126 		"Die Operation wird nicht unterstützt oder ist auf dieser Platform nicht implementiert",
127 		"Allgemeiner Fehler",
128 	}, { /* Hungarian (hu) */
129 		"Sikeres",
130 		"Be-/kimeneti hiba",
131 		"Érvénytelen paraméter",
132 		"Hozzáférés megtagadva",
133 		"Az eszköz nem található (eltávolították?)",
134 		"Nem található",
135 		"Az erőforrás foglalt",
136 		"Időtúllépés",
137 		"Túlcsordulás",
138 		"Törött adatcsatorna",
139 		"Rendszerhívás megszakítva",
140 		"Nincs elég memória",
141 		"A művelet nem támogatott ezen a rendszeren",
142 		"Általános hiba",
143 	},
144 };
145 
146 static const char * const (*usbi_error_strings)[LIBUSB_ERROR_COUNT] = &usbi_localized_errors[0];
147 
148 /** \ingroup libusb_misc
149  * Set the language, and only the language, not the encoding! used for
150  * translatable libusb messages.
151  *
152  * This takes a locale string in the default setlocale format: lang[-region]
153  * or lang[_country_region][.codeset]. Only the lang part of the string is
154  * used, and only 2 letter ISO 639-1 codes are accepted for it, such as "de".
155  * The optional region, country_region or codeset parts are ignored. This
156  * means that functions which return translatable strings will NOT honor the
157  * specified encoding.
158  * All strings returned are encoded as UTF-8 strings.
159  *
160  * If libusb_setlocale() is not called, all messages will be in English.
161  *
162  * The following functions return translatable strings: libusb_strerror().
163  * Note that the libusb log messages controlled through libusb_set_debug()
164  * are not translated, they are always in English.
165  *
166  * For POSIX UTF-8 environments if you want libusb to follow the standard
167  * locale settings, call libusb_setlocale(setlocale(LC_MESSAGES, NULL)),
168  * after your app has done its locale setup.
169  *
170  * \param locale locale-string in the form of lang[_country_region][.codeset]
171  * or lang[-region], where lang is a 2 letter ISO 639-1 code
172  * \returns LIBUSB_SUCCESS on success
173  * \returns LIBUSB_ERROR_INVALID_PARAM if the locale doesn't meet the requirements
174  * \returns LIBUSB_ERROR_NOT_FOUND if the requested language is not supported
175  * \returns a LIBUSB_ERROR code on other errors
176  */
177 
libusb_setlocale(const char * locale)178 int API_EXPORTED libusb_setlocale(const char *locale)
179 {
180 	size_t i;
181 
182 	if (!locale || strlen(locale) < 2
183 	    || (locale[2] != '\0' && locale[2] != '-' && locale[2] != '_' && locale[2] != '.'))
184 		return LIBUSB_ERROR_INVALID_PARAM;
185 
186 	for (i = 0; i < ARRAYSIZE(usbi_locale_supported); i++) {
187 		if (usbi_locale_supported[i][0] == tolower((unsigned char)locale[0])
188 		    && usbi_locale_supported[i][1] == tolower((unsigned char)locale[1]))
189 			break;
190 	}
191 
192 	if (i == ARRAYSIZE(usbi_locale_supported))
193 		return LIBUSB_ERROR_NOT_FOUND;
194 
195 	usbi_error_strings = &usbi_localized_errors[i];
196 
197 	return LIBUSB_SUCCESS;
198 }
199 
200 /** \ingroup libusb_misc
201  * Returns a constant string with a short description of the given error code,
202  * this description is intended for displaying to the end user and will be in
203  * the language set by libusb_setlocale().
204  *
205  * The returned string is encoded in UTF-8.
206  *
207  * The messages always start with a capital letter and end without any dot.
208  * The caller must not free() the returned string.
209  *
210  * \param errcode the error code whose description is desired
211  * \returns a short description of the error code in UTF-8 encoding
212  */
libusb_strerror(int errcode)213 DEFAULT_VISIBILITY const char * LIBUSB_CALL libusb_strerror(int errcode)
214 {
215 	int errcode_index = -errcode;
216 
217 	if (errcode_index < 0 || errcode_index >= LIBUSB_ERROR_COUNT) {
218 		/* "Other Error", which should always be our last message, is returned */
219 		errcode_index = LIBUSB_ERROR_COUNT - 1;
220 	}
221 
222 	return (*usbi_error_strings)[errcode_index];
223 }
224