66 if(!result) { |
67 if(!result) { |
67 flib_log_e("Out of memory trying to calloc %zu objects of %zu bytes each.", count, elementsize); |
68 flib_log_e("Out of memory trying to calloc %zu objects of %zu bytes each.", count, elementsize); |
68 } |
69 } |
69 return result; |
70 return result; |
70 } |
71 } |
|
72 |
|
73 static bool isAsciiAlnum(char c) { |
|
74 return (c>='0' && c<='9') || (c>='a' && c <='z') || (c>='A' && c <='Z'); |
|
75 } |
|
76 |
|
77 char *flib_urlencode(const char *inbuf) { |
|
78 if(!inbuf) { |
|
79 return NULL; |
|
80 } |
|
81 size_t insize = strlen(inbuf); |
|
82 if(insize > SIZE_MAX/4) { |
|
83 flib_log_e("String too long in flib_urlencode: %zu bytes.", insize); |
|
84 return NULL; |
|
85 } |
|
86 |
|
87 char *outbuf = flib_malloc(insize*3+1); |
|
88 if(!outbuf) { |
|
89 return NULL; |
|
90 } |
|
91 |
|
92 size_t inpos = 0, outpos = 0; |
|
93 while(inbuf[inpos]) { |
|
94 if(isAsciiAlnum(inbuf[inpos])) { |
|
95 outbuf[outpos++] = inbuf[inpos++]; |
|
96 } else { |
|
97 if(snprintf(outbuf+outpos, 4, "%%%02X", (unsigned)((uint8_t*)inbuf)[inpos])<0) { |
|
98 flib_log_e("printf error in flib_urlencode"); |
|
99 free(outbuf); |
|
100 return NULL; |
|
101 } |
|
102 inpos++; |
|
103 outpos += 3; |
|
104 } |
|
105 } |
|
106 outbuf[outpos] = 0; |
|
107 char *shrunk = realloc(outbuf, outpos+1); |
|
108 return shrunk ? shrunk : outbuf; |
|
109 } |
|
110 |
|
111 char *flib_urldecode(const char *inbuf) { |
|
112 char *outbuf = flib_malloc(strlen(inbuf)+1); |
|
113 if(!outbuf) { |
|
114 return NULL; |
|
115 } |
|
116 |
|
117 size_t inpos = 0, outpos = 0; |
|
118 while(inbuf[inpos]) { |
|
119 if(inbuf[inpos] == '%' && isxdigit(inbuf[inpos+1]) && isxdigit(inbuf[inpos+2])) { |
|
120 char temp[3] = {inbuf[inpos+1],inbuf[inpos+2],0}; |
|
121 outbuf[outpos++] = strtol(temp, NULL, 16); |
|
122 inpos += 3; |
|
123 } else { |
|
124 outbuf[outpos++] = inbuf[inpos++]; |
|
125 } |
|
126 } |
|
127 outbuf[outpos] = 0; |
|
128 char *shrunk = realloc(outbuf, outpos+1); |
|
129 return shrunk ? shrunk : outbuf; |
|
130 } |