Debian Codegraph @

src/xml.c

raw ◀ ▶
Source reconstructed at patch state 1 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 /* $Id: xml.c,v 1.37 2004/11/11 03:39:34 mgrouch Exp $ */
2
3 /*
4
5 XMLStarlet: Command Line Toolkit to query/edit/check/transform XML documents
6
7 Copyright (c) 2002 Mikhail Grushinskiy. All Rights Reserved.
8
9 Permission is hereby granted, free of charge, to any person obtaining a copy
10 of this software and associated documentation files (the "Software"), to deal
11 in the Software without restriction, including without limitation the rights
12 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 copies of the Software, and to permit persons to whom the Software is
14 furnished to do so, subject to the following conditions:
15
16 The above copyright notice and this permission notice shall be included in
17 all copies or substantial portions of the Software.
18
19 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 THE SOFTWARE.
26
27 */
28
29 #include <config.h>
30 #include <version.h>
31
32 #include <assert.h>
33 #include <string.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36
37 #include <libxslt/xslt.h>
38 #include <libxslt/xsltconfig.h>
39
40 #ifdef _WIN32
41 # define WIN32_LEAN_AND_MEAN
42 # include <windows.h>
43 # include <shellapi.h> /* CommandLineToArgvW() */
44 #endif
45
46 #include "xmlstar.h"
47
48 gOptions globalOptions;
49
50 static const xmlChar* XMLSTAR_NS = BAD_CAST "http://xmlstar.sourceforge.net";
51 static const xmlChar* XMLSTAR_NS_PREFIX = BAD_CAST "xstar";
52
53 extern int edMain(int argc, char **argv);
54 extern int selMain(int argc, char **argv);
55 extern int trMain(int argc, char **argv);
56 extern int valMain(int argc, char **argv);
57 extern int foMain(int argc, char **argv);
58 extern int elMain(int argc, char **argv);
59 extern int c14nMain(int argc, char **argv);
60 extern int lsMain(int argc, char **argv);
61 extern int pyxMain(int argc, char **argv);
62 extern int depyxMain(int argc, char **argv);
63 extern int escMain(int argc, char **argv, int escape);
64
65 const char more_info[] =
66 "XMLStarlet is a command line toolkit to query/edit/check/transform\n"
67 "XML documents (for more information see http://xmlstar.sourceforge.net/)\n";
68
69 const char libxslt_more_info[] =
70 "\n"
71 "Current implementation uses libxslt from GNOME codebase as XSLT processor\n"
72 "(see http://xmlsoft.org/ for more details)\n";
73
74 /**
75 * Display usage syntax
76 */
77 void
78 usage(int argc, char **argv, exit_status status)
79 {
80 extern void fprint_usage(FILE* o, const char* argv0);
81 FILE* o = (status == EXIT_SUCCESS)? stdout : stderr;
82 fprint_usage(o, argv[0]);
83 fprintf(o, "%s", more_info);
84 exit(status);
85 }
86
87 /**
88 * Initialize global command line options
89 */
90 void
91 gInitOptions(gOptionsPtr ops)
92 {
93 ops->quiet = 0;
94 ops->doc_namespace = 1;
95 }
96
97 /**
98 * Error reporting functions
99 */
100 void reportGenericError(void* ctx, const char * msg, ...) {
101 /* do nothing */
102 }
103
104 /* by default all errors are reported */
105 static ErrorInfo errorInfo = { NULL, NULL, VERBOSE, CONTINUE };
106
107 void reportError(void *ptr, xmlErrorPtr error)
108 {
109 ErrorInfo *errorInfo = (ErrorInfo*) ptr;
110 assert(errorInfo);
111
112 if (errorInfo->verbose)
113 {
114 int msglen;
115 int domain = error->domain;
116 const char *filename =
117 error->file? error->file :
118 errorInfo? errorInfo->filename :
119 NULL;
120 xmlTextReaderPtr reader = errorInfo->xmlReader;
121
122 int line = (!filename)? 0 :
123 (reader)? xmlTextReaderGetParserLineNumber(reader) :
124 error->line;
125 int column = (!filename)? 0 :
126 (reader)? xmlTextReaderGetParserColumnNumber(reader) :
127 error->int2;
128 if (line)
129 {
130 fprintf(stderr, "%s:%d.%d: ", filename, line, column);
131 }
132
133 msglen = strlen(error->message);
134 if (error->message[msglen-1] == '\n')
135 error->message[msglen-1] = '\0';
136 fprintf(stderr, "%s", error->message);
137
138 /* only print extra info if it's not in message */
139 if (error->str1 && strstr(error->message, error->str1) == NULL) {
140 fprintf(stderr, ": %s", error->str1);
141 if (error->str2 && strstr(error->message, error->str2) == NULL) {
142 fprintf(stderr, ", %s", error->str2);
143 }
144 if (error->str3 && strstr(error->message, error->str3) == NULL) {
145 fprintf(stderr, ", %s", error->str3);
146 }
147 }
148 fprintf(stderr, "%s", "\n");
149
150
151 if ((domain == XML_FROM_PARSER) || (domain == XML_FROM_HTML) ||
152 (domain == XML_FROM_DTD) || (domain == XML_FROM_NAMESPACE) ||
153 (domain == XML_FROM_IO) || (domain == XML_FROM_VALID)) {
154 xmlParserCtxtPtr ctxt = error->ctxt;
155 if (ctxt) xmlParserPrintFileContext(ctxt->input);
156 }
157 }
158 if (errorInfo->stop == STOP) {
159 exit(EXIT_FAILURE);
160 }
161 }
162
163 void
164 suppressErrors(void)
165 {
166 xmlSetGenericErrorFunc(NULL, reportGenericError);
167 errorInfo.verbose = QUIET;
168 }
169
170 #define CHECK_MEM(ret) if (!ret) \
171 (fprintf(stderr, "%s", "out of memory\n"), exit(EXIT_INTERNAL_ERROR))
172
173 void*
174 xmalloc(size_t size)
175 {
176 void *ret = malloc(size);
177 CHECK_MEM(ret);
178 return ret;
179 }
180 void*
181 xrealloc(void *ptr, size_t size)
182 {
183 void *ret = realloc(ptr, size);
184 CHECK_MEM(ret);
185 return ret;
186 }
187 char*
188 xstrdup(const char *str)
189 {
190 char *ret = (char*) xmlStrdup(BAD_CAST str);
191 CHECK_MEM(ret);
192 return ret;
193 }
194
195
196 #ifdef _WIN32
197 /* On Windows, it's not really practical to get argv in UTF-8, so we have to do
198 this little dance. */
199 static void
200 gGetUnicodeOptions(int argc, char **argv)
201 {
202 int nArgs, i;
203 LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
204 assert(nArgs == argc);
205
206 for (i = 0; i < argc; i++) {
207 char *utf;
208 int utflen = WideCharToMultiByte(CP_UTF8, 0,
209 szArglist[i], -1,
210 NULL, 0, NULL, NULL);
211 if (utflen <= 0) {
212 fprintf(stderr, "Error decoding argument %d\n", i);
213 exit(EXIT_BAD_ARGS);
214 }
215 utf = malloc(utflen);
216 WideCharToMultiByte(CP_UTF8, 0,
217 szArglist[i], -1,
218 utf, utflen, NULL, NULL);
219 argv[i] = utf;
220 }
221 LocalFree(szArglist);
222 }
223 #else
224 # define gGetUnicodeOptions(argc, argv)
225 #endif
226
227 /**
228 * Parse global command line options
229 */
230 void
231 gParseOptions(gOptionsPtr ops, int *argc, char **argv)
232 {
233 int i, j;
234 i = 1;
235 while(i < *argc)
236 {
237 if (!strcmp(argv[i], "--quiet") || !strcmp(argv[i], "-q"))
238 {
239 ops->quiet = 1;
240 i++;
241 }
242 else if (!strcmp(argv[i], "--no-doc-namespace"))
243 {
244 ops->doc_namespace = 0;
245 i++;
246 }
247 else if (!strcmp(argv[i], "--doc-namespace"))
248 {
249 ops->doc_namespace = 1;
250 i++;
251 }
252 else if (!strcmp(argv[i], "--version"))
253 {
254 fprintf(stdout, "%s\n"
255 "compiled against libxml2 %s, linked with %s\n"
256 "compiled against libxslt %s, linked with %s\n",
257 VERSION,
258 LIBXML_DOTTED_VERSION, xmlParserVersion,
259 LIBXSLT_DOTTED_VERSION, xsltEngineVersion);
260 exit(EXIT_SUCCESS);
261 }
262 else if (!strcmp(argv[i], "--help"))
263 {
264 usage(*argc, argv, EXIT_SUCCESS);
265 }
266 else if (argv[i][0] != '-')
267 {
268 /* remove parsed arguments */
269 i--;
270 for (j = 1; j < *argc; j++) {
271 if (j < *argc - i)
272 argv[j] = argv[j + i];
273 else
274 argv[j] = 0;
275 }
276 *argc -= i;
277 return;
278 }
279 else
280 {
281 usage(*argc, argv, EXIT_BAD_ARGS);
282 }
283 }
284 }
285
286 /**
287 * This is the main function
288 */
289 int
290 main(int argc, char **argv)
291 {
292 int ret = 0;
293
294 xmlMemSetup(free, xmalloc, xrealloc, xstrdup);
295
296 gGetUnicodeOptions(argc, argv);
297 gInitOptions(&globalOptions);
298 gParseOptions(&globalOptions, &argc, argv);
299
300 xmlSetStructuredErrorFunc(&errorInfo, reportError);
301 if (globalOptions.quiet)
302 suppressErrors();
303
304 if (argc <= 1)
305 {
306 usage(argc, argv, EXIT_BAD_ARGS);
307 }
308 else if (!strcmp(argv[1], "ed") || !strcmp(argv[1], "edit"))
309 {
310 ret = edMain(argc, argv);
311 }
312 else if (!strcmp(argv[1], "sel") || !strcmp(argv[1], "select"))
313 {
314 ret = selMain(argc, argv);
315 }
316 else if (!strcmp(argv[1], "tr") || !strcmp(argv[1], "transform"))
317 {
318 ret = trMain(argc, argv);
319 }
320 else if (!strcmp(argv[1], "fo") || !strcmp(argv[1], "format"))
321 {
322 ret = foMain(argc, argv);
323 }
324 else if (!strcmp(argv[1], "val") || !strcmp(argv[1], "validate"))
325 {
326 ret = valMain(argc, argv);
327 }
328 else if (!strcmp(argv[1], "el") || !strcmp(argv[1], "elements"))
329 {
330 ret = elMain(argc, argv);
331 }
332 else if (!strcmp(argv[1], "c14n") || !strcmp(argv[1], "canonic"))
333 {
334 ret = c14nMain(argc, argv);
335 }
336 else if (!strcmp(argv[1], "ls") || !strcmp(argv[1], "list"))
337 {
338 ret = lsMain(argc, argv);
339 }
340 else if (!strcmp(argv[1], "pyx") || !strcmp(argv[1], "xmln"))
341 {
342 ret = pyxMain(argc, argv);
343 }
344 else if (!strcmp(argv[1], "depyx") || !strcmp(argv[1], "p2x"))
345 {
346 ret = depyxMain(argc, argv);
347 }
348 else if (!strcmp(argv[1], "esc") || !strcmp(argv[1], "escape"))
349 {
350 ret = escMain(argc, argv, 1);
351 }
352 else if (!strcmp(argv[1], "unesc") || !strcmp(argv[1], "unescape"))
353 {
354 ret = escMain(argc, argv, 0);
355 }
356 else
357 {
358 usage(argc, argv, EXIT_BAD_ARGS);
359 }
360
361 exit(ret);
362 }
363
364
365 void
366 registerXstarVariable(xmlXPathContextPtr ctxt,
367 const char* name, xmlXPathObjectPtr value)
368 {
369 xmlXPathRegisterVariableNS(ctxt, BAD_CAST name, XMLSTAR_NS, value);
370 }
371
372 static xmlXPathObjectPtr varLookupFallbackToXstarNS(void* ctxt_vp,
373 const xmlChar* name, const xmlChar* ns_uri)
374 {
375 xmlXPathObjectPtr ret;
376 xmlXPathContextPtr ctxt = ctxt_vp;
377
378 ctxt->varLookupFunc = NULL; /* avoid infinite recursion! */
379
380 /* first get the default lookup value */
381 ret = xmlXPathVariableLookupNS(ctxt, name, ns_uri);
382
383 if (!ret && !ns_uri) {
384 /* if we didn't find anything, and there was no namespace given,
385 try looking in XMLStarlet namespace */
386 ret = xmlXPathVariableLookupNS(ctxt, name, XMLSTAR_NS);
387 }
388
389 ctxt->varLookupFunc = &varLookupFallbackToXstarNS;
390 return ret;
391 }
392
393 void
394 registerXstarNs(xmlXPathContextPtr ctxt)
395 {
396 xmlXPathRegisterVariableLookup(ctxt, &varLookupFallbackToXstarNS, ctxt);
397 xmlXPathRegisterNs(ctxt, XMLSTAR_NS_PREFIX, XMLSTAR_NS);
398 }
399
400
401 static void bad_ns_opt(const char *msg)
402 {
403 fprintf(stderr, "Bad namespace option: %s\n", msg);
404 exit(EXIT_BAD_ARGS);
405 }
406
407 const xmlChar *default_ns = NULL;
408
409 #define MAX_NS_ARGS 256
410 xmlChar *ns_arr[2 * MAX_NS_ARGS + 1];
411
412 /**
413 * Parse command line for -N <prefix>=<namespace> arguments
414 */
415 int
416 parseNSArr(xmlChar** ns_arr, int* plen, int argc, char **argv)
417 {
418 int i = 0;
419 *plen = 0;
420 ns_arr[0] = 0;
421
422 for (i=0; i<argc; i++)
423 {
424 int prefix_len;
425 xmlChar *name, *value;
426 const xmlChar *equal_sign;
427
428 /* check for end of arguments */
429 if (argv[i] == 0 || argv[i][0] != '-')
430 break;
431 if (strcmp(argv[i], "-N") != 0)
432 continue;
433
434 i++;
435 if (i >= argc) bad_ns_opt("-N without argument");
436
437 equal_sign = xmlStrchr((const xmlChar*) argv[i], '=');
438 if (!equal_sign)
439 bad_ns_opt("namespace should have the form <prefix>=<url>");
440 prefix_len = equal_sign - (const xmlChar*) argv[i];
441
442 name = xmlStrndup((const xmlChar*) argv[i], prefix_len);
443 value = xmlStrdup((const xmlChar*) argv[i]+prefix_len+1);
444
445 if (*plen >= MAX_NS_ARGS)
446 {
447 fprintf(stderr, "%s", "too many namespaces increase MAX_NS_ARGS\n");
448 exit(EXIT_BAD_ARGS);
449 }
450
451 ns_arr[*plen] = name;
452 (*plen)++;
453 ns_arr[*plen] = value;
454 (*plen)++;
455 ns_arr[*plen] = 0;
456
457 }
458
459 return i;
460 }
461
462 /**
463 * Cleanup memory allocated by namespaces arguments
464 */
465 void
466 cleanupNSArr(xmlChar **ns_arr)
467 {
468 xmlChar **p = ns_arr;
469
470 while (*p)
471 {
472 xmlFree(*p);
473 p++;
474 }
475 }