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