fixing up the "is setup" check in the installer
[gwvp.git] / gwvplib / gwvpgitwebservice.php
1 <?php
2
3 $CALL_ME_FUNCTIONS["gitcontrol"] = "gwvp_gitControlCallMe";
4
5 //$MENU_ITEMS["20repos"]["text"] = "Repo Admin";
6 //$MENU_ITEMS["20repos"]["link"] = "$BASE_URL/admin/repos";
7 $HOME_PAGE_PROVIDERS["gitlog"] = "gwvp_GitLogProvider";
8
9 // TODO: we could actually change backend interface such that is
10 // will respond to any url's that contain "repo.git" rather then
11 // having to be $BASE_URL/git/repo.git
12 function gwvp_gitControlCallMe()
13 {
14         if(isset($_REQUEST["q"])) {
15                 $query = $_REQUEST["q"];
16                 $qspl = explode("/", $query);
17                 if(isset($qspl[0])) {
18                         if($qspl[0] == "git") {
19                                 return "gwvp_gitBackendInterface";
20                         }
21                 } 
22                 else return false;
23         }
24         
25         return false;
26         
27 }
28
29 function gwvp_GitLogProvider()
30 {
31         /*
32          * The home page provider will:
33          * 1) show the last 10 commits for every repository - though, excluding private repos
34          * 2) if loged in, show the last commit on any repo's the user owns
35          * 
36          * So i need a table thats going to list "writes" by user - as in POST writes but only
37          * put that info into the stats (doesnt exist) db if the repo is publically readable
38          * 
39          * Or... should we instead just list every repo?
40          */
41 }
42
43 function gwvp_repoPermissionCheck($repo, $user)
44 {
45         return true;
46 }
47
48 function gwvp_gitBackendInterface()
49 {
50         // and this is where i re-code the git backend interface from scratch
51         global $BASE_URL;
52         
53         $repo_base = gwvp_getConfigVal("repodir");
54         
55         // TODO: we need to stop passing the repo name around as "repo.git", it needs to be just "repo"
56         
57         
58         /* bizare git problem that ignores 403's or continues on with a push despite them 
59         error_log("FLAP for ".$_SERVER["REQUEST_URI"]);
60         if(isset($_REQUEST)) {
61                 $dump = print_r($_REQUEST, true);
62                 error_log("FLAP, $dump");
63         }
64         if(isset($_SERVER["PHP_AUTH_USER"])) {
65                 error_log("FLAP: donut hole");
66         }*/
67         
68         
69
70         
71         $repo = "";
72         $repoid = false;
73         $newloc = "/";
74         if(isset($_REQUEST["q"])) {
75                 $query = $_REQUEST["q"];
76                 $qspl = explode("/", $query);
77                 // TODO do this with 
78                 $repo = preg_replace("/\.git$/", "", $qspl[1]);
79                 $repoid = gwvp_GetRepoId($repo);
80                 for($i=2; $i < count($qspl); $i++) {
81                         $newloc .= "/".$qspl[$i];
82                 }
83         }
84         
85         if($repoid == false) {
86                 gwvp_fourZeroFour();
87                 return;
88         }
89         
90         // we do an update server cause its weird and i cant figure out when it actually needs to happen
91         chdir("$repo_base/$repo.git");
92         exec("/usr/bin/git update-server-info");
93         
94         
95         // so now we have the repo
96         // next we determine if this is a read or a write
97         $write = false;
98         if(isset($_REQUEST["service"])) {
99                 if($_REQUEST["service"] == "git-receive-pack") {
100                         error_log("got write as receivepack in post");
101                         $write = true;
102                 }
103         }
104         if($_SERVER["REQUEST_METHOD"] == "POST") {
105                 $write = true;
106         }
107         // THIS MAY CAUSE ISSUES LATER ON but we do it cause the git client ignores our 403 when it uses git-receive-pack after an auth
108         // no, this isnt a solution cause auth'd read attempts will come up as writes...
109         //if(isset($_SERVER["PHP_AUTH_USER"])) {
110                 //$write = true;
111         //}
112         
113         // if its a write, we push for authentication
114         if($write) {
115                 error_log("is write attempt, ask for login");
116                 $person = gwvp_checkBasicAuthLogin();
117                 if($person == false) {
118                         gwvp_AskForBasicAuth();
119                         return;
120                 } else {
121                         error_log("checking perms for $person against $repoid for repo $repo");
122                         $perms = gwvp_resolvRepoPerms(gwvp_getUserId(null, $person), $repoid);
123                         if($perms < 3) {
124                                 error_log("perms are $perms and im not allowed");
125                                 gwvp_fourZeroThree();
126                                 exit(0);
127                         } else {
128                                 // here we pass to the git backend
129                                 error_log("perms are $perms and im allowed");
130                                 gwvp_callGitBackend($person["username"], $repo);
131                         }
132                 }
133                 return;
134         }
135         
136         // if not we figure out the anon permissions for a repo
137         $perms = gwvp_resolvRepoPerms(-1, $repoid);
138         
139         // if they're less then read, we need to then check the user auth permissions
140         if($perms < 2) {
141                 // we ask for auth
142                 $person = gwvp_checkBasicAuthLogin();
143                 if($person == false) {
144                         gwvp_AskForBasicAuth();
145                         return;
146                 } else {
147                         $perms = gwvp_resolvRepoPerms(gwvp_getUserId(null, $person), $repoid);
148                         if($perms < 2) {
149                                 $dump = print_r($person, true);
150                                 error_log("in basic read, called 403 for $perms $dump");
151                                 gwvp_fourZeroThree();
152                                 return;
153                         }
154                 }
155         }
156         
157         // if we made it this far, we a read and we have permissions to do so, just search the file from the repo
158         if(file_exists("$repo_base/$repo.git/$newloc")) {
159                 error_log("would ask $repo for $repo.git/$newloc from $repo_base/$repo.git/$newloc");
160                 $fh = fopen("$repo_base/$repo.git/$newloc", "rb");
161                 
162                 error_log("pushing file");
163                 while(!feof($fh)) {
164                         echo fread($fh, 8192);
165                 }
166         } else {
167                 //echo "would ask $repo,$actual_repo_name for $repo/$newloc from $repo_base/$repo/$newloc, NE";
168                 gwvp_fourZeroFour();
169                 return;
170         }
171         
172 }
173
174
175 function gwvp_gitBackendInterface_old()
176 {
177         global $BASE_URL;
178         
179         $repo_base = gwvp_getConfigVal("repodir");
180         
181         $repo = "";
182         $newloc = "/";
183         if(isset($_REQUEST["q"])) {
184                 $query = $_REQUEST["q"];
185                 $qspl = explode("/", $query);
186                 $repo = $qspl[1];
187                 for($i=2; $i < count($qspl); $i++) {
188                         $newloc .= "/".$qspl[$i];
189                 }
190         }
191         
192         $actual_repo_name = preg_replace("/\.git$/", "", $repo); 
193         
194         $user = gwvp_checkBasicAuthLogin();
195
196         if(!$user) {
197                 error_log("User is set to false, so its anonymouse");
198         } else {
199                 error_log("user is $user");
200         }
201         
202         // must remember that $user of false is anonymous when we code gwvp_repoPerm'sCheck()
203         if(!gwvp_repoPermissionCheck($actual_repo_name, $user)) {
204                 error_log("perms check fails - start auth");
205                 if(isset($_SERVER["PHP_AUTH_USER"])) {
206                         error_log("have auth - push 403");
207                         gwvp_fourZeroThree();
208                 } else {
209                         error_log("push auth");
210                         gwvp_AskForBasicAuth();
211                         return;
212                 }
213         }
214         
215         // we need to quite a bit of parsing in here. The "repo" will always be /git/repo.git
216         // but if we get here from a browser, we need to forward back to a normal repo viewer
217         // the only way i can think of doing this is to check the useragent for the word "git"
218         
219         /*
220          * here we need to
221          * 1) figure out the repo its acessing
222          * 2) figure out the perms on the repo
223          * 3) determine if its a pull or a push
224          * - if its a pull, we just serve straight from the fs
225          * - if its a push, we go thru git-http-backend
226          * 4) if it requiers auth, we push to auth
227          * 
228          */
229         $agent = "git-unknown";
230         $isgitagent = false;
231         
232         // tested the user agent bit with jgit from eclipse and normal git... seems to work
233         if(isset($_SERVER["HTTP_USER_AGENT"])) {
234                 $agent = $_SERVER["HTTP_USER_AGENT"];
235                 error_log("in git backend with user agent $agent");
236                 if(stristr($agent, "git")!==false) {
237                         $isgitagent = true;
238                 }
239         }
240         
241         
242                 
243         /* dont need this code right now
244         if($isgitagent) echo "GIT: i am a git backened interface for a repo $repo, agent $agent";
245         else echo "NOT GIT: i am a git backened interface for a repo $repo, agent $agent";
246         */
247         
248         // now we need to rebuild the actual request or do we?
249         //$basegit = "$BASE_URL/git/something.git";
250         //$newloc = preg_replace("/^$basegit/", "", $_SERVER["REQUEST_URI"]);
251         chdir("$repo_base/$repo");
252         exec("/usr/bin/git update-server-info");
253         
254         if($_SERVER["REQUEST_METHOD"] == "POST") {
255                         gwvp_AskForBasicAuth();
256                         gwvp_callGitBackend($repo);
257                         return;
258         }
259         
260         if(isset($_REQUEST["service"])) {
261                 if($_REQUEST["service"] == "git-receive-pack") {
262                         // we are a write call - we need auth and we're going to the backend proper
263                         gwvp_AskForBasicAuth();
264                         gwvp_callGitBackend($repo);
265                         return;
266                 }
267         }
268         
269         
270         if(file_exists("$repo_base/$repo/$newloc")) {
271                 error_log("would ask $repo,$actual_repo_name for $repo/$newloc from $repo_base/$repo/$newloc");
272                 $fh = fopen("$repo_base/$repo/$newloc", "rb");
273                 
274                 error_log("pushing file");
275                 while(!feof($fh)) {
276                         echo fread($fh, 8192);
277                 }
278         } else {
279                 echo "would ask $repo,$actual_repo_name for $repo/$newloc from $repo_base/$repo/$newloc, NE";
280                 header('HTTP/1.0 404 No Such Thing');
281                 return;
282         }
283 }
284
285 function gwvp_canManageRepo($userid, $repoid)
286 {
287         // only the owner or an admin can do these tasks
288         error_log("Checking repoid, $repoid against userid $userid");
289         
290         if(gwvp_IsUserAdmin(null, null, $userid)) return true;
291         if(gwvp_IsRepoOwner($userid, $repoid)) return true;
292         return false;
293 }
294
295 function gwvp_callGitBackend($username, $repo)
296 {
297         // this is where things become a nightmare
298                 $fh   = fopen('php://input', "r");
299                 
300                 $ruri = $_SERVER["REQUEST_URI"];
301                 $strrem = "git/$repo.git";
302                 $euri = str_replace($strrem, "", $_REQUEST["q"]);
303                 //$euri = preg_replace("/^git\/$repo\.git/", "", $_REQUEST["q"]);
304                 
305                 
306                 
307                 $rmeth = $_SERVER["REQUEST_METHOD"];
308                 
309                 $qs = "";
310                 foreach($_REQUEST as $key => $var) {
311                         if($key != "q") {
312                                 //error_log("adding, $var from $key");
313                                 if($qs == "") $qs.="$key=$var";
314                                 else $qs.="&$key=$var";
315                         }
316                 }
317                 
318                 //sleep(2);
319                 
320                 
321                 
322                 // this is where the fun, it ends.
323                 $myoutput = "";
324                 unset($myoutput);
325                 
326                 // this be nasty!
327                 
328                 // setup env
329                 if(isset($procenv))     unset($procenv);
330                 $procenv["GATEWAY_INTERFACE"] = "CGI/1.1";
331                 $procenv["PATH_TRANSLATED"] = "/tmp/$repo.git/$euri";
332                 $procenv["REQUEST_METHOD"] = "$rmeth";
333                 $procenv["GIT_HTTP_EXPORT_ALL"] = "1";
334                 $procenv["QUERY_STRING"] = "$qs";
335                 $procenv["HTTP_USER_AGENT"] = "git/1.7.1";
336                 $procenv["REMOTE_USER"] = "$username";
337                 $procenv["REMOTE_ADDR"] = $_SERVER["REMOTE_ADDR"];
338                 $procenv["AUTH_TYPE"] = "Basic";
339                 
340                 if(isset($_SERVER["CONTENT_TYPE"])) { 
341                         $procenv["CONTENT_TYPE"] = $_SERVER["CONTENT_TYPE"];
342                 } else {
343                         //$procenv["CONTENT_TYPE"] = "";
344                 }
345                 if(isset($_SERVER["CONTENT_LENGTH"])) { 
346                         $procenv["CONTENT_LENGTH"] = $_SERVER["CONTENT_LENGTH"];
347                 }
348                 
349                 error_log("path trans'd is /tmp/$repo.git/$euri from $ruri with ".$_REQUEST["q"]." $strrem");
350                 
351                 
352                 
353
354                 $pwd = "/tmp/";
355                 
356                 $proc = proc_open("/usr/lib/git-core/git-http-backend", array(array("pipe","rb"),array("pipe","wb"),array("file","/tmp/err", "a")), $pipes, $pwd, $procenv);
357                 
358                 $untilblank = false;
359                 while(!$untilblank&&!feof($pipes[1])) {
360                         $lines_t = fgets($pipes[1]);
361                         $lines = trim($lines_t);
362                         error_log("got line: $lines");
363                         if($lines_t == "\r\n") {
364                                 $untilblank = true;
365                                 error_log("now blank");
366                         } else header($lines);
367                         if($lines === false) {
368                                 error_log("got an unexpexted exit...");
369                                 exit(0);
370                         }
371                         
372                 }
373                 
374
375                 $firstline = true;
376                 $continue = true;
377                 
378                 if(!stream_set_blocking($fh,0)) {
379                         error_log("cant set input non-blocking");
380                 }
381
382                 if(!stream_set_blocking($pipes[1],0)) {
383                         error_log("cant set pipe1 non-blocking");
384                 }
385                 
386                 // i was going to use stream_select, but i feel this works better like this
387                 while($continue) {
388                         // do client
389                         if(!feof($fh)) {
390                                 $from_client_data = fread($fh,8192);
391                                 if($from_client_data !== false) fwrite($pipes[0], $from_client_data);
392                                 fflush($pipes[0]);
393                                 //fwrite($fl, $from_client_data);
394                                 $client_len = strlen($from_client_data);
395                         } else {
396                                 error_log("client end");
397                                 $client_len = 0;
398                         }
399                         
400                         // do cgi
401                         // sometimes, we get a \r\n from the cgi, i do not know why she swallowed the fly,
402                         // but i do know that the fgets for the headers above should have comsued that
403                         if(!feof($pipes[1])) {
404                                 $from_cgi_data_t = fread($pipes[1],8192);
405                                 $from_cgi_data = $from_cgi_data_t;
406                                 
407                                 // i dont know if this will solve it... it coudl cause some serious issues elsewhere
408                                 // TODO: this is a hack, i need to know why the fgets above doesn consume the \r\n even tho it reads it
409                                 // i.e. why the pointer doesnt increment over it, cause the freads above then get them again.
410                                 if($firstline) {
411                                         if(strlen($from_cgi_data_t)>0) {
412                                                 // i dont get why this happens, and its very frustrating.. im not sure if its a bug in php
413                                                 // or something the git-http-backend thing is doing..
414                                                 // TODO: find out why this happens
415                                                 $from_cgi_data = preg_replace("/^\r\n/", "", $from_cgi_data_t);
416                                                 if(strlen($from_cgi_data)!=strlen($from_cgi_data_t)) {
417                                                         error_log("MOOOKS - we did trunc");
418                                                 } else {
419                                                         error_log("MOOOKS - we did not trunc");
420                                                 }
421                                                 $firstline = false;
422                                         }
423                                 }
424                                 
425                                 if($from_cgi_data !== false) {
426                                         echo $from_cgi_data;
427                                         flush();
428                                 }
429                                 $cgi_len = strlen($from_cgi_data);
430                         } else {
431                                 error_log("cgi end");
432                                 $cgi_len = 0;
433                         }
434                         
435                         if(feof($pipes[1])) $continue = false;
436                         else {
437                                 if($client_len == 0 && $cgi_len == 0) {
438                                         usleep(200000);
439                                         error_log("sleep tick");
440                                 } else {
441                                         error_log("sizes: $client_len, $cgi_len");
442                                         if($cgi_len > 0) {
443                                                 error_log("from cgi: \"$from_cgi_data\"");
444                                         }
445                                 }
446                         }
447                         
448                 }
449                 
450                 
451                 //fclose($fl);
452                 fclose($fh);
453                 fclose($pipes[1]);
454                 fclose($pipes[0]);      
455 }
456
457
458
459 function gwvp_repoExists($name)
460 {
461         $repo_base = gwvp_getConfigVal("repodir");
462         
463         if(file_exists("$repo_base/$name.git")) return true;
464         else return false;
465 }
466
467 // default perms:
468 // 0 - anyone can clone/read, only owner can write
469 // 1 - noone can clone/read, repo is visible (i.e. name), only owner can read/write repo
470 // 2 - only owner can see anything
471 function gwvp_createGitRepo($name, $ownerid, $desc, $bundle=null, $defaultperms=0)
472 {
473         $repo_base = gwvp_getConfigVal("repodir");
474         
475         // phew, this works, but i tell you this - bundles arent quite as nice as they should be
476         if($bundle == null) {
477                 error_log("would create $repo_base/$name.git");
478                 exec("/usr/bin/git init $repo_base/$name.git --bare > /tmp/gitlog 2>&1");
479                 chdir("$repo_base/$name.git");
480                 exec("/usr/bin/git update-server-info");
481         } else {
482                 error_log("create via mirror on $repo_base/$name.git");
483                 exec("/usr/bin/git clone --mirror $bundle $repo_base/$name.git > /tmp/gitlog 2>&1");
484                 chdir("$repo_base/$name.git");
485                 exec("/usr/bin/git update-server-info");
486         }
487
488         // gwvp_AddRepo($reponame, $repodesc, $repoowner, $defaultperms = 0)
489         gwvp_AddRepo($name, $desc, $ownerid, $defaultperms);
490         
491         return true;
492 }
493
494 // this funciton returns one of three things, read, visible, write, none
495 // as
496 // 0 - none
497 // 1 - visible
498 // 2 - read
499 // 3 - write
500 // 4 - owner/administrator
501 function gwvp_resolvRepoPerms($userid, $repoid)
502 {
503         $ownerid = gwvp_getRepoOwner($repoid);
504         $isadmin = gwvp_IsUserAdmin(null, null, $userid);
505         
506         error_log("USerid is $userid, ownerid $ownerid");
507         
508         if($isadmin) return 4;
509         
510         if($userid == $ownerid) return 4;
511         
512         // now we load the perms table and pray
513         $repoperms = gwvp_getRepoPermissions($repoid);
514         $usergroups = gwvp_getGroupsForUser(null, $userid);
515
516         $maxperm = 0;
517         if($repoperms != false) foreach($repoperms as $perm) {
518                 // need to go thru each perm, then check it agains the user we're trying to figure
519                 // the perms on
520                 switch($perm["type"]) {
521                         case "read":
522                                 $permval = 2;
523                                 break;
524                         case "visible":
525                                 $permval = 1;
526                                 break;
527                         case "write":
528                                 $permval = 3;
529                                 break;
530                         default:
531                                 $permval = 0;
532                 }
533                 
534                 // we only var if permval is greater then current
535                 if($permval > $maxperm) {
536                         //error_log("going into check for $maxperm/$permval, ".$perm["ref"]);
537                         if($perm["ref"] == "anon") {
538                                 $maxperm = $permval;
539                         } else if($perm["ref"] == "authed") {
540                                 $maxperm = $permval;
541                         } else {
542                                 // now we do splits
543                                 $spl = explode(":", $perm["ref"]);
544                                 $idtype = $spl[0];
545                                 $idval = $spl[1];
546                                 if($idtype == "group") {
547                                         // function gwvp_IsGroupMember($email, $groupname)
548                                         if(gwvp_IsGroupMemberById($userid, $idval)) $maxperm = $permval;
549                                 } else if ($idtype == "user") {
550                                         //error_log("checking $userid, $idval");
551                                         if($userid == $idval) $maxperm = $permval;
552                                 }
553                         }
554                 }
555         }
556         
557         // thats TOTALLY going to work... -_0 we should really write a unit test for this, but thats a bit
558         // hard given the db req's so for now, we'll leave it as is
559         return $maxperm;
560 }
561
562 ?>