6 use Digest::SHA qw(sha256_hex);
9 ###--------------------------------------------------------------------------
12 sub merge_hash (\%%) {
13 my ($hashref, %defaults) = @_;
14 for my $k (keys %defaults)
15 { $hashref->{$k} = $defaults{$k} unless exists $hashref->{$k}; }
18 ###--------------------------------------------------------------------------
21 our $DSN = "dbi:Pg(pg_enable_utf8=>1):host=db";
23 our @BACKOFF = (0.1, 10, 1.5, 0.5, 2.0);
25 our $BASEURL = "http://odin.gg/";
26 our $STATIC = "http://odin.gg/";
28 our $SHORTURL_PATH = "u";
29 our $PASTEBIN_PATH = "p";
31 our $URLMAXLEN = 1024;
36 our %COOKIE_DEFAULTS = (
43 our ($SCHEME, $DOMAIN, $BASEPATH) = $BASEURL =~ m!^([^:]+)://([^/]+)(/.*)$!;
44 merge_hash %COOKIE_DEFAULTS, -domain => $DOMAIN, -path => $BASEPATH;
45 merge_hash %COOKIE_DEFAULTS, -secure => undef if $SCHEME eq "https";
47 our $SHORTURL = "$BASEURL$SHORTURL_PATH";
48 our $PASTEBIN = "$BASEURL$PASTEBIN_PATH";
50 ###--------------------------------------------------------------------------
51 ### Miscellaneous utilities.
54 sub update_now () { $NOW = time; }
57 (our $PROG = $0) =~ s:^.*/::;
59 sub fail_cmdline ($$%) {
60 my ($msg, $label, %args) = @_;
61 print STDERR "$PROG: $msg\n";
65 our $FAILPROC = \&fail_cmdline;
68 my ($msg, $label, %args) = @_;
69 $FAILPROC->($msg, $label, %args);
72 sub set_mason_failproc ($) {
75 my ($msg, $label, %args) = @_;
77 $m->comp($label, %args);
88 ###--------------------------------------------------------------------------
89 ### Database utilities.
93 my $db = DBI->connect_cached($DSN, undef, undef, {
99 my $drv = $db->{Driver}{Name};
101 $db->{private_odin_retry_p} = sub { $db->state =~ /^40[0P]01$/ };
102 $db->{private_odin_unixstamp} = sub { "extract(epoch from $_[0])" };
103 } elsif ($drv eq "SQLite") {
104 $db->{private_odin_retry_p} = sub { $db->err == 5 };
105 $db->{private_odin_unixstamp} = sub { "strftime('%s', $_[0])" };
107 fail "unsupported database driver `$drv' (patches welcome)", undef;
114 my ($body, $db) = @_;
118 my ($sleep, $maxsleep, $mult, $minvar, $maxvar) = @BACKOFF;
119 for (my $i = 0; $i < $RETRY; $i++) {
121 eval { @rv = $body->(); $db->commit; };
123 return @rv unless $exc;
124 my $retryp = $db->{private_odin_retry_p}();
125 eval { $db->rollback; };
126 die $exc unless $retryp;
127 my $t = $sleep * ($minvar + rand($maxvar - $minvar));
128 $sleep *= $mult; $sleep = $max if $sleep > $max;
129 select undef, undef, undef, $t;
134 sub sql_timestamp ($$) {
136 return $db->{private_odin_unixstamp}->($col);
139 ###--------------------------------------------------------------------------
140 ### Sequence numbers and tagging.
143 my ($db, $table) = @_;
144 my ($seq) = $db->selectrow_array("SELECT seq FROM $table");
145 die "no sequence number in $table" unless defined $seq;
146 $db->do("UPDATE $table SET seq = ?", undef, $seq + 1);
151 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
152 my $NALPHA = length $ALPHABET;
158 $tag .= substr($ALPHABET, $seq % $NALPHA, 1);
159 $seq = int $seq/$NALPHA;
164 ###--------------------------------------------------------------------------
168 sub fetch_cookies ($) {
172 my $cookies = $r->header_in("Cookie");
173 if (defined $cookies) {
174 for my $kv (split /;/, $cookies) {
175 my ($k, $v) = split /=/, $kv, 2;
176 $k =~ s/^\s*(|\S|\S.*\S)\s*$/$1/;
177 $v =~ s/^\s*(|\S|\S.*\S)\s*$/$1/;
179 $v =~ s/\%([0-9a-f][0-9a-f])/chr hex $1/eg;
185 sub bake_cookie ($$%) {
186 my ($r, $cookie, %attr) = @_;
187 merge_hash %attr, %COOKIE_DEFAULTS;
189 my $v = $attr{$_}; tr/_-/-/d;
190 defined $v ? "$_=$v" : $_
192 $r->headers_out->add("Set-Cookie", join "; ", $cookie, @attr);
197 return $ENV{PATH_INFO} // $r->path_info;
200 ###--------------------------------------------------------------------------
203 sub escapify ($$;$) {
204 my ($m, $s, $mode) = @_;
205 return $m->interp->apply_escapes($s, $mode // "h");
208 ###--------------------------------------------------------------------------
211 our ($WHO, $WHOSURE);
212 our ($WHOMATCH, $WHOCMP, $WHOPAT);
216 my $raddr = $ENV{REMOTE_ADDR} // $r->connection->remote_ip;
217 $WHO = ":NET-$raddr"; $WHOSURE = 0;
218 $WHOMATCH = "LIKE"; $WHOCMP = ":NET-\%"; $WHOPAT = qr/^:NET-/;
222 $WHO = $ENV{USERV_USER}
223 // ($< == $> && $ENV{USER})
224 // @{[getpwuid $<]}[0]
225 // die "nameless user";
226 $WHOMATCH = "="; $WHOCMP = $WHO; $WHOPAT = qr/^\Q$WHO\E$/;
231 open my $fh, "/dev/urandom" or die "open urandom: $!";
232 sysread $fh, my $rand, 16;
233 (my $edit = encode_base64 $rand) =~ tr:+/=\n:.-:d;
234 return $edit, sha256_hex $edit;
237 ###--------------------------------------------------------------------------
240 sub get_shorturl ($) {
244 my ($url) = $db->selectrow_array
245 ("SELECT url FROM odin_shorturl WHERE tag = ?", undef, $tag);
246 fail "tag `$tag' not found", ".notfound", tag => $tag unless defined $url;
250 sub valid_url_p ($) {
253 length $url < $URLMAXLEN &&
254 scalar grep { $url =~ /$_/ } @URLPAT;
257 sub new_shorturl ($) {
260 valid_url_p $url or fail "invalid url", ".badurl", u => $url;
265 ($tag) = $db->selectrow_array
266 ("SELECT tag FROM odin_shorturl WHERE owner $WHOMATCH ? AND url = ?",
267 undef, $WHOCMP, $url);
268 unless (defined $tag) {
269 $tag = encode_tag(next_seq($db, "odin_shorturl_seq"));
270 $db->do("INSERT INTO odin_shorturl (tag, owner, url) VALUES (?, ?, ?)",
271 undef, $tag, $WHO, $url);
277 sub check_shorturl_owner ($$) {
280 my ($owner) = $db->selectrow_array
281 ("SELECT owner FROM odin_shorturl WHERE tag = ?", undef, $tag);
282 fail "tag `$tag' not found", ".notfound", tag => $tag
283 unless defined $owner;
284 fail "not owner of `$tag'", ".notowner", tag => $tag
285 unless $owner =~ /$WHOPAT/;
288 sub update_shorturl ($$) {
289 my ($tag, $url) = @_;
293 check_shorturl_owner $db, $tag;
294 $db->do("UPDATE odin_shorturl SET url = ? WHERE tag = ?",
299 sub delete_shorturl (@) {
304 for my $tag (@tags) {
305 check_shorturl_owner $db, $tag;
306 $db->do("DELETE FROM odin_shorturl WHERE tag = ?", undef, $tag);
311 ###--------------------------------------------------------------------------
314 our %PASTEBIN_DEFAULTS = (
315 title => "(untitled)",
319 our @PASTEBIN_PROPS = keys %PASTEBIN_DEFAULTS;
320 our $PASTEBIN_PROPCOLS = join ", ", @PASTEBIN_PROPS;
321 our $PASTEBIN_PROPPLACES = join ", ", map "?", @PASTEBIN_PROPS;
323 sub new_pastebin (\%) {
327 my ($editkey, $hash) = new_editkey;
330 merge_hash %$new, %PASTEBIN_DEFAULTS;
332 $tag = encode_tag next_seq $db, "odin_pastebin_seq";
333 $db->do("INSERT INTO odin_pastebin
334 (tag, edithash, owner, $PASTEBIN_PROPCOLS)
335 VALUES (?, ?, ?, $PASTEBIN_PROPPLACES)", undef,
336 $tag, $hash, $WHO, @{$new}{@PASTEBIN_PROPS});
338 return $tag, $editkey;
341 sub get_pastebin ($$\%) {
342 my ($db, $tag, $props) = @_;
344 (my $owner, my $hash, @{$props}{@PASTEBIN_PROPS}) =
345 $db->selectrow_array("SELECT owner, edithash, $PASTEBIN_PROPCOLS
346 FROM odin_pastebin WHERE tag = ?",
348 fail "tag `$tag' not found", ".notfound", tag => $tag
349 unless defined $owner;
350 return $owner, $hash;
353 sub get_pastebin_check_owner ($$\%) {
354 my ($db, $tag, $props) = @_;
356 my ($owner, $hash) = get_pastebin $db, $tag, %$props;
357 fail "not owner of `$tag'", ".notowner", tag => $tag
358 unless $WHOSURE && $WHO eq $owner;
361 sub get_pastebin_check_editkey_or_owner ($$$\%) {
362 my ($db, $tag, $editkey, $props) = @_;
364 if (!defined $editkey) { get_pastebin_check_owner $db, $tag, %$props; }
366 my ($owner, $hash) = get_pastebin $db, $tag, %$props;
367 fail "incorrect edit key for `$tag'", ".badhash", tag => $tag
368 unless $hash eq sha256_hex $editkey;
372 sub rekey_pastebin ($) {
378 get_pastebin_check_owner $db, $tag, my %hunoz;
379 ($editkey, my $hash) = new_editkey;
380 $db->do("UPDATE odin_pastebin SET edithash = ? WHERE tag = ?",
386 sub claim_pastebin ($$) {
387 my ($tag, $editkey) = @_;
390 $WHOSURE or fail "you can't claim pastes", ".notsure";
392 get_pastebin_check_editkey_or_owner $db, $tag, $editkey, my %hunoz;
393 $db->do("UPDATE odin_pastebin SET owner = ? WHERE tag = ?",
398 sub update_pastebin ($$\%) {
399 my ($tag, $editkey, $new) = @_;
404 get_pastebin_check_editkey_or_owner $db, $tag, $editkey, my %old;
405 for my $p (@PASTEBIN_PROPS) {
406 if (!defined $new->{$p}) { $new->{$p} = $old{$p}; }
408 $db->do("UPDATE odin_pastebin SET $p = ? WHERE tag = ?",
409 undef, $new->{$p}, $tag)
410 unless $new->{$p} eq $old{$p};
418 sub delete_pastebin (@) {
423 (my $tag, my $editkey, @a) = @a;
424 get_pastebin_check_editkey_or_owner $db, $tag, $editkey, my %hunoz;
425 $db->do("DELETE FROM odin_pastebin WHERE tag = ?", undef, $tag);
430 sub tidy_pastebin_content ($) {
432 return undef unless defined $content;
433 $content =~ tr/\r//d;
434 $content =~ s/([^\n])\z/$1\n/;
438 ###--------------------------------------------------------------------------
439 ### Simple option parser.
441 package Odin::OptParse;
444 my ($cls, @args) = @_;
455 if (!length $me->{cur}) {
456 my $args = $me->{args};
457 if (!@$args) { return undef; }
458 elsif ($args->[0] =~ /^[^-]|^-$/) { return undef; }
459 elsif ($args->[0] eq "--") { shift @$args; return undef; }
460 $me->{cur} = substr shift @$args, 1;
462 my $o = $me->{opt} = substr $me->{cur}, 0, 1;
463 $me->{cur} = substr $me->{cur}, 1;
470 if (length $me->{cur}) { $a = $me->{cur}; $me->{cur} = ""; }
471 elsif (@{$me->{args}}) { $a = shift @{$me->{args}}; }
472 else { $a = undef; $me->err("option `-$me->{opt}' requires an argument"); }
476 sub rest { return @{$_[0]->{args}}; }
477 sub ok { return $_[0]->{ok}; }
478 sub bad { $_[0]->{ok} = 0; }
479 sub err { $_[0]->bad; print STDERR "$PROG: $_[1]\n"; }
480 sub unk { $_[0]->err("unknown option `-$_[0]->{opt}'"); }
482 ###----- That's all, folks --------------------------------------------------