urlcode.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * urlcode.c
  3. *
  4. * Created on: 18.01.2016
  5. * Author: pavel
  6. */
  7. #include <ctype.h>
  8. #include <stdint.h>
  9. /* Converts a hex character to its integer value */
  10. char from_hex(char ch) {
  11. return isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10;
  12. }
  13. /* Converts an integer value to its hex character*/
  14. char to_hex(char code) {
  15. static char hex[] = "0123456789abcdef";
  16. return hex[code & 15];
  17. }
  18. /* Returns a url-encoded version of str */
  19. /* IMPORTANT: be sure that outbuf is big enougth */
  20. char *url_encode(char *outbuf, uint32_t outlen, char *inbuf) {
  21. char *pstr = inbuf, *buf = outbuf, *pbuf = buf;
  22. while ((*pstr) && outlen > 3) {
  23. if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~')
  24. *pbuf++ = *pstr;
  25. else if (*pstr == ' ') {
  26. *pbuf++ = '+';
  27. outlen--;
  28. }
  29. else {
  30. *pbuf++ = '%', *pbuf++ = to_hex(*pstr >> 4), *pbuf++ = to_hex(*pstr & 15);
  31. outlen-=3;
  32. }
  33. pstr++;
  34. }
  35. *pbuf = '\0';
  36. return buf;
  37. }
  38. /* Returns a url-decoded version of str */
  39. /* IMPORTANT: be sure that outbuf is big enougth */
  40. char *url_decode(char *outbuf, uint32_t outlen, char *inbuf) {
  41. char *pstr = inbuf, *buf = outbuf, *pbuf = buf;
  42. while ((*pstr) && outlen > 1) {
  43. if (*pstr == '%') {
  44. if (pstr[1] && pstr[2]) {
  45. *pbuf++ = from_hex(pstr[1]) << 4 | from_hex(pstr[2]);
  46. pstr += 2;
  47. }
  48. } else if (*pstr == '+') {
  49. *pbuf++ = ' ';
  50. } else {
  51. *pbuf++ = *pstr;
  52. }
  53. pstr++;
  54. outlen--;
  55. }
  56. *pbuf = '\0';
  57. return buf;
  58. }