6 use Digest::SHA qw(sha256_hex);
10 ###--------------------------------------------------------------------------
13 sub merge_hash (\%%) {
14 my ($hashref, %defaults) = @_;
15 for my $k (keys %defaults)
16 { $hashref->{$k} = $defaults{$k} unless exists $hashref->{$k}; }
19 ###--------------------------------------------------------------------------
22 our $DSN = "dbi:Pg(pg_enable_utf8=>1):host=db";
24 our @BACKOFF = (0.1, 10, 1.5, 0.5, 2.0);
26 our $BASEURL = "http://odin.gg/";
27 our $STATIC = "http://odin.gg/";
29 our $SHORTURL_PATH = "u";
30 our $PASTEBIN_PATH = "p";
32 our $URLMAXLEN = 1024;
37 our $PASTEMAXLEN = 1024*1024;
39 our %COOKIE_DEFAULTS = (
46 our ($SCHEME, $DOMAIN, $BASEPATH) = $BASEURL =~ m!^([^:]+)://([^/]+)(/.*)$!;
47 merge_hash %COOKIE_DEFAULTS, -domain => $DOMAIN, -path => $BASEPATH;
48 merge_hash %COOKIE_DEFAULTS, -secure => undef if $SCHEME eq "https";
50 our $SHORTURL = "$BASEURL$SHORTURL_PATH";
51 our $PASTEBIN = "$BASEURL$PASTEBIN_PATH";
53 ###--------------------------------------------------------------------------
54 ### Miscellaneous utilities.
57 sub update_now () { $NOW = time; }
60 (our $PROG = $0) =~ s:^.*/::;
62 sub fail_cmdline ($$%) {
63 my ($msg, $label, %args) = @_;
64 print STDERR "$PROG: $msg\n";
68 our $FAILPROC = \&fail_cmdline;
71 my ($msg, $label, %args) = @_;
72 $FAILPROC->($msg, $label, %args);
75 sub set_mason_failproc ($) {
78 my ($msg, $label, %args) = @_;
80 $m->comp($label, %args);
91 sub print_columns (@) {
95 while (@col && $col[1] eq "") { splice @col, 0, 2; }
96 my ($wd, $v) = splice @col, 0, 2;
97 push @fmt, "%s"; push @val, $v;
99 my ($wd, $v) = splice @col, 0, 2;
100 push @fmt, "%-${wd}s";
103 printf join(" ", reverse @fmt) . "\n", reverse @val;
108 return $t == -1 ? "--" : strftime "%Y-%m-%d %H:%M:%S %z", localtime $t;
111 ###--------------------------------------------------------------------------
112 ### Database utilities.
116 my $db = DBI->connect_cached($DSN, undef, undef, {
122 my $drv = $db->{Driver}{Name};
124 $db->{private_odin_retry_p} = sub { $db->state =~ /^40[0P]01$/ };
125 } elsif ($drv eq "SQLite") {
126 $db->{private_odin_retry_p} = sub { $db->err == 5 };
128 $db->{private_odin_retry_p} = sub { 0 };
135 my ($body, $db) = @_;
139 my ($sleep, $maxsleep, $mult, $minvar, $maxvar) = @BACKOFF;
140 for (my $i = 0; $i < $RETRY; $i++) {
142 eval { @rv = $body->(); $db->commit; };
144 return @rv unless $exc;
145 my $retryp = $db->{private_odin_retry_p}();
146 eval { $db->rollback; };
147 die $exc unless $retryp;
148 my $t = $sleep * ($minvar + rand($maxvar - $minvar));
149 $sleep *= $mult; $sleep = $max if $sleep > $max;
150 select undef, undef, undef, $t;
156 ###--------------------------------------------------------------------------
157 ### Sequence numbers and tagging.
160 my ($db, $table) = @_;
161 my ($seq) = $db->selectrow_array("SELECT seq FROM $table");
162 die "no sequence number in $table" unless defined $seq;
163 $db->do("UPDATE $table SET seq = ?", undef, $seq + 1);
168 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
169 my $NALPHA = length $ALPHABET;
175 $tag .= substr($ALPHABET, $seq % $NALPHA, 1);
176 $seq = int $seq/$NALPHA;
181 ###--------------------------------------------------------------------------
185 sub fetch_cookies ($) {
189 my $cookies = $r->header_in("Cookie");
190 if (defined $cookies) {
191 for my $kv (split /;/, $cookies) {
192 my ($k, $v) = split /=/, $kv, 2;
193 $k =~ s/^\s*(|\S|\S.*\S)\s*$/$1/;
194 $v =~ s/^\s*(|\S|\S.*\S)\s*$/$1/;
196 $v =~ s/\%([0-9a-f][0-9a-f])/chr hex $1/eg;
202 sub bake_cookie ($$%) {
203 my ($r, $cookie, %attr) = @_;
204 merge_hash %attr, %COOKIE_DEFAULTS;
206 my $v = $attr{$_}; tr/_-/-/d;
207 defined $v ? "$_=$v" : $_
209 $r->headers_out->add("Set-Cookie", join "; ", $cookie, @attr);
214 return $ENV{PATH_INFO} // $r->path_info;
217 ###--------------------------------------------------------------------------
220 sub escapify ($$;$) {
221 my ($m, $s, $mode) = @_;
222 return $m->interp->apply_escapes($s, $mode // "h");
225 ###--------------------------------------------------------------------------
228 our ($WHO, $WHOSURE);
229 our ($WHOMATCH, $WHOCMP, $WHOPAT);
233 my $raddr = $ENV{REMOTE_ADDR} // $r->connection->remote_ip;
234 $WHO = ":NET-$raddr"; $WHOSURE = 0;
235 $WHOMATCH = "LIKE"; $WHOCMP = ":NET-\%"; $WHOPAT = qr/^:NET-/;
239 $WHO = $ENV{USERV_USER}
240 // ($< == $> && $ENV{USER})
241 // @{[getpwuid $<]}[0]
242 // die "nameless user";
243 $WHOMATCH = "="; $WHOCMP = $WHO; $WHOPAT = qr/^\Q$WHO\E$/;
248 open my $fh, "/dev/urandom" or die "open urandom: $!";
249 sysread $fh, my $rand, 16;
250 (my $edit = encode_base64 $rand) =~ tr:+/=\n:.-:d;
251 return $edit, sha256_hex $edit;
254 ###--------------------------------------------------------------------------
257 sub get_shorturl ($) {
261 my ($url) = $db->selectrow_array
262 ("SELECT url FROM odin_shorturl WHERE tag = ?", undef, $tag);
263 fail "tag `$tag' not found", ".notfound", tag => $tag unless defined $url;
267 sub valid_url_p ($) {
270 length $url < $URLMAXLEN &&
271 scalar grep { $url =~ /$_/ } @URLPAT;
274 sub new_shorturl ($) {
277 valid_url_p $url or fail "invalid url", ".badurl", u => $url;
282 ($tag) = $db->selectrow_array
283 ("SELECT tag FROM odin_shorturl WHERE owner $WHOMATCH ? AND url = ?",
284 undef, $WHOCMP, $url);
285 unless (defined $tag) {
286 $tag = encode_tag(next_seq($db, "odin_shorturl_seq"));
287 $db->do("INSERT INTO odin_shorturl (tag, stamp, owner, url)
288 VALUES (?, ?, ?, ?)", undef,
289 $tag, $NOW, $WHO, $url);
295 sub check_shorturl_owner ($$) {
298 my ($owner) = $db->selectrow_array
299 ("SELECT owner FROM odin_shorturl WHERE tag = ?", undef, $tag);
300 fail "tag `$tag' not found", ".notfound", tag => $tag
301 unless defined $owner;
302 fail "not owner of `$tag'", ".notowner", tag => $tag
303 unless $owner =~ /$WHOPAT/;
306 sub update_shorturl ($$) {
307 my ($tag, $url) = @_;
311 check_shorturl_owner $db, $tag;
312 $db->do("UPDATE odin_shorturl SET url = ? WHERE tag = ?",
317 sub delete_shorturl (@) {
322 for my $tag (@tags) {
323 check_shorturl_owner $db, $tag;
324 $db->do("DELETE FROM odin_shorturl WHERE tag = ?", undef, $tag);
329 ###--------------------------------------------------------------------------
332 our %PASTEBIN_DEFAULTS = (
333 title => "(untitled)",
337 our @PASTEBIN_PROPS = keys %PASTEBIN_DEFAULTS;
338 our $PASTEBIN_PROPCOLS = join ", ", @PASTEBIN_PROPS;
339 our $PASTEBIN_PROPPLACES = join ", ", map "?", @PASTEBIN_PROPS;
341 sub new_pastebin (\%) {
345 my ($editkey, $hash) = new_editkey;
348 merge_hash %$new, %PASTEBIN_DEFAULTS;
350 $tag = encode_tag next_seq $db, "odin_pastebin_seq";
351 $db->do("INSERT INTO odin_pastebin
352 (tag, stamp, edithash, owner, $PASTEBIN_PROPCOLS)
353 VALUES (?, ?, ?, ?, $PASTEBIN_PROPPLACES)", undef,
354 $tag, $NOW, $hash, $WHO, @{$new}{@PASTEBIN_PROPS});
356 return $tag, $editkey;
359 sub get_pastebin ($$\%) {
360 my ($db, $tag, $props) = @_;
362 (my $owner, my $hash, @{$props}{@PASTEBIN_PROPS}) =
363 $db->selectrow_array("SELECT owner, edithash, $PASTEBIN_PROPCOLS
364 FROM odin_pastebin WHERE tag = ?",
366 fail "tag `$tag' not found", ".notfound", tag => $tag
367 unless defined $owner;
368 return $owner, $hash;
371 sub get_pastebin_check_owner ($$\%) {
372 my ($db, $tag, $props) = @_;
374 my ($owner, $hash) = get_pastebin $db, $tag, %$props;
375 fail "not owner of `$tag'", ".notowner", tag => $tag
376 unless $WHOSURE && $WHO eq $owner;
379 sub get_pastebin_check_editkey_or_owner ($$$\%) {
380 my ($db, $tag, $editkey, $props) = @_;
382 if (!defined $editkey) { get_pastebin_check_owner $db, $tag, %$props; }
384 my ($owner, $hash) = get_pastebin $db, $tag, %$props;
385 fail "incorrect edit key for `$tag'", ".badhash", tag => $tag
386 unless $hash eq sha256_hex $editkey;
390 sub rekey_pastebin ($) {
396 get_pastebin_check_owner $db, $tag, my %hunoz;
397 ($editkey, my $hash) = new_editkey;
398 $db->do("UPDATE odin_pastebin SET edithash = ? WHERE tag = ?",
404 sub claim_pastebin ($$) {
405 my ($tag, $editkey) = @_;
408 $WHOSURE or fail "you can't claim pastes", ".notsure";
410 get_pastebin_check_editkey_or_owner $db, $tag, $editkey, my %hunoz;
411 $db->do("UPDATE odin_pastebin SET owner = ? WHERE tag = ?",
416 sub update_pastebin ($$\%) {
417 my ($tag, $editkey, $new) = @_;
422 get_pastebin_check_editkey_or_owner $db, $tag, $editkey, my %old;
423 for my $p (@PASTEBIN_PROPS) {
424 if (!defined $new->{$p}) { $new->{$p} = $old{$p}; }
426 $db->do("UPDATE odin_pastebin SET $p = ? WHERE tag = ?",
427 undef, $new->{$p}, $tag)
428 unless $new->{$p} eq $old{$p};
436 sub delete_pastebin (@) {
441 (my $tag, my $editkey, @a) = @a;
442 get_pastebin_check_editkey_or_owner $db, $tag, $editkey, my %hunoz;
443 $db->do("DELETE FROM odin_pastebin WHERE tag = ?", undef, $tag);
448 sub tidy_pastebin_content ($) {
450 return undef unless defined $content;
451 $content =~ tr/\r//d;
452 $content =~ s/([^\n])\z/$1\n/;
453 length $content <= $PASTEMAXLEN or
454 fail "invalid paste content", ".badpaste";
458 ###--------------------------------------------------------------------------
459 ### Simple option parser.
461 package Odin::OptParse;
464 my ($cls, @args) = @_;
475 if (!length $me->{cur}) {
476 my $args = $me->{args};
477 if (!@$args) { return undef; }
478 elsif ($args->[0] =~ /^[^-]|^-$/) { return undef; }
479 elsif ($args->[0] eq "--") { shift @$args; return undef; }
480 $me->{cur} = substr shift @$args, 1;
482 my $o = $me->{opt} = substr $me->{cur}, 0, 1;
483 $me->{cur} = substr $me->{cur}, 1;
490 if (length $me->{cur}) { $a = $me->{cur}; $me->{cur} = ""; }
491 elsif (@{$me->{args}}) { $a = shift @{$me->{args}}; }
492 else { $a = undef; $me->err("option `-$me->{opt}' requires an argument"); }
496 sub rest { return @{$_[0]->{args}}; }
497 sub ok { return $_[0]->{ok}; }
498 sub bad { $_[0]->{ok} = 0; }
499 sub err { $_[0]->bad; print STDERR "$PROG: $_[1]\n"; }
500 sub unk { $_[0]->err("unknown option `-$_[0]->{opt}'"); }
502 ###----- That's all, folks --------------------------------------------------