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