added writesize
[tridge/junkcode.git] / tserver / tserver.c
1 #include "includes.h"
2
3 static struct cgi_state *cgi;
4
5 /* this is a helper function for file upload. The scripts can call 
6   @save_file(cgi_variablename, filename) to save the contents of 
7   an uploaded file to disk
8 */
9 static void save_file(struct template_state *tmpl, 
10                       const char *name, const char *value,
11                       int argc, char **argv)
12 {
13         char *var_name, *file_name;
14         int fd;
15         const char *content;
16         unsigned size, ret;
17
18         if (argc != 2) {
19                 printf("Invalid arguments to function %s (%d)\n", name, argc);
20                 return;
21         }
22         var_name = argv[0];
23         file_name = argv[1];
24
25         content = cgi->get_content(cgi, var_name, &size);
26         if (!content) {
27                 printf("No content for variable %s?\n", var_name);
28                 return;
29         }
30         fd = open(file_name, O_CREAT | O_TRUNC | O_WRONLY, 0644);
31         if (fd == -1) {
32                 printf("Failed to open %s (%s)\n", file_name, strerror(errno));
33                 return;
34         }
35         ret = write(fd, content, size);
36         if (ret != size) {
37                 printf("out of space writing %s (wrote %u)\n", file_name, ret);
38         }
39         close(fd);
40 }
41
42 /* the main webserver process, called with stdin and stdout setup
43  */
44 static void run_webserver(void)
45 {
46         struct stat st;
47
48         if (chdir("html") != 0) {
49                 fprintf(stderr,"Can't find html directory?\n");
50                 exit(1);
51         }
52
53         cgi = cgi_init();
54         cgi->setup(cgi);
55         cgi->load_variables(cgi);
56         cgi->tmpl->put(cgi->tmpl, "save_file", "", save_file);
57
58         /* handle a direct file download */
59         if (!strstr(cgi->pathinfo, "..") && *cgi->pathinfo != '/' &&
60             stat(cgi->pathinfo, &st) == 0 && S_ISREG(st.st_mode)) {
61                 cgi->download(cgi, cgi->pathinfo);
62                 cgi->destroy(cgi);
63                 return;
64         }
65
66         cgi->download(cgi, "index.html");
67         cgi->destroy(cgi);
68 }
69
70
71 /* main program, just start listening and answering queries */
72 int main(int argc, char *argv[])
73 {
74         int port = TSERVER_PORT;
75         extern char *optarg;
76         int opt;
77
78         while ((opt=getopt(argc, argv, "p:")) != -1) {
79                 switch (opt) {
80                 case 'p':
81                         port = atoi(optarg);
82                         break;
83                 }
84         }       
85
86         tcp_listener(port, run_webserver);
87         return 0;
88 }
89