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