xref: /plan9/sys/src/libhttpd/redirected.c (revision ec59a3ddbfceee0efe34584c2c9981a5e5ff1ec4)
1 #include <u.h>
2 #include <libc.h>
3 #include <bin.h>
4 #include <httpd.h>
5 
6 int
7 hredirected(HConnect *c, char *how, char *uri)
8 {
9 	Hio *hout;
10 	char *s, *ss, *host;
11 	int n;
12 
13 	host = c->head.host;
14 	if(strchr(uri, ':')){
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 
27 	n = snprint(c->xferbuf, HBufSize,
28 			"<head><title>Redirection</title></head>\r\n"
29 			"<body><h1>Redirection</h1>\r\n"
30 			"Your selection can be found <a href=\"%U\"> here</a>.<p></body>\r\n", uri);
31 
32 	hout = &c->hout;
33 	hprint(hout, "%s %s\r\n", hversion, how);
34 	hprint(hout, "Date: %D\r\n", time(nil));
35 	hprint(hout, "Server: Plan9\r\n");
36 	hprint(hout, "Content-type: text/html\r\n");
37 	hprint(hout, "Content-Length: %d\r\n", n);
38 	if(host == nil || host[0] == 0)
39 		hprint(hout, "Location: %U\r\n", uri);
40 	else
41 		hprint(hout, "Location: http://%U%U\r\n", host, uri);
42 	if(c->head.closeit)
43 		hprint(hout, "Connection: close\r\n");
44 	else if(!http11(c))
45 		hprint(hout, "Connection: Keep-Alive\r\n");
46 	hprint(hout, "\r\n");
47 
48 	if(strcmp(c->req.meth, "HEAD") != 0)
49 		hwrite(hout, c->xferbuf, n);
50 
51 	if(c->replog){
52 		if(host == nil || host[0] == 0)
53 			c->replog(c, "Reply: %s\nRedirect: %U\n", how, uri);
54 		else
55 			c->replog(c, "Reply: %s\nRedirect: http://%U%U\n", how, host, uri);
56 	}
57 	return hflush(hout);
58 }
59 
60 int
61 hmoved(HConnect *c, char *uri)
62 {
63 	return hredirected(c, "301 Moved Permanently", uri);
64 }
65