]> Pileus Git - vpaste/blob - index.cgi
fix awk for head command
[vpaste] / index.cgi
1 #!/bin/bash
2
3 # Copyright (C) 2009-2012 Andy Spencer
4 #
5 # This program is free software: you can redistribute it and/or modify it under
6 # the terms of the GNU Affero General Public License as published by the Free
7 # Software Foundation, either version 3 of the License, or (at your option) any
8 # later version.
9 #
10 # This program is distributed in the hope that it will be useful, but WITHOUT
11 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12 # FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
13 # details.
14
15 # Remove url codings from stdin
16 function get_modeline {
17         echo "$QUERY_STRING" |
18         sed -e 's/%\([0-9A-F][0-9A-F]\)/\\\\\x\1/g; s/[,&?]/ /g' |
19         xargs echo -e
20 }
21 function get_param {
22         get_modeline | awk -v "key=$1" 'BEGIN{RS=" "; FS="="}; $1 ~ key {print $2}'
23 }
24
25 # Extract an uploaded file from standard input
26 #   $1 is the name of the input to extract
27 function cut_file {
28         bnd="${CONTENT_TYPE/*boundary\=/}"
29         awk -v "want=$1" -v "bnd=$bnd" '
30                 BEGIN { RS="\r\n" }
31
32                 # reset based on boundaries
33                 $0 == "--"bnd""     { st=1; next; }
34                 $0 == "--"bnd"--"   { st=0; next; }
35                 $0 == "--"bnd"--\r" { st=0; next; }
36
37                 # search for wanted file
38                 st == 1 && $0 ~  "^Content-Disposition:.* name=\""want"\"" { st=2; next; }
39                 st == 1 && $0 == "" { st=9; next; }
40
41                 # wait for newline, then start printing
42                 st == 2 && $0 == "" { st=3; next; }
43                 st == 3             { print $0    }
44         ' | head -c $((128*1024)) # Limit size to 128K
45 }
46
47 # Print out a generic header
48 function header {
49         echo "Content-Type: $1; charset=UTF-8"
50         if [[ "$HTTP_ACCEPT_ENCODING" == *'gzip'* ]]; then
51                 echo "Content-Encoding: gzip"
52                 echo
53                 exec 1> >(gzip)
54         else
55                 echo
56         fi
57 }
58
59 # Print plain message and exit
60 function message {
61         while [ "$1" == '-h' ]; do
62                 shift; echo "$1"; shift
63         done
64         header text/plain
65         echo "$*"
66         exit
67 }
68
69 # List previous pastes
70 function do_cmd {
71         header text/plain
72         case "$1" in
73         head)
74                 awk -v 'rows=4' -v 'cols=60' '
75                         FNR==1      { gsub(/.*\//, "", FILENAME);
76                                       print FILENAME
77                                       print "-----" }
78                         FNR==1,/^$/ { next }
79                         /\S/        { i++; printf "%."cols"s\n", $0 }
80                         i>=rows     { nextfile  }
81                         ENDFILE     { i=0; print ""  }
82                 ' $(ls -t db/*)
83                 ;;
84         ls)
85                 ls -t db | column
86                 ;;
87         esac
88 }
89
90 # Format a file for viewing
91 function do_print {
92         if [ -f "./$1" ]; then
93                 input="$1"
94         elif [ -f "db/$1" ]; then
95                 input="db/$1"
96                 trim='1,/^$/d' # sed command to remove cruft
97         else
98                 message -h 'Status: 404 Not Found' \
99                         "File '$1' not found"
100         fi
101
102         # Check for raw paste
103         if [[ "$QUERY_STRING" == 'raw'* ||
104               "$REQUEST_URI"  != *'?'* &&
105               ( "$input"       != 'db/'* ||
106                 "$HTTP_ACCEPT" != *'html'* ) ]]; then
107                 header text/plain
108                 sed "$trim" "$input"
109                 exit
110         fi
111
112         # Create a temp file with the provided modeline
113         output="$(mktemp)"
114         tmp="$(mktemp)"
115         sed "\$avim: $(get_modeline)" "$input" > "$tmp"
116
117         # - I have some plugins in ~/.vim
118         # - Run ex in screen to trick it into thinking that it
119         #   has a real terminal, note that we also have to set
120         #   term=xterm-256color in vimrc
121         HOME=/home/andy \
122         screen -D -m ex -nXZ -i NONE -u vimrc \
123                 '+sil! set fde= fdt= fex= inde= inex= key= pa= pexpr=' \
124                 '+sil! set iconstring= ruf= stl= tal=' \
125                 "+sil! set titlestring=$1\ -\ vpaste.net" \
126                 '+sil! set noml'     \
127                 '+sil! $d|'$trim     \
128                 '+sil! %s/\r//g' \
129                 '+sil! TOhtml'       \
130                 "+sav! $output" \
131                 '+qall!'        \
132                 "$tmp"
133
134         header text/html
135         cat "$output"
136         rm "$tmp" "$output"
137 }
138
139
140 # Upload handler
141 function do_upload {
142         body=$(cat -)
143         spam=$(echo -n "$body" | cut_file "ignoreme")
144         text=$(echo -n "$body" | cut_file "(text|x)")
145         [ ! -z "$spam" ] && message "Spam check.."
146         [   -z "$text" ] && message "No text pasted"
147
148         # Format and save message
149         output="$(mktemp db/XXXXX)"
150         cat >"$output" <<-EOF
151                 vim: $(get_modeline)
152                 Date: $(date -R)
153                 From: $REMOTE_ADDR
154
155                 $text
156         EOF
157
158         # Redirect user
159         uri="$url$(basename "$output")"
160         message -h 'Status: 302 Found' \
161                 -h "Location: $uri"    \
162                 "$uri"
163 }
164
165 # Default index page
166 function do_help {
167         filetypes=$(
168                 ls /usr/share/vim/vim*/syntax/ /home/andy/.vim/syntax/ |
169                 sed -n '/^\(syntax\|manual\|synload\|2html\|colortest\|hitest\).vim$/d; s/.vim$//p' |
170                 sort | uniq
171         )
172         uploads=$(ls -t db | head -n 5)
173         filetype=$(get_param '^(ft|filet(y(pe?)?)?)$')
174         vpaste='<a href="vpaste?ft=sh">vpaste</a>'
175
176         header text/html
177         cat <<-EOF
178         <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
179           "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
180         <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
181                 <head>
182                         <title>vpaste.net - Vim based pastebin</title>
183                         <meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
184                         <meta name="description" content="vpaste: Vim based pastebin" />
185                         <meta name="keywords" content="vpaste,paste,pastebin,vim" />
186                         <meta name="google-site-verification" content="OvHF73zD7osJ1VSq9rJxnMFlja36944ud6CiP_iXQnI" />
187                         <style type="text/css">
188                                 *          { margin: 0;
189                                              padding: 0; }
190                                 body       { margin: 4em 8em 4em 8em;
191                                              font-family: sans-serif; }
192                                 /* Items */
193                                 textarea   { width: 100%;
194                                              margin-bottom: 0.5em; }
195                                 .buttons   { float: left; }
196                                 .links     { float: right; }
197                                 .links *   { text-decoration: none;
198                                              margin-left: 0.5em; }
199                                 .box       { display: none;
200                                              clear: both;
201                                              margin-top: 2.7em;
202                                              border-top: solid 1px #888; }
203                                 /* box contents */
204                                 h1         { margin-top: 1.0em;
205                                              font-size: larger; }
206                                 ul,dd,dl,p { margin: 0 0 0 2em; }
207                                 dt         { font-weight: bold;
208                                              padding: 0.5em 0 0 0; }
209                                 span       { font-family: monospace; }
210                                 .cmds dd   { font-family: monospace; }
211                         </style>
212                         <script type="text/javascript">
213                                 //<![CDATA[
214                                 function show(id) {
215                                         var boxes = document.getElementsByClassName('box')
216                                         for (var i = 0; i < boxes.length; i++) {
217                                                 var box = boxes[i]
218                                                 if (box.id == id && box.style.display != 'block')
219                                                         box.style.display = 'block'
220                                                 else
221                                                         box.style.display = "none"
222                                         }
223                                 }
224                                 function autoshow() {
225                                         var id  = document.location.toString().replace(/.*#/, '')
226                                         var box = document.getElementById(id)
227                                         if (box) box.style.display = "block"
228                                 }
229                                 //]]>
230                         </script>
231                 </head>
232
233                 <body onload="autoshow()">
234                         <form id="form" method="post" action="" enctype="multipart/form-data">
235                                 <div>
236                                         <input style="display:none" type="text" name="ignoreme" value="" />
237                                         <textarea name="text" cols="80" rows="25"></textarea>
238                                 </div>
239                                 <div class="buttons">
240                                         <select onchange="document.getElementById('form').action =
241                                                           document.location + '?ft=' + this.value;">
242                                                 <option value="" disabled="disabled">Filetype</option>
243                                                 <option value="">None</option>
244                                                 $(for ft in $filetypes; do
245                                                         echo "<option$(
246                                                         [ "$ft" = "$filetype" ] &&
247                                                                 echo ' selected="selected"'
248                                                         )>$ft</option>"
249                                                 done)
250                                         </select>
251                                         <input type="submit" value="Paste" />
252                                 </div>
253                                 <div class="links">
254                                         <a href="">vpaste</a> <span>-</span>
255                                         <a href="#usage"   onclick="show('usage'  )">Usage</a>
256                                         <a href="#devel"   onclick="show('devel'  )">Development</a>
257                                         <a href="#uploads" onclick="show('uploads')">Uploads</a>
258                                 </div>
259                         </form>
260
261                         <div class="box" id="usage">
262                                 <h1>Pasting</h1>
263                                 <dl class="cmds">
264                                         <dt>From a shell</dt>
265                                         <dd> $vpaste file [option=value,..]</dd>
266                                         <dd> &lt;command&gt; | $vpaste [option=value,..]</dd>
267
268                                         <dt>From Vim</dt>
269                                         <dd> :map vp :exec "w !vpaste ft=".&amp;ft&lt;CR&gt;</dd>
270                                         <dd> :vmap vp &lt;ESC&gt;:exec "'&lt;,'&gt;w !vpaste ft=".&amp;ft&lt;CR&gt;</dd>
271
272                                         <dt>With curl</dt>
273                                         <dd> &lt;command&gt; | curl -F 'text=&lt;-' $url[?option=value,..]</dd>
274                                 </dl>
275
276                                 <h1>Options</h1>
277                                 <p>Add <b>?option[=value],..</b> to make your text a rainbow.</p>
278                                 <p>Options specified when uploading are saved as defaults.</p>
279
280                                 <dl>
281                                         <dt>bg, background={light|dark}</dt>
282                                         <dd>Background color to use for the page</dd>
283                                         <dt>et, expandtab</dt>
284                                         <dd>Expand tabs to spaces</dd>
285                                         <dt>fdm, foldmethod=(syntax|indent)</dt>
286                                         <dd>Turn on dynamic code folding</dd>
287                                         <dt>ft, filetype={filetype}</dt>
288                                         <dd>A filetype to use for highlighting, see above menu for supported types</dd>
289                                         <dt>nu, number</dt>
290                                         <dd>Add line numbers</dd>
291                                         <dt>ts, tabstop=[N]</dt>
292                                         <dd>Number of spaces to use for tabs when <b>et</b> is set</dd>
293                                         <dt>...</dt>
294                                         <dd>See :help modeline for more information</dd>
295                                 </dl>
296                         </div>
297
298                         <div class="box" id="devel">
299                                 <h1>License</h1>
300                                 <p>Copyright © 2009-2012
301                                    Andy Spencer &lt;andy753421@gmail.com&gt;</p>
302                                 <p>See individual files for licenses</p>
303
304                                 <h1>Source code</h1>
305                                 <ul>
306                                         <li><a href="vpaste?ft=sh">vpaste</a></li>
307                                         <li><a href="index.cgi?ft=sh">index.cgi</a>
308                                             <a href="vimrc?ft=vim">vimrc</a>
309                                             <a href="htaccess?ft=apache">htaccess</a>
310                                             <a href="robots.txt?ft=robots">robots.txt</a>
311                                             <a href="sitemap.xml?ft=xml">sitemap.xml</a></li>
312                                         <li><a href="2html.patch?ft=diff">2html.patch</a></li>
313                                         <li><a href="https://lug.rose-hulman.edu/svn/misc/trunk/htdocs/vpaste/">Subversion</a></li>
314                                 </ul>
315
316                                 <h1>Bugs</h1>
317                                 <ul>
318                                         <li>Using strange filetypes (ft=2html) may result in strange output.</li>
319                                         <li><a href="mailto:andy753421@gmail.com?subject=vpaste bug">Other?</a></li>
320                                 </ul>
321                         </div>
322
323                         <div class="box" id="uploads">
324                                 <h1>Recent Uploads</h1>
325                                 <ul>$(for upload in ${uploads[@]}; do
326                                     echo -n "<li>"
327                                     echo -n "<span>$upload</span> "
328                                     echo -n "<a href='$upload?raw'>text</a> "
329                                     echo -n "<a href='$upload'>rainbow</a>"
330                                     echo "</li>"
331                                 done)
332                                 </ul>
333                                 <p><a href="ls">list all</a></p>
334                                 <p><a href="head">sample all</a></p>
335                         </div>
336                 </body>
337         </html>
338         EOF
339 }
340
341 # Main
342 PATH=/bin:/usr/bin
343 url="http://$HTTP_HOST${REQUEST_URI/\?*}"
344 pathinfo="${REQUEST_URI/*\/}"
345 pathinfo="${pathinfo/\?*}"
346
347 if [ "$pathinfo" = ls ]; then
348         do_cmd ls
349 elif [ "$pathinfo" = head ]; then
350         do_cmd head
351 elif [ "$pathinfo" ]; then
352         do_print "$pathinfo"
353 elif [ "$CONTENT_TYPE" ]; then
354         do_upload
355 else
356         do_help
357 fi