xref: /plan9/acme/mail/src/html.c (revision 95fdf19ce7a8b273bf38b8060fb3ebbec5fd23fc)
1 #include <u.h>
2 #include <libc.h>
3 #include <bio.h>
4 #include <thread.h>
5 #include <ctype.h>
6 #include <plumb.h>
7 #include "dat.h"
8 
9 
10 char*
formathtml(char * body,int * np)11 formathtml(char *body, int *np)
12 {
13 	int i, j, p[2], q[2];
14 	Exec *e;
15 	char buf[1024];
16 	Channel *sync;
17 
18 	e = emalloc(sizeof(struct Exec));
19 	if(pipe(p) < 0 || pipe(q) < 0)
20 		error("can't create pipe: %r");
21 
22 	e->p[0] = p[0];
23 	e->p[1] = p[1];
24 	e->q[0] = q[0];
25 	e->q[1] = q[1];
26 	e->argv = emalloc(3*sizeof(char*));
27 	e->argv[0] = estrdup("htmlfmt");
28 	e->argv[1] = estrdup("-cutf-8");
29 	e->argv[2] = nil;
30 	e->prog = "/bin/htmlfmt";
31 	sync = chancreate(sizeof(int), 0);
32 	e->sync = sync;
33 	proccreate(execproc, e, EXECSTACK);
34 	recvul(sync);
35 	close(p[0]);
36 	close(q[1]);
37 
38 	if((i=write(p[1], body, *np)) != *np){
39 		fprint(2, "Mail: warning: htmlfmt failed: wrote %d of %d: %r\n", i, *np);
40 		close(p[1]);
41 		close(q[0]);
42 		return body;
43 	}
44 	close(p[1]);
45 
46 	free(body);
47 	body = nil;
48 	i = 0;
49 	for(;;){
50 		j = read(q[0], buf, sizeof buf);
51 		if(j <= 0)
52 			break;
53 		body = realloc(body, i+j+1);
54 		if(body == nil)
55 			error("realloc failed: %r");
56 		memmove(body+i, buf, j);
57 		i += j;
58 		body[i] = '\0';
59 	}
60 	close(q[0]);
61 
62 	*np = i;
63 	return body;
64 }
65 
66 char*
readbody(char * type,char * dir,int * np)67 readbody(char *type, char *dir, int *np)
68 {
69 	char *body;
70 
71 	body = readfile(dir, "body", np);
72 	if(body != nil && strcmp(type, "text/html") == 0)
73 		return formathtml(body, np);
74 	return body;
75 }
76