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