redirected.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <bin.h>
  4. #include <httpd.h>
  5. int
  6. hredirected(HConnect *c, char *how, char *uri)
  7. {
  8. Hio *hout;
  9. char *s, *ss, *scheme, *host;
  10. char sayport[NETPATHLEN];
  11. int n;
  12. scheme = c->scheme? c->scheme: "http";
  13. host = c->head.host;
  14. if(strchr(uri, ':') != nil)
  15. host = "";
  16. else if(uri[0] != '/'){
  17. s = strrchr(c->req.uri, '/');
  18. if(s != nil)
  19. *s = '\0';
  20. ss = halloc(c, strlen(c->req.uri) + strlen(uri) + 2 + UTFmax);
  21. sprint(ss, "%s/%s", c->req.uri, uri);
  22. uri = ss;
  23. if(s != nil)
  24. *s = '/';
  25. }
  26. if((strcmp(scheme, "http") == 0 && atoi(c->port) == 80) ||
  27. (strcmp(scheme, "https") == 0 && atoi(c->port) == 443) ||
  28. strchr(host, ':') != nil)
  29. sayport[0] = '\0';
  30. else
  31. snprint(sayport, sizeof sayport, ":%s", c->port);
  32. n = snprint(c->xferbuf, HBufSize,
  33. "<head><title>Redirection</title></head>\r\n"
  34. "<body><h1>Redirection</h1>\r\n"
  35. "Your selection can be found <a href=\"%U\"> here</a>.<p></body>\r\n", uri);
  36. hout = &c->hout;
  37. hprint(hout, "%s %s\r\n", hversion, how);
  38. hprint(hout, "Date: %D\r\n", time(nil));
  39. hprint(hout, "Server: Plan9\r\n");
  40. hprint(hout, "Content-type: text/html\r\n");
  41. hprint(hout, "Content-Length: %d\r\n", n);
  42. if(host == nil || host[0] == 0)
  43. hprint(hout, "Location: %U\r\n", uri);
  44. else
  45. hprint(hout, "Location: %s://%U%s%U\r\n",
  46. scheme, host, sayport, uri);
  47. if(c->head.closeit)
  48. hprint(hout, "Connection: close\r\n");
  49. else if(!http11(c))
  50. hprint(hout, "Connection: Keep-Alive\r\n");
  51. hprint(hout, "\r\n");
  52. if(strcmp(c->req.meth, "HEAD") != 0)
  53. hwrite(hout, c->xferbuf, n);
  54. if(c->replog)
  55. if(host == nil || host[0] == 0)
  56. c->replog(c, "Reply: %s\nRedirect: %U\n", how, uri);
  57. else
  58. c->replog(c, "Reply: %s\nRedirect: %s://%U%s%U\n",
  59. how, scheme, host, sayport, uri);
  60. return hflush(hout);
  61. }
  62. int
  63. hmoved(HConnect *c, char *uri)
  64. {
  65. return hredirected(c, "301 Moved Permanently", uri);
  66. }