source of highlighter
plain | download
    1 /*
    2  * 2017 by kabel@blackhole.sk
    3  * gcc -O2 -o highlight highlight.c
    4  */
    5 
    6 #include <stdio.h>
    7 #include <stdlib.h>
    8 #include <string.h>
    9 #include <unistd.h>
   10 #include <sys/types.h>
   11 #include <sys/wait.h>
   12 
   13 #define EXECVE_EMPTY_ARGS ((char * const []) {NULL})
   14 #define EXECVE_ARGS(...) ((char * const []) {__VA_ARGS__, NULL})
   15 
   16 int main (int argc, char ** argv) {
   17         char *req_path, *qmark, *local_path, *ext;
   18         pid_t child;
   19 
   20         req_path = getenv("REQUEST_URI");
   21         if (req_path == NULL || strncmp(req_path, "/~kabel/", 8))
   22                 return 1;
   23 
   24         qmark = strchr(req_path, '?');
   25         if (qmark != NULL)
   26                 *qmark = '\0';
   27 
   28         local_path = malloc(22 + strlen(req_path));
   29         sprintf(local_path, "/home/kabel/public_html/%s", req_path + 8); /* get rid of "/~kabel" */
   30 
   31         ext = strrchr(local_path, '.');
   32         if (ext == NULL)
   33                 return 1;
   34         ++ext;
   35 
   36         printf("Content-type: text/html; charset=UTF-8\n\n"
   37                 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n"
   38                 "<html>\n"
   39                 "<head>\n"
   40                 "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n"
   41                 "<title>Highlighted source code of %s</title>\n"
   42                 "<link rel=\"stylesheet\" href=\"/~kabel/highlight.css\" type=\"text/css\" media=\"screen\">\n"
   43                 "</head>\n"
   44                 "<body>\n"
   45                 "<div class=\"head\">\n"
   46                 "<div class=\"right\"><a href=\"/~kabel/src/highlight.c\">source of highlighter</a></div>\n"
   47                 "<div>\n"
   48                 "<a href=\"%s?plain\">plain</a>\n"
   49                 "| <a href=\"%s?download\">download</a>\n"
   50                 "</div>\n"
   51                 "</div>\n"
   52                 "<pre class=\"hl\">\n", req_path, req_path, req_path);
   53 
   54         fflush(stdout);
   55 
   56         child = fork();
   57         if (child == 0) {
   58                 execve("/home/kabel/gentoo/usr/bin/highlight",
   59                         EXECVE_ARGS("highlight", "-t", "8", "-Iflai",
   60                                     local_path, "--force", "-S", ext),
   61                         EXECVE_EMPTY_ARGS);
   62 
   63                 return 1;
   64         } else if (child > 0) {
   65                 waitpid(child, NULL, 0);
   66         } else {
   67                 printf("highlighting failed");
   68         }
   69 
   70         printf("</pre>\n"
   71                 "</body>\n"
   72                 "</html>\n");
   73 
   74         fflush(stdout);
   75 
   76         return 0;
   77 }