unesc.c 969 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /*
  2. * upas/unesc - interpret =?foo?bar?=char?= escapes
  3. */
  4. #include <u.h>
  5. #include <libc.h>
  6. #include <bio.h>
  7. int
  8. hex(int c)
  9. {
  10. if('0' <= c && c <= '9')
  11. return c - '0';
  12. if('a' <= c && c <= 'f')
  13. return c - 'a' + 10;
  14. if('A' <= c && c <= 'F')
  15. return c - 'A' + 10;
  16. return 0;
  17. }
  18. void
  19. main(void)
  20. {
  21. int c;
  22. Biobuf bin, bout;
  23. Binit(&bin, 0, OREAD);
  24. Binit(&bout, 1, OWRITE);
  25. while((c = Bgetc(&bin)) != Beof)
  26. if(c != '=')
  27. Bputc(&bout, c);
  28. else if((c = Bgetc(&bin)) != '?'){
  29. Bputc(&bout, '=');
  30. Bputc(&bout, c);
  31. } else {
  32. while((c = Bgetc(&bin)) != Beof && c != '?')
  33. continue; /* consume foo */
  34. while((c = Bgetc(&bin)) != Beof && c != '?')
  35. continue; /* consume bar */
  36. while((c = Bgetc(&bin)) != Beof && c != '?'){
  37. if(c == '='){
  38. c = hex(Bgetc(&bin)) << 4;
  39. c |= hex(Bgetc(&bin));
  40. }
  41. Bputc(&bout, c);
  42. }
  43. c = Bgetc(&bin); /* consume '=' */
  44. if (c != '=')
  45. Bungetc(&bin);
  46. }
  47. Bterm(&bout);
  48. exits(0);
  49. }