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