xref: /plan9/sys/src/libhttpd/redirected.c (revision b39189fd423aed869c5cf5189bc504918cff969b)
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;
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 		ss = halloc(c, strlen(c->req.uri) + strlen(uri) + 2 + UTFmax);
23 		sprint(ss, "%s/%s", c->req.uri, uri);
24 		uri = ss;
25 		if(s != nil)
26 			*s = '/';
27 	}
28 
29 	if((strcmp(scheme, "http") == 0 && atoi(c->port) == 80) ||
30 	   (strcmp(scheme, "https") == 0 && atoi(c->port) == 443) ||
31 	    strchr(host, ':') != nil)
32 		sayport[0] = '\0';
33 	else
34 		snprint(sayport, sizeof sayport, ":%s", c->port);
35 
36 	n = snprint(c->xferbuf, HBufSize,
37 			"<head><title>Redirection</title></head>\r\n"
38 			"<body><h1>Redirection</h1>\r\n"
39 			"Your selection can be found <a href=\"%U\"> here</a>.<p></body>\r\n", uri);
40 
41 	hout = &c->hout;
42 	hprint(hout, "%s %s\r\n", hversion, how);
43 	hprint(hout, "Date: %D\r\n", time(nil));
44 	hprint(hout, "Server: Plan9\r\n");
45 	hprint(hout, "Content-type: text/html\r\n");
46 	hprint(hout, "Content-Length: %d\r\n", n);
47 	if(host == nil || host[0] == 0)
48 		hprint(hout, "Location: %U\r\n", uri);
49 	else
50 		hprint(hout, "Location: %s://%U%s%U\r\n",
51 			scheme, host, sayport, uri);
52 	if(c->head.closeit)
53 		hprint(hout, "Connection: close\r\n");
54 	else if(!http11(c))
55 		hprint(hout, "Connection: Keep-Alive\r\n");
56 	hprint(hout, "\r\n");
57 
58 	if(strcmp(c->req.meth, "HEAD") != 0)
59 		hwrite(hout, c->xferbuf, n);
60 
61 	if(c->replog)
62 		if(host == nil || host[0] == 0)
63 			c->replog(c, "Reply: %s\nRedirect: %U\n", how, uri);
64 		else
65 			c->replog(c, "Reply: %s\nRedirect: %s://%U%s%U\n",
66 				how, scheme, host, sayport, uri);
67 	return hflush(hout);
68 }
69 
70 int
hmoved(HConnect * c,char * uri)71 hmoved(HConnect *c, char *uri)
72 {
73 	return hredirected(c, "301 Moved Permanently", uri);
74 }
75