summaryrefslogtreecommitdiff
path: root/escape.c
blob: be801e24e7aaddfef85a4ccd5dc56d48c3a50fbd (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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

#include "request.h"

char *real_escape_string(const byte *src, int size)
{
    char *escaped;
    char *pos;

    if (memchr(src, '\0', size - 1) || memchr(src, '\n', size) || memchr(src, '\r', size)) {
	fprintf(stderr, "cannot handle this string\n");
	return NULL;
    }

    pos = escaped = malloc(sizeof(char) * (size * 2 + 1));

    if (escaped == NULL) {
	fprintf(stderr, "malloc failed: %m\n");
	return NULL;
    }

    for (int i = 0; i < size; ++i) {
	if (!isalnum(src[i])) {
	    *escaped++ = '\\';
	}
	*escaped++ = src[i];
    }

    *escaped = '\0';

    return pos;
}