~grubng-dev/grubng/servers-dispatch-php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php

$workunit_folder = '/home/bartek/grub/workunits/wu/';
$uploadhost = 'grub.silc.org.ua:8088';
$workunits_choose_count = 5;
require("login.php");

if (!isset($_SERVER['PHP_AUTH_USER'])) 
{
    header('WWW-Authenticate: Basic realm="GrubNG"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Authorization required';
    exit;
} 

if ( ! check_login($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) )
{
   header('HTTP/1.0 401 Unauthorized');
   echo 'Bad username or password.';
   exit;
}

$wudir = opendir($workunit_folder);

if ($wudir === false)
{
   header("HTTP/1.0 500 Internal Server Error");
   echo 'Cannot open directory with workunits.';
   exit;
}

$workunits = array();
$count = 0;
while (false !== ($file = readdir($wudir)))
{
  if ($file != "." && $file != "..")
  {
	$workunits[] = $file;
	if (++$count >= $workunits_choose_count)
		break;
  }
}
closedir($wudir);

//If here no available workunits, inform client about it and exit
if (count($workunits) == 0)
{
  header("HTTP/1.0 503 Service Unavailable");
  header("Retry-After: 3600"); #An hour
  echo 'No workunits available.';
  exit;
}

do 
{
  if (count($workunits) == 0) 
    {
      header("HTTP/1.0 503 Service Unavailable");
      header("Retry-After: 2");
      echo 'Cannot get a workunit for you now. Please try again.';
      exit;
    }
  $index = rand(0, count($workunits) - 1);
  $workunit = $workunits[$index];
  unset($workunits[$index]);
} while (@readfile("$workunit_folder/$workunit") == false); #Get another workunit if false or 0

$key = sha1(substr($workunit, 0, -4) . " " . $_SERVER['PHP_AUTH_USER']);
echo "PUT /". urlencode($_SERVER['PHP_AUTH_USER']) . ".$key.arc.gz HTTP/1.0\r\nHost: $uploadhost\r\n\r\n";
unlink("$workunit_folder/$workunit");