chiark / gitweb /
Store Unix timestamps in the database, rather than SQL ones.
[odin-cgi] / lib / Odin.pm
CommitLineData
be24e9af
MW
1### -*-perl-*-
2
3package Odin;
4
5use DBI;
6use Digest::SHA qw(sha256_hex);
7use MIME::Base64;
8
9###--------------------------------------------------------------------------
10### Early utilities.
11
12sub merge_hash (\%%) {
13 my ($hashref, %defaults) = @_;
14 for my $k (keys %defaults)
15 { $hashref->{$k} = $defaults{$k} unless exists $hashref->{$k}; }
16}
17
18###--------------------------------------------------------------------------
19### Configuration.
20
21our $DSN = "dbi:Pg(pg_enable_utf8=>1):host=db";
22our $RETRY = 10;
23our @BACKOFF = (0.1, 10, 1.5, 0.5, 2.0);
24
25our $BASEURL = "http://odin.gg/";
26our $STATIC = "http://odin.gg/";
27
28our $SHORTURL_PATH = "u";
29our $PASTEBIN_PATH = "p";
30
31our $URLMAXLEN = 1024;
32our @URLPAT = (
33 qr{^https?://}
34);
35
36our %COOKIE_DEFAULTS = (
37 -httponly => undef,
38 -max_age => 3600
39);
40
41require "config.pl";
42
43our ($SCHEME, $DOMAIN, $BASEPATH) = $BASEURL =~ m!^([^:]+)://([^/]+)(/.*)$!;
44merge_hash %COOKIE_DEFAULTS, -domain => $DOMAIN, -path => $BASEPATH;
45merge_hash %COOKIE_DEFAULTS, -secure => undef if $SCHEME eq "https";
46
47our $SHORTURL = "$BASEURL$SHORTURL_PATH";
48our $PASTEBIN = "$BASEURL$PASTEBIN_PATH";
49
50###--------------------------------------------------------------------------
51### Miscellaneous utilities.
52
503f7910
MW
53our $NOW;
54sub update_now () { $NOW = time; }
55update_now;
56
be24e9af
MW
57(our $PROG = $0) =~ s:^.*/::;
58
59sub fail_cmdline ($$%) {
60 my ($msg, $label, %args) = @_;
61 print STDERR "$PROG: $msg\n";
62 exit 1;
63}
64
65our $FAILPROC = \&fail_cmdline;
66
67sub fail ($;$%) {
68 my ($msg, $label, %args) = @_;
69 $FAILPROC->($msg, $label, %args);
70}
71
72sub set_mason_failproc ($) {
73 my ($m) = @_;
74 $FAILPROC = sub {
75 my ($msg, $label, %args) = @_;
76 $m->clear_buffer;
77 $m->comp($label, %args);
78 $m->abort;
79 };
80}
81
82sub nice_name ($) {
83 my ($s) = @_;
84 $s =~ s/\W+//g;
85 return lc $s;
86}
87
88###--------------------------------------------------------------------------
89### Database utilities.
90
91sub open_db (@) {
92 my @attr = @_;
93 my $db = DBI->connect_cached($DSN, undef, undef, {
94 PrintError => 0,
95 RaiseError => 1,
96 @attr
97 });
98
99 my $drv = $db->{Driver}{Name};
100 if ($drv eq "Pg") {
101 $db->{private_odin_retry_p} = sub { $db->state =~ /^40[0P]01$/ };
be24e9af
MW
102 } elsif ($drv eq "SQLite") {
103 $db->{private_odin_retry_p} = sub { $db->err == 5 };
be24e9af 104 } else {
3300e9a2 105 $db->{private_odin_retry_p} = sub { 0 };
be24e9af
MW
106 }
107
108 return $db;
109}
110
111sub xact (&$) {
112 my ($body, $db) = @_;
113 my @rv;
114 my $exc;
115
116 my ($sleep, $maxsleep, $mult, $minvar, $maxvar) = @BACKOFF;
117 for (my $i = 0; $i < $RETRY; $i++) {
118 $db->begin_work;
119 eval { @rv = $body->(); $db->commit; };
120 $exc = $@;
121 return @rv unless $exc;
122 my $retryp = $db->{private_odin_retry_p}();
123 eval { $db->rollback; };
124 die $exc unless $retryp;
125 my $t = $sleep * ($minvar + rand($maxvar - $minvar));
126 $sleep *= $mult; $sleep = $max if $sleep > $max;
127 select undef, undef, undef, $t;
128 }
129 die $exc;
130}
131
be24e9af
MW
132
133###--------------------------------------------------------------------------
134### Sequence numbers and tagging.
135
136sub next_seq ($$) {
137 my ($db, $table) = @_;
138 my ($seq) = $db->selectrow_array("SELECT seq FROM $table");
139 die "no sequence number in $table" unless defined $seq;
140 $db->do("UPDATE $table SET seq = ?", undef, $seq + 1);
141 return $seq;
142}
143
144my $ALPHABET =
145 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
146my $NALPHA = length $ALPHABET;
147
148sub encode_tag ($) {
149 my ($seq) = @_;
150 my $tag = "";
151 while ($seq) {
152 $tag .= substr($ALPHABET, $seq % $NALPHA, 1);
153 $seq = int $seq/$NALPHA;
154 }
155 return $tag;
156}
157
158###--------------------------------------------------------------------------
159### HTTP utilities.
160
161our %COOKIE;
162sub fetch_cookies ($) {
163 my ($r) = @_;
164
165 %COOKIE = ();
166 my $cookies = $r->header_in("Cookie");
167 if (defined $cookies) {
168 for my $kv (split /;/, $cookies) {
169 my ($k, $v) = split /=/, $kv, 2;
170 $k =~ s/^\s*(|\S|\S.*\S)\s*$/$1/;
171 $v =~ s/^\s*(|\S|\S.*\S)\s*$/$1/;
172 $v =~ s/\+/ /g;
173 $v =~ s/\%([0-9a-f][0-9a-f])/chr hex $1/eg;
174 $COOKIE{$k} = $v;
175 }
176 }
177}
178
179sub bake_cookie ($$%) {
180 my ($r, $cookie, %attr) = @_;
181 merge_hash %attr, %COOKIE_DEFAULTS;
182 my @attr = map {
183 my $v = $attr{$_}; tr/_-/-/d;
184 defined $v ? "$_=$v" : $_
185 } keys %attr;
186 $r->headers_out->add("Set-Cookie", join "; ", $cookie, @attr);
187}
188
189sub path_info ($) {
190 my ($r) = @_;
191 return $ENV{PATH_INFO} // $r->path_info;
192}
193
194###--------------------------------------------------------------------------
195### HTML utilities.
196
197sub escapify ($$;$) {
198 my ($m, $s, $mode) = @_;
199 return $m->interp->apply_escapes($s, $mode // "h");
200}
201
202###--------------------------------------------------------------------------
203### Access control.
204
205our ($WHO, $WHOSURE);
206our ($WHOMATCH, $WHOCMP, $WHOPAT);
207
208sub cgi_who ($) {
209 my ($r) = @_;
210 my $raddr = $ENV{REMOTE_ADDR} // $r->connection->remote_ip;
211 $WHO = ":NET-$raddr"; $WHOSURE = 0;
212 $WHOMATCH = "LIKE"; $WHOCMP = ":NET-\%"; $WHOPAT = qr/^:NET-/;
213}
214
215sub cmdline_who () {
216 $WHO = $ENV{USERV_USER}
217 // ($< == $> && $ENV{USER})
218 // @{[getpwuid $<]}[0]
219 // die "nameless user";
220 $WHOMATCH = "="; $WHOCMP = $WHO; $WHOPAT = qr/^\Q$WHO\E$/;
221 $WHOSURE = 1;
222}
223
224sub new_editkey () {
225 open my $fh, "/dev/urandom" or die "open urandom: $!";
226 sysread $fh, my $rand, 16;
227 (my $edit = encode_base64 $rand) =~ tr:+/=\n:.-:d;
228 return $edit, sha256_hex $edit;
229}
230
231###--------------------------------------------------------------------------
232### URL shortening.
233
234sub get_shorturl ($) {
235 my ($tag) = @_;
236
237 my $db = open_db;
238 my ($url) = $db->selectrow_array
239 ("SELECT url FROM odin_shorturl WHERE tag = ?", undef, $tag);
240 fail "tag `$tag' not found", ".notfound", tag => $tag unless defined $url;
241 return $url;
242}
243
244sub valid_url_p ($) {
245 my ($url) = @_;
246 return
247 length $url < $URLMAXLEN &&
248 scalar grep { $url =~ /$_/ } @URLPAT;
249}
250
251sub new_shorturl ($) {
252 my ($url) = @_;
253
254 valid_url_p $url or fail "invalid url", ".badurl", u => $url;
255
256 my $db = open_db;
257 my $tag;
258 xact {
259 ($tag) = $db->selectrow_array
260 ("SELECT tag FROM odin_shorturl WHERE owner $WHOMATCH ? AND url = ?",
261 undef, $WHOCMP, $url);
262 unless (defined $tag) {
263 $tag = encode_tag(next_seq($db, "odin_shorturl_seq"));
3300e9a2
MW
264 $db->do("INSERT INTO odin_shorturl (tag, stamp, owner, url)
265 VALUES (?, ?, ?, ?)", undef,
266 $tag, $NOW, $WHO, $url);
be24e9af
MW
267 }
268 } $db;
269 return $tag;
270}
271
272sub check_shorturl_owner ($$) {
273 my ($db, $tag) = @_;
274
275 my ($owner) = $db->selectrow_array
276 ("SELECT owner FROM odin_shorturl WHERE tag = ?", undef, $tag);
277 fail "tag `$tag' not found", ".notfound", tag => $tag
278 unless defined $owner;
279 fail "not owner of `$tag'", ".notowner", tag => $tag
280 unless $owner =~ /$WHOPAT/;
281}
282
283sub update_shorturl ($$) {
284 my ($tag, $url) = @_;
285
286 my $db = open_db;
287 xact {
288 check_shorturl_owner $db, $tag;
289 $db->do("UPDATE odin_shorturl SET url = ? WHERE tag = ?",
290 undef, $url, $tag);
291 } $db;
292}
293
294sub delete_shorturl (@) {
295 my (@tags) = @_;
296
297 my $db = open_db;
298 xact {
299 for my $tag (@tags) {
300 check_shorturl_owner $db, $tag;
301 $db->do("DELETE FROM odin_shorturl WHERE tag = ?", undef, $tag);
302 }
303 } $db;
304}
305
306###--------------------------------------------------------------------------
307### Paste bin.
308
309our %PASTEBIN_DEFAULTS = (
310 title => "(untitled)",
97a33b9c 311 lang => "txt",
be24e9af
MW
312 content => ""
313);
314our @PASTEBIN_PROPS = keys %PASTEBIN_DEFAULTS;
315our $PASTEBIN_PROPCOLS = join ", ", @PASTEBIN_PROPS;
316our $PASTEBIN_PROPPLACES = join ", ", map "?", @PASTEBIN_PROPS;
317
318sub new_pastebin (\%) {
319 my ($new) = @_;
320
321 my $db = open_db;
322 my ($editkey, $hash) = new_editkey;
323 my $tag;
324
325 merge_hash %$new, %PASTEBIN_DEFAULTS;
326 xact {
327 $tag = encode_tag next_seq $db, "odin_pastebin_seq";
328 $db->do("INSERT INTO odin_pastebin
3300e9a2
MW
329 (tag, stamp, edithash, owner, $PASTEBIN_PROPCOLS)
330 VALUES (?, ?, ?, ?, $PASTEBIN_PROPPLACES)", undef,
331 $tag, $NOW, $hash, $WHO, @{$new}{@PASTEBIN_PROPS});
be24e9af
MW
332 } $db;
333 return $tag, $editkey;
334}
335
336sub get_pastebin ($$\%) {
337 my ($db, $tag, $props) = @_;
338
339 (my $owner, my $hash, @{$props}{@PASTEBIN_PROPS}) =
340 $db->selectrow_array("SELECT owner, edithash, $PASTEBIN_PROPCOLS
341 FROM odin_pastebin WHERE tag = ?",
342 undef, $tag);
343 fail "tag `$tag' not found", ".notfound", tag => $tag
344 unless defined $owner;
345 return $owner, $hash;
346}
347
348sub get_pastebin_check_owner ($$\%) {
349 my ($db, $tag, $props) = @_;
350
351 my ($owner, $hash) = get_pastebin $db, $tag, %$props;
352 fail "not owner of `$tag'", ".notowner", tag => $tag
353 unless $WHOSURE && $WHO eq $owner;
354}
355
356sub get_pastebin_check_editkey_or_owner ($$$\%) {
357 my ($db, $tag, $editkey, $props) = @_;
358
359 if (!defined $editkey) { get_pastebin_check_owner $db, $tag, %$props; }
360 else {
361 my ($owner, $hash) = get_pastebin $db, $tag, %$props;
362 fail "incorrect edit key for `$tag'", ".badhash", tag => $tag
363 unless $hash eq sha256_hex $editkey;
364 }
365}
366
367sub rekey_pastebin ($) {
368 my ($tag) = @_;
369
370 my $db = open_db;
371 my $editkey;
372 xact {
373 get_pastebin_check_owner $db, $tag, my %hunoz;
374 ($editkey, my $hash) = new_editkey;
375 $db->do("UPDATE odin_pastebin SET edithash = ? WHERE tag = ?",
376 undef, $hash, $tag);
377 } $db;
378 return $editkey;
379}
380
381sub claim_pastebin ($$) {
382 my ($tag, $editkey) = @_;
383
384 my $db = open_db;
385 $WHOSURE or fail "you can't claim pastes", ".notsure";
386 xact {
387 get_pastebin_check_editkey_or_owner $db, $tag, $editkey, my %hunoz;
388 $db->do("UPDATE odin_pastebin SET owner = ? WHERE tag = ?",
389 undef, $WHO, $tag);
390 } $db;
391}
392
393sub update_pastebin ($$\%) {
394 my ($tag, $editkey, $new) = @_;
395
396 my $db = open_db;
397 my $editp = 0;
398 xact {
399 get_pastebin_check_editkey_or_owner $db, $tag, $editkey, my %old;
400 for my $p (@PASTEBIN_PROPS) {
401 if (!defined $new->{$p}) { $new->{$p} = $old{$p}; }
402 else {
403 $db->do("UPDATE odin_pastebin SET $p = ? WHERE tag = ?",
404 undef, $new->{$p}, $tag)
405 unless $new->{$p} eq $old{$p};
406 $editp = 1;
407 }
408 }
409 } $db;
410 return $editp;
411}
412
413sub delete_pastebin (@) {
414 my @a = @_;
415 my $db = open_db;
416 xact {
417 while (@a) {
418 (my $tag, my $editkey, @a) = @a;
419 get_pastebin_check_editkey_or_owner $db, $tag, $editkey, my %hunoz;
420 $db->do("DELETE FROM odin_pastebin WHERE tag = ?", undef, $tag);
421 }
422 } $db;
423}
424
425sub tidy_pastebin_content ($) {
426 my ($content) = @_;
427 return undef unless defined $content;
428 $content =~ tr/\r//d;
429 $content =~ s/([^\n])\z/$1\n/;
430 return $content;
431}
432
f0bcb39a
MW
433###--------------------------------------------------------------------------
434### Simple option parser.
435
436package Odin::OptParse;
437
438sub new {
439 my ($cls, @args) = @_;
440 return bless {
441 cur => "",
442 args => \@args,
443 opt => undef,
444 ok => 1
445 }, $cls;
446}
447
448sub get {
449 my ($me) = @_;
450 if (!length $me->{cur}) {
451 my $args = $me->{args};
452 if (!@$args) { return undef; }
453 elsif ($args->[0] =~ /^[^-]|^-$/) { return undef; }
454 elsif ($args->[0] eq "--") { shift @$args; return undef; }
455 $me->{cur} = substr shift @$args, 1;
456 }
457 my $o = $me->{opt} = substr $me->{cur}, 0, 1;
458 $me->{cur} = substr $me->{cur}, 1;
459 return $o;
460}
461
462sub arg {
463 my ($me) = @_;
464 my $a;
465 if (length $me->{cur}) { $a = $me->{cur}; $me->{cur} = ""; }
466 elsif (@{$me->{args}}) { $a = shift @{$me->{args}}; }
467 else { $a = undef; $me->err("option `-$me->{opt}' requires an argument"); }
468 return $a;
469}
470
471sub rest { return @{$_[0]->{args}}; }
472sub ok { return $_[0]->{ok}; }
473sub bad { $_[0]->{ok} = 0; }
474sub err { $_[0]->bad; print STDERR "$PROG: $_[1]\n"; }
475sub unk { $_[0]->err("unknown option `-$_[0]->{opt}'"); }
476
be24e9af
MW
477###----- That's all, folks --------------------------------------------------
478
4791;