summaryrefslogtreecommitdiff
path: root/src/util/virbuffer.c
blob: 01d04cc4f97f6d683fc9762340a51c5aa008d88e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
/*
 * virbuffer.c: buffers for libvirt
 *
 * Copyright (C) 2005-2008, 2010-2015 Red Hat, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see
 * <http://www.gnu.org/licenses/>.
 */

#include <config.h>

#include <stdarg.h>

#include "virbuffer.h"

#define VIR_FROM_THIS VIR_FROM_NONE

/**
 * virBufferAdjustIndent:
 * @buf: the buffer
 * @indent: adjustment to make
 *
 * Alter the auto-indent value by adding indent (positive to increase,
 * negative to decrease).  Automatic indentation is performed by all
 * additive functions when the existing buffer is empty or ends with a
 * newline (however, note that no indentation is added after newlines
 * embedded in an appended string).  If @indent would cause overflow, the
 * indentation level is truncated.
 */
void
virBufferAdjustIndent(virBuffer *buf, int indent)
{
    if (!buf)
        return;

    if (indent > 0) {
        if (INT_MAX - indent < buf->indent) {
            buf->indent = INT_MAX;
            return;
        }
    } else {
        if (buf->indent < -indent) {
            buf->indent = 0;
            return;
        }
    }

    buf->indent += indent;
}


/**
 * virBufferSetIndent:
 * @buf: the buffer
 * @indent: new indentation size.
 *
 * Set the auto-indent value to @indent. See virBufferAdjustIndent on how auto
 * indentation is applied.
 */
void
virBufferSetIndent(virBuffer *buf, int indent)
{
    if (!buf)
        return;

    buf->indent = indent;
}


/**
 * virBufferGetIndent:
 * @buf: the buffer
 *
 * Return the current auto-indent setting of @buf.
 */
size_t
virBufferGetIndent(const virBuffer *buf)
{
    return buf->indent;
}


/**
 * virBufferGetEffectiveIndent:
 * @buf: the buffer
 *
 * Returns the number of spaces that need to be appended to @buf to honour
 * auto-indentation.
 */
size_t
virBufferGetEffectiveIndent(const virBuffer *buf)
{
    if (buf->str && buf->str->len && buf->str->str[buf->str->len - 1] != '\n')
        return 0;

    return buf->indent;
}


/**
 * virBufferInitialize
 * @buf: the buffer
 *
 * Ensures that the internal GString container is allocated.
 */
static void
virBufferInitialize(virBuffer *buf)
{
    if (!buf->str)
        buf->str = g_string_new(NULL);
}


static void
virBufferApplyIndent(virBuffer *buf)
{
    const char space[] = "                               ";
    size_t spacesz = sizeof(space) - 1;
    size_t toindent = virBufferGetEffectiveIndent(buf);

    if (toindent == 0)
        return;

    while (toindent > spacesz) {
        g_string_append_len(buf->str, space, spacesz);
        toindent -= spacesz;
    }

    g_string_append_len(buf->str, space, toindent);
}


/**
 * virBufferAdd:
 * @buf: the buffer to append to
 * @str: the string
 * @len: the number of bytes to add, or -1
 *
 * Add a string range to an XML buffer. If @len == -1, the length of
 * str is recomputed to the full string.  Auto indentation may be applied.
 *
 */
void
virBufferAdd(virBuffer *buf, const char *str, int len)
{
    if (!str || !buf)
        return;

    virBufferInitialize(buf);
    virBufferApplyIndent(buf);

    if (len < 0)
        g_string_append(buf->str, str);
    else
        g_string_append_len(buf->str, str, len);
}

/**
 * virBufferAddBuffer:
 * @buf: the buffer to append to
 * @toadd: the buffer to append
 *
 * Add a buffer into another buffer without need to go through:
 * virBufferContentAndReset(), virBufferAdd(). Auto indentation
 * is (intentionally) NOT applied!
 *
 * The @toadd virBuffer is consumed and cleared.
 */
void
virBufferAddBuffer(virBuffer *buf, virBuffer *toadd)
{
    if (!toadd || !toadd->str)
        return;

    if (buf) {
        virBufferInitialize(buf);
        g_string_append_len(buf->str, toadd->str->str, toadd->str->len);
    }

    virBufferFreeAndReset(toadd);
}

/**
 * virBufferAddChar:
 * @buf: the buffer to append to
 * @c: the character to add
 *
 * Add a single character 'c' to a buffer.  Auto indentation may be applied.
 *
 */
void
virBufferAddChar(virBuffer *buf, char c)
{
    virBufferAdd(buf, &c, 1);
}

/**
 * virBufferCurrentContent:
 * @buf: Buffer
 *
 * Get the current content from the buffer.  The content is only valid
 * until the next operation on @buf, and an empty string is returned if
 * no content is present yet.
 *
 * Returns the buffer content or NULL in case of error.
 */
const char *
virBufferCurrentContent(virBuffer *buf)
{
    if (!buf)
        return NULL;

    if (!buf->str ||
        buf->str->len == 0)
        return "";

    return buf->str->str;
}

/**
 * virBufferContentAndReset:
 * @buf: Buffer
 *
 * Get the content from the buffer and free (only) the buffer structure.
 * The caller owns the returned string & should free it when no longer
 * required. The buffer object is reset to its initial state.  This
 * interface intentionally returns NULL instead of an empty string if
 * there is no content.
 *
 * Returns the buffer content or NULL in case of error.
 */
char *
virBufferContentAndReset(virBuffer *buf)
{
    char *str = NULL;

    if (!buf)
        return NULL;

    if (buf->str)
        str = g_string_free(buf->str, false);

    memset(buf, 0, sizeof(*buf));
    return str;
}

/**
 * virBufferFreeAndReset:
 * @buf: the buffer to free and reset
 *
 * Frees the buffer content and resets the buffer structure.
 */
void virBufferFreeAndReset(virBuffer *buf)
{
    if (!buf)
        return;

    if (buf->str)
        g_string_free(buf->str, true);

    memset(buf, 0, sizeof(*buf));
}

/**
 * virBufferUse:
 * @buf: the usage of the string in the buffer
 *
 * Return the string usage in bytes
 */
size_t
virBufferUse(const virBuffer *buf)
{
    if (!buf || !buf->str)
        return 0;

    return buf->str->len;
}

/**
 * virBufferAsprintf:
 * @buf: the buffer to append to
 * @format: the format
 * @...: the variable list of arguments
 *
 * Do a formatted print to an XML buffer.  Auto indentation may be applied.
 */
void
virBufferAsprintf(virBuffer *buf, const char *format, ...)
{
    va_list argptr;
    va_start(argptr, format);
    virBufferVasprintf(buf, format, argptr);
    va_end(argptr);
}

/**
 * virBufferVasprintf:
 * @buf: the buffer to append to
 * @format: the format
 * @argptr: the variable list of arguments
 *
 * Do a formatted print to an XML buffer.  Auto indentation may be applied.
 */
void
virBufferVasprintf(virBuffer *buf, const char *format, va_list argptr)
{
    if ((format == NULL) || (buf == NULL))
        return;

    virBufferInitialize(buf);
    virBufferApplyIndent(buf);

    g_string_append_vprintf(buf->str, format, argptr);
}


/**
 * virBufferEscapeString:
 * @buf: the buffer to append to
 * @format: a printf like format string but with only one %s parameter
 * @str: the string argument which needs to be escaped
 *
 * Do a formatted print with a single string to an XML buffer. The
 * string is escaped for use in XML.  If @str is NULL, nothing is
 * added (not even the rest of @format).  Auto indentation may be
 * applied.
 */
void
virBufferEscapeString(virBuffer *buf, const char *format, const char *str)
{
    int len;
    g_autofree char *escaped = NULL;
    char *out;
    const char *cur;
    const char forbidden_characters[] = {
        0x01,   0x02,   0x03,   0x04,   0x05,   0x06,   0x07,   0x08,
        /*\t*/  /*\n*/  0x0B,   0x0C,   /*\r*/  0x0E,   0x0F,   0x10,
        0x11,   0x12,   0x13,   0x14,   0x15,   0x16,   0x17,   0x18,
        0x19,   '"',    '&',    '\'',   '<',    '>',
        '\0'
    };

    if ((format == NULL) || (buf == NULL) || (str == NULL))
        return;

    len = strlen(str);
    if (strcspn(str, forbidden_characters) == len) {
        virBufferAsprintf(buf, format, str);
        return;
    }

    escaped = g_malloc0_n(len + 1, 6);

    cur = str;
    out = escaped;
    while (*cur != 0) {
        if (*cur == '<') {
            *out++ = '&';
            *out++ = 'l';
            *out++ = 't';
            *out++ = ';';
        } else if (*cur == '>') {
            *out++ = '&';
            *out++ = 'g';
            *out++ = 't';
            *out++ = ';';
        } else if (*cur == '&') {
            *out++ = '&';
            *out++ = 'a';
            *out++ = 'm';
            *out++ = 'p';
            *out++ = ';';
        } else if (*cur == '"') {
            *out++ = '&';
            *out++ = 'q';
            *out++ = 'u';
            *out++ = 'o';
            *out++ = 't';
            *out++ = ';';
        } else if (*cur == '\'') {
            *out++ = '&';
            *out++ = 'a';
            *out++ = 'p';
            *out++ = 'o';
            *out++ = 's';
            *out++ = ';';
        } else if (!strchr(forbidden_characters, *cur)) {
            /*
             * default case, just copy !
             * Note that character over 0x80 are likely to give problem
             * with UTF-8 XML, but since our string don't have an encoding
             * it's hard to handle properly we have to assume it's UTF-8 too
             */
            *out++ = *cur;
        } else {
            /* silently ignore control characters */
        }
        cur++;
    }
    *out = 0;

    virBufferAsprintf(buf, format, escaped);
}

/**
 * virBufferEscapeSexpr:
 * @buf: the buffer to append to
 * @format: a printf like format string but with only one %s parameter
 * @str: the string argument which needs to be escaped
 *
 * Do a formatted print with a single string to an sexpr buffer. The
 * string is escaped to avoid generating a sexpr that xen will choke
 * on. This doesn't fully escape the sexpr, just enough for our code
 * to work.  Auto indentation may be applied.
 */
void
virBufferEscapeSexpr(virBuffer *buf,
                     const char *format,
                     const char *str)
{
    virBufferEscape(buf, '\\', "\\'", format, str);
}

/**
 * virBufferEscapeRegex:
 * @buf: the buffer to append to
 * @format: a printf like format string but with only one %s parameter
 * @str: the string argument which needs to be escaped
 *
 * Do a formatted print with a single string to a buffer.  The @str is
 * escaped to avoid using POSIX extended regular expression meta-characters.
 * Escaping is not applied to characters specified in @format. Auto
 * indentation may be applied.
 */
void
virBufferEscapeRegex(virBuffer *buf,
                     const char *format,
                     const char *str)
{
    virBufferEscape(buf, '\\', "^$.|?*+()[]{}\\", format, str);
}


/**
 * virBufferEscapeSQL:
 * @buf: the buffer to append to
 * @format: a printf like format string but with only one %s parameter
 * @str: the string argument which needs to be escaped
 *
 * Do a formatted print with a single string to a buffer.  The @str is
 * escaped to prevent SQL injection (format is expected to contain \"%s\").
 * Auto indentation may be applied.
 */
void
virBufferEscapeSQL(virBuffer *buf,
                   const char *format,
                   const char *str)
{
    virBufferEscape(buf, '\\', "'\"\\", format, str);
}


/**
 * virBufferEscape:
 * @buf: the buffer to append to
 * @escape: the escape character to inject
 * @toescape: NUL-terminated list of characters to escape
 * @format: a printf like format string but with only one %s parameter
 * @str: the string argument which needs to be escaped
 *
 * Do a formatted print with a single string to a buffer.  Any characters
 * in the provided list that are contained in @str are escaped with the
 * given escape.  Escaping is not applied to characters specified in @format.
 * Auto indentation may be applied.
 */
void
virBufferEscape(virBuffer *buf, char escape, const char *toescape,
                const char *format, const char *str)
{
    int len;
    g_autofree char *escaped = NULL;
    char *out;
    const char *cur;

    if ((format == NULL) || (buf == NULL) || (str == NULL))
        return;

    len = strlen(str);
    if (strcspn(str, toescape) == len) {
        virBufferAsprintf(buf, format, str);
        return;
    }

    escaped = g_malloc0_n(len + 1, 2);

    cur = str;
    out = escaped;
    while (*cur != 0) {
        if (strchr(toescape, *cur))
            *out++ = escape;
        *out++ = *cur;
        cur++;
    }
    *out = 0;

    virBufferAsprintf(buf, format, escaped);
}


/**
 * virBufferURIEncodeString:
 * @buf: the buffer to append to
 * @str: the string argument which will be URI-encoded
 *
 * Append the string to the buffer.  The string will be URI-encoded
 * during the append (ie any non alphanumeric characters are replaced
 * with '%xx' hex sequences).  Auto indentation may be applied.
 */
void
virBufferURIEncodeString(virBuffer *buf, const char *str)
{
    if ((buf == NULL) || (str == NULL))
        return;

    virBufferInitialize(buf);
    virBufferApplyIndent(buf);

    g_string_append_uri_escaped(buf->str, str, NULL, false);
}

/**
 * virBufferEscapeShell:
 * @buf: the buffer to append to
 * @str: an unquoted string
 *
 * Quotes a string so that the shell (/bin/sh) will interpret the
 * quoted string to mean str.  Auto indentation may be applied.
 */
void
virBufferEscapeShell(virBuffer *buf, const char *str)
{
    g_autofree char *escaped = NULL;
    char *out;
    const char *cur;

    if ((buf == NULL) || (str == NULL))
        return;

    if (!*str) {
        virBufferAddLit(buf, "''");
        return;
    }

    /* Only quote if str includes shell metacharacters. */
    if (!strpbrk(str, "\r\t\n !\"#$&'()*;<>?[\\]^`{|}~")) {
        virBufferAdd(buf, str, -1);
        return;
    }

    escaped = g_malloc0_n(strlen(str) + 1, 4);

    cur = str;
    out = escaped;

    *out++ = '\'';
    while (*cur != 0) {
        if (*cur == '\'') {
            *out++ = '\'';
            /* Replace literal ' with a close ', a \', and a open ' */
            *out++ = '\\';
            *out++ = '\'';
        }
        *out++ = *cur++;
    }
    *out++ = '\'';
    *out = 0;

    virBufferAdd(buf, escaped, -1);
}

/**
 * virBufferStrcatVArgs:
 * @buf: the buffer to append to
 * @ap: variable argument structure
 *
 * See virBufferStrcat.
 */
void
virBufferStrcatVArgs(virBuffer *buf,
                     va_list ap)
{
    char *str;

    while ((str = va_arg(ap, char *)) != NULL)
        virBufferAdd(buf, str, -1);
}

/**
 * virBufferStrcat:
 * @buf: the buffer to append to
 * @...: the variable list of strings, the last argument must be NULL
 *
 * Concatenate strings to an XML buffer.  Auto indentation may be applied
 * after each string argument.
 */
void
virBufferStrcat(virBuffer *buf, ...)
{
    va_list ap;

    if (!buf)
        return;

    va_start(ap, buf);
    virBufferStrcatVArgs(buf, ap);
    va_end(ap);
}

/**
 * virBufferTrim:
 * @buf: the buffer to trim
 * @str: the string to be trimmed from the tail
 *
 * Trim the supplied string from the tail of the buffer.
 */
void
virBufferTrim(virBuffer *buf, const char *str)
{
    size_t len = 0;

    if (!buf || !buf->str)
        return;

    if (!str)
        return;

    len = strlen(str);

    if (len > buf->str->len ||
        memcmp(&buf->str->str[buf->str->len - len], str, len) != 0)
        return;

    g_string_truncate(buf->str, buf->str->len - len);
}

/**
 * virBufferTrimChars:
 * @buf: the buffer to trim
 * @trim: the characters to be trimmed
 *
 * Trim the tail of the buffer. The longest string that can be formed with
 * the characters from @trim is trimmed.
 */
void
virBufferTrimChars(virBuffer *buf, const char *trim)
{
    ssize_t i;

    if (!buf || !buf->str)
        return;

    if (!trim)
        return;

    for (i = buf->str->len - 1; i > 0; i--) {
        if (!strchr(trim, buf->str->str[i]))
            break;
    }

    g_string_truncate(buf->str, i + 1);
}

/**
 * virBufferTrimLen:
 * @buf: the buffer to trim
 * @len: the number of bytes to trim
 *
 * Trim the tail of a buffer.
 */
void
virBufferTrimLen(virBuffer *buf, int len)
{
    if (!buf || !buf->str)
        return;

    if (len > buf->str->len)
        return;

    g_string_truncate(buf->str, buf->str->len - len);
}

/**
 * virBufferAddStr:
 * @buf: the buffer to append to
 * @str: string to append
 *
 * Appends @str to @buffer. Applies autoindentation on the separate lines of
 * @str.
 */
void
virBufferAddStr(virBuffer *buf,
                const char *str)
{
    const char *end;

    if (!buf || !str)
        return;

    while (*str) {
        if ((end = strchr(str, '\n'))) {
            virBufferAdd(buf, str, (end - str) + 1);
            str = end + 1;
        } else {
            virBufferAdd(buf, str, -1);
            break;
        }
    }
}