redirected.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include <u.h>
  10. #include <libc.h>
  11. #include <bin.h>
  12. #include <httpd.h>
  13. int
  14. hredirected(HConnect *c, char *how, char *uri)
  15. {
  16. Hio *hout;
  17. char *s, *ss, *scheme, *host;
  18. char sayport[NETPATHLEN];
  19. int n;
  20. scheme = c->scheme? c->scheme: "http";
  21. host = c->head.host;
  22. if(strchr(uri, ':') != nil)
  23. host = "";
  24. else if(uri[0] != '/'){
  25. s = strrchr(c->req.uri, '/');
  26. if(s != nil)
  27. *s = '\0';
  28. ss = halloc(c, strlen(c->req.uri) + strlen(uri) + 2 + UTFmax);
  29. sprint(ss, "%s/%s", c->req.uri, uri);
  30. uri = ss;
  31. if(s != nil)
  32. *s = '/';
  33. }
  34. if((strcmp(scheme, "http") == 0 && atoi(c->port) == 80) ||
  35. (strcmp(scheme, "https") == 0 && atoi(c->port) == 443) ||
  36. strchr(host, ':') != nil)
  37. sayport[0] = '\0';
  38. else
  39. snprint(sayport, sizeof sayport, ":%s", c->port);
  40. n = snprint(c->xferbuf, HBufSize,
  41. "<head><title>Redirection</title></head>\r\n"
  42. "<body><h1>Redirection</h1>\r\n"
  43. "Your selection can be found <a href=\"%U\"> here</a>.<p></body>\r\n", uri);
  44. hout = &c->hout;
  45. hprint(hout, "%s %s\r\n", hversion, how);
  46. hprint(hout, "Date: %D\r\n", time(nil));
  47. hprint(hout, "Server: Plan9\r\n");
  48. hprint(hout, "Content-type: text/html\r\n");
  49. hprint(hout, "Content-Length: %d\r\n", n);
  50. if(host == nil || host[0] == 0)
  51. hprint(hout, "Location: %U\r\n", uri);
  52. else
  53. hprint(hout, "Location: %s://%U%s%U\r\n",
  54. scheme, host, sayport, uri);
  55. if(c->head.closeit)
  56. hprint(hout, "Connection: close\r\n");
  57. else if(!http11(c))
  58. hprint(hout, "Connection: Keep-Alive\r\n");
  59. hprint(hout, "\r\n");
  60. if(strcmp(c->req.meth, "HEAD") != 0)
  61. hwrite(hout, c->xferbuf, n);
  62. if(c->replog) {
  63. if(host == nil || host[0] == 0)
  64. c->replog(c, "Reply: %s\nRedirect: %U\n", how, uri);
  65. else
  66. c->replog(c, "Reply: %s\nRedirect: %s://%U%s%U\n",
  67. how, scheme, host, sayport, uri);
  68. }
  69. return hflush(hout);
  70. }
  71. int
  72. hmoved(HConnect *c, char *uri)
  73. {
  74. return hredirected(c, "301 Moved Permanently", uri);
  75. }