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