424c108e1d78c3a67e229ddc8cfe3657b9432219
[gwvp-mini.git] / gwvpmini / gwvpmini_gitbackend.php
1 <?php
2
3 $CALL_ME_FUNCTIONS["gitcontrol"] = "gwvpmini_gitControlCallMe";
4
5 //$MENU_ITEMS["20repos"]["text"] = "Repo Admin";
6 //$MENU_ITEMS["20repos"]["link"] = "$BASE_URL/admin/repos";
7
8 // TODO: we could actually change backend interface such that is
9 // will respond to any url's that contain "repo.git" rather then
10 // having to be $BASE_URL/git/repo.git
11 function gwvpmini_gitControlCallMe()
12 {
13         if(isset($_REQUEST["q"])) {
14                 $query = $_REQUEST["q"];
15                 $qspl = explode("/", $query);
16                 if(isset($qspl[0])) {
17                         if($qspl[0] == "git") {
18                                 return "gwvpmini_gitBackendInterface";
19                         }
20                 } 
21                 else return false;
22         }
23         
24         return false;
25         
26 }
27
28
29 function gwvpmini_CreateRepoHooks($repopath, $cmdpath, $reponame)
30 {
31         $fp = fopen("$repopath/hooks/pre-receive", "w");
32         
33         if(!$fp) error_log("could not create pre-receive hook");
34         
35         // TODO: think about this one
36         //$script = '#!/bin/bash'."\n\n".'DCOMMIT=`cat`'."\n".'START=`echo $DCOMMIT|cut -d " " -f 1`'."\n".'END=`echo $DCOMMIT|cut -d " " -f 2`'."\n".'REF=`echo $DCOMMIT|cut -d " " -f 3`'."\n\n";
37         $script = "#!/bin/bash\n\nDCOMMIT=".'`cat`'."\n\nphp $cmdpath $reponame \$REMOTE_USER pre-receive \$DCOMMIT\n\n";
38         fwrite($fp, $script);
39         
40         fclose($fp);
41         
42         chmod("$repopath/hooks/pre-receive", 0755);
43
44
45         $fp = fopen("$repopath/hooks/update", "w");
46         
47         if(!$fp) error_log("could not create update hook");
48         
49         // TODO: think about this one
50         unset($script);
51         $script = "#!/bin/bash\n\nphp $cmdpath $reponame \$REMOTE_USER update \$1 \$2 \$3\n\n";
52         fwrite($fp, $script);
53         
54         fclose($fp);
55         
56         chmod("$repopath/hooks/update", 0755);
57 }
58
59 function gwvpmini_gitBackendInterface()
60 {
61         // and this is where i re-code the git backend interface from scratch
62         global $BASE_URL, $cmd_line_tool;
63         
64         header_remove("Pragma");\r
65         header_remove("Cache-Control");\r
66         header_remove("Set-Cookie");\r
67         header_remove("Expires");\r
68         header_remove("X-Powered-By");\r
69         header_remove("Vary");
70         //header("Content-Encoding: none");\r
71         
72         
73         $repo_base = gwvpmini_getConfigVal("repodir");
74         
75         // TODO: we need to stop passing the repo name around as "repo.git", it needs to be just "repo"
76         
77         
78         /* bizare git problem that ignores 403's or continues on with a push despite them 
79         // error_log("FLAP for ".$_SERVER["REQUEST_URI"]);
80         if(isset($_REQUEST)) {
81                 $dump = print_r($_REQUEST, true);
82                 // error_log("FLAP, $dump");
83         }
84         if(isset($_SERVER["PHP_AUTH_USER"])) {
85                 // error_log("FLAP: donut hole");
86         }*/
87         
88         error_log("REQUESTINBACKEND: ".print_r($_REQUEST, true));
89         
90         $repo = "";
91         $repoid = false;
92         $newloc = "/";
93         if(isset($_REQUEST["q"])) {
94                 $query = $_REQUEST["q"];
95                 $qspl = explode("/", $query);
96                 // TODO do this with 
97                 $repo = preg_replace("/\.git$/", "", $qspl[1]);
98                 $repoid = gwvpmini_GetRepoId($repo);
99                 for($i=2; $i < count($qspl); $i++) {
100                         $newloc .= "/".$qspl[$i];
101                 }
102         }
103         
104         if($repoid == false) {
105                 gwvpmini_fourZeroFour();
106                 return;
107         }
108         
109         // we do an update server cause its weird and i cant figure out when it actually needs to happen
110         chdir("$repo_base/$repo.git");
111         // dont believe i have to do this
112         //exec("/usr/bin/git update-server-info");
113         
114         if(!file_exists("$repo_base/$repo.git/hooks/pre-receive") || !file_exists("$repo_base/$repo.git/hooks/update")) {
115                 // error_log("WRITING HOOKS");
116                 gwvpmini_CreateRepoHooks("$repo_base/$repo.git", $cmd_line_tool, $repo);
117         }
118         
119         
120         // so now we have the repo
121         // next we determine if this is a read or a write
122         
123         // TODO: WE NEED TO FIX THIS, IT DOESNT ALWAYS DETECT a "WRITE"
124         $write = false;
125         if(isset($_REQUEST["service"])) {
126                 if($_REQUEST["service"] == "git-receive-pack") {
127                         // error_log("got write as receivepack in post");
128                         $write = true;
129                 }
130         }
131         if(preg_match("/.*git-receive-pack$/", $_REQUEST["q"])) $write = true;
132         //$write = true;
133         // 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
134         // no, this isnt a solution cause auth'd read attempts will come up as writes...
135         //if(isset($_SERVER["PHP_AUTH_USER"])) {
136                 //$write = true;
137         //}
138         
139         
140         $person = gwvpmini_checkBasicAuthLogin();
141         //$write = true;
142         // next, figure out permissions for repo
143         $rid = gwvpmini_GetRepoId($repo);
144         $uid = -1;
145         // error_log("AT THIS POINT WE HAVE $uid, $rid, $repo $person");
146         
147         if(!$person) {
148                 if($write) {
149                         // error_log("ASK FOR BASIC AUTH");
150                         gwvpmini_AskForBasicAuth();
151                         return;
152                 } else {
153                         $perm = gwvpmini_GetRepoPerm($rid, "a");
154                         if($perm < 1) {
155                                 // error_log("ASK FOR BASIC AUTH 2");
156                                 gwvpmini_AskForBasicAuth();
157                                 return;
158                         }
159                 }
160         } else {
161                 $uid = gwvpmini_GetUserId($person);
162                 $perm = gwvpmini_GetRepoPerm($rid, $uid);
163                 if($write) {
164                         if($perm < 2) {
165                                 // error_log("SEND FOFF");
166                                 gwvpmini_fourZeroThree();
167                                 return;
168                         }
169                 } else {
170                         if($perm < 1) {
171                                 gwvpmini_fourZeroThree();
172                                 return;
173                         }
174                 }
175         }
176         
177         // if its a write, we push for authentication
178         
179         //if($write) {
180         if(!$person) {
181                 $person = "anonymous";
182         }
183         
184         // if its a write, we check (before and after) the branch/tag info to see if they were updated
185         if($write) {
186                 error_log("REQUESTINBACKEND: processed as write");
187         } else {
188                 error_log("REQUESTINBACKEND: processed as read");
189         }
190         
191         gwvpmini_callGitBackend($person, $repo);
192         
193         //if($write) {
194                 //}
195         return;
196         //}
197
198         // if we made it this far, we a read and we have permissions to do so, just search the file from the repo
199         /*if(file_exists("$repo_base/$repo.git/$newloc")) {
200                 // error_log("would ask $repo for $repo.git/$newloc from $repo_base/$repo.git/$newloc");
201                 $fh = fopen("$repo_base/$repo.git/$newloc", "rb");
202                 
203                 // error_log("pushing file");
204                 while(!feof($fh)) {
205                         echo fread($fh, 8192);
206                 }
207         } else {
208                 // error_log("would ask $repo for $repo/$newloc from $repo_base/$repo/$newloc, NE");
209                 gwvpmini_fourZeroFour();
210                 return;
211         }*/
212         
213 }
214
215 function gwvpmini_canManageRepo($userid, $repoid)
216 {
217         // only the owner or an admin can do these tasks
218         // error_log("Checking repoid, $repoid against userid $userid");
219         
220         if(gwvpmini_IsUserAdmin(null, null, $userid)) return true;
221         if(gwvpmini_IsRepoOwner($userid, $repoid)) return true;
222         return false;
223 }
224
225
226 // TODO: this whole bit needs a re-write
227 function gwvpmini_callGitBackend($username, $repo)
228 {
229         // this is where things become a nightmare
230                 $fh   = fopen('php://input', "r");
231                 
232                 $repo_base = gwvpmini_getConfigVal("repodir");\r
233                 
234                 
235                 $ruri = $_SERVER["REQUEST_URI"];
236                 $strrem = "git/$repo.git";
237                 $euri = str_replace($strrem, "", $_REQUEST["q"]);
238                 //$euri = preg_replace("/^git\/$repo\.git/", "", $_REQUEST["q"]);
239                 
240                 
241                 
242                 $rmeth = $_SERVER["REQUEST_METHOD"];
243                 
244                 $qs = "";
245                 foreach($_REQUEST as $key => $var) {
246                         if($key != "q") {
247                                 //// error_log("adding, $var from $key");
248                                 if($qs == "") $qs.="$key=$var";
249                                 else $qs.="&$key=$var";
250                         }
251                 }
252                 
253                 //sleep(2);
254                 
255                 $userdets = gwvpmini_getUser($username);
256                 
257                 // this is where the fun, it ends.
258                 $myoutput = "";
259                 unset($myoutput);
260                 
261                 // this be nasty!
262                 
263                 // setup env
264                 if(isset($procenv))     unset($procenv);
265                 $procenv["GATEWAY_INTERFACE"] = "CGI/1.1";
266                 $procenv["PATH_TRANSLATED"] = "/$repo_base/$repo.git/$euri";
267                 $procenv["REQUEST_METHOD"] = "$rmeth";
268                 $procenv["GIT_COMMITTER_NAME"] = $userdets["fullname"];
269                 $procenv["GIT_COMMITTER_EMAIL"] = $userdets["email"];
270                 $procenv["GIT_HTTP_EXPORT_ALL"] = "1";
271                 $procenv["QUERY_STRING"] = "$qs";
272                 $procenv["HTTP_USER_AGENT"] = "git/1.7.1";
273                 $procenv["REMOTE_USER"] = "$username";
274                 $procenv["REMOTE_ADDR"] = $_SERVER["REMOTE_ADDR"];
275                 $procenv["AUTH_TYPE"] = "Basic";
276                 
277                 //// error_log("PROCENV: ".print_r($procenv,true));
278                 
279                 if(isset($_SERVER["CONTENT_TYPE"])) { 
280                         $procenv["CONTENT_TYPE"] = $_SERVER["CONTENT_TYPE"];
281                 } else {
282                         //$procenv["CONTENT_TYPE"] = "";
283                 }
284                 if(isset($_SERVER["CONTENT_LENGTH"])) { 
285                         $procenv["CONTENT_LENGTH"] = $_SERVER["CONTENT_LENGTH"];
286                 }
287
288                 $headers = getallheaders();
289                 
290                 error_log("path trans'd is /$repo_base/$repo.git/$euri from $ruri with ".$_REQUEST["q"]." $strrem pre is ".print_r($_REQUEST,true)." and foff ".print_r($headers, true));
291                 
292                 $pwd = "/$repo_base/";
293                 
294                 $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);
295                 
296                 $untilblank = false;
297                 while(!$untilblank&&!feof($pipes[1])) {
298                         $lines_t = fgets($pipes[1]);
299                         $lines = trim($lines_t);
300                         // error_log("got line: $lines");
301                         if($lines_t == "\r\n") {
302                                 $untilblank = true;
303                                 // error_log("now blank");
304                         } else header($lines);
305                         if($lines === false) {
306                                 // error_log("got an unexpexted exit...");
307                                 exit(0);
308                         }
309                         
310                 }
311                 
312
313                 $firstline = true;
314                 $continue = true;
315                 
316                 if(!stream_set_blocking($fh,0)) {
317                         // error_log("cant set input non-blocking");
318                 }
319
320                 if(!stream_set_blocking($pipes[1],0)) {
321                         // error_log("cant set pipe1 non-blocking");
322                 }
323                 
324                 
325                 $stlimit = 0;
326                 $fp = fopen("/tmp/gitup.".rand(0,4000000), "w");
327                 $from_client_data = "";
328                 // i was going to use stream_select, but i feel this works better like this
329                 while($continue) {
330                         // do client
331                         
332                         // lets start again....
333                                 
334                         if(!feof($fh)) {
335                                 if(isset($headers["Content-Length"])) {
336                                         $cl = $headers["Content-Length"];
337                                         while(strlen($from_client_data) < $cl) {
338                                                 error_log("re-read ".strlen($from_client_data));
339                                                 $from_client_data .= fread($fh, $cl);
340                                         }
341                                 } else  $from_client_data = fread($fh,8192);
342                                 
343                                 // TODO: BIG TODO: must rewrite this bit. its ugly as sin, it works, but it probably shouldnt.
344                                 
345                                 if(isset($headers["Content-Encoding"])) {
346                                         if($headers["Content-Encoding"] == "gzip") {
347                                                 //error_log("DAM YOU GIT CLIENT and your retarded gzip encoding");
348                                                 $from_client_data = gzinflate(substr($from_client_data, 10));
349                                                 //$from_client_data = gzdecode($from_client_data);
350                                         }
351                                 }
352                                 if($from_client_data !== false) {
353                                         fwrite($pipes[0], $from_client_data);
354                                         fwrite($fp, $from_client_data);
355                                 }
356                                 fflush($pipes[0]);
357                                 //fwrite($fl, $from_client_data);
358                                 $client_len = strlen($from_client_data);
359                         } else {
360                                 error_log("client end");
361                                 $client_len = 0;
362                                 //$continue = false;
363                         }
364                         
365                                 
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                                         error_log("send to client");
395                                         echo $from_cgi_data;
396                                         flush();
397                                 }
398                                 $cgi_len = strlen($from_cgi_data);
399                         } else {
400                                 // error_log("cgi end");
401                                 $cgi_len = 0;
402                         }
403                         
404                         flush();
405                         
406                         if(feof($pipes[1])) $continue = false;
407                         else {
408                                 if($client_len == 0 && $cgi_len == 0) {
409                                         usleep(200000);
410                                         error_log("sleep tick");
411                                         $stlimit++;
412                                         if($stlimit > 5000) $continue = false;
413                                 } else {
414                                         $stlimit = 0;
415                                         error_log("sizes: $client_len, $cgi_len");
416                                         if($cgi_len > 0) {
417                                                 //error_log("from cgi: \"$from_cgi_data\"");
418                                         }
419                                 }
420                         }
421                         
422                 }
423                 
424                 
425                 flush();
426                 error_log("and im done...");
427                 
428                 //fclose($fl);
429                 fclose($fh);
430                 fclose($pipes[1]);
431                 fclose($pipes[0]);      
432                 
433                 exit(0);
434 }
435
436
437
438 function gwvpmini_repoExists($name)
439 {
440         $repo_base = gwvpmini_getConfigVal("repodir");
441         
442         if(file_exists("$repo_base/$name.git")) return true;
443         else return false;
444 }
445
446 // default perms:
447 // 0 - anyone can clone/read, only owner can write
448 // 1 - noone can clone/read, repo is visible (i.e. name), only owner can read/write repo
449 // 2 - only owner can see anything
450 function gwvpmini_createGitRepo($name, $ownerid, $desc, $defperms, $clonefrom, $isremoteclone)
451 {
452         global $cmd_line_tool;
453         
454         $repo_base = gwvpmini_getConfigVal("repodir");
455         
456         if($clonefrom !== false) {
457                 error_log("how did i end up in clonefrom? $clonefrom");
458                 if(!$isremoteclone) {
459                         exec("/usr/bin/git clone --bare $repo_base/$clonefrom.git $repo_base/$name.git >> /tmp/gitlog 2>&1");
460                         gwvpmini_AddRepo($name, $desc, $ownerid, $defperms, $clonefrom);
461                 } else {
462                         // we do this from an outside call in the background
463                         $cmd = "/usr/bin/php $cmd_line_tool $clonefrom $name backgroundclone >> /tmp/gitlog 2>&1 &";
464                         error_log("cmd called as $cmd");
465                         exec($cmd);
466                         gwvpmini_AddRepo($name, $desc, $ownerid, $defperms, $clonefrom);
467                         $rn = gwvpmini_getRepo(null, $name, null);
468                         $rid = $rn["id"];
469                         gwvpmini_SetRepoCloning($rid);
470                         gwvpmini_SendMessage("info", "Background clone initiated for $name ($rid) from $clonefrom... your repo will be available once the background clone is finished");
471                         return false;
472                 }
473         } else {
474         
475         // phew, this works, but i tell you this - bundles arent quite as nice as they should be
476         // error_log("would create $repo_base/$name.git");
477                 exec("/usr/bin/git init $repo_base/$name.git --bare >> /tmp/gitlog 2>&1");
478                 chdir("$repo_base/$name.git");
479                 exec("/usr/bin/git update-server-info");
480         
481                 // gwvpmini_AddRepo($reponame, $repodesc, $repoowner, $defaultperms = 0)
482                 gwvpmini_AddRepo($name, $desc, $ownerid, $defperms, $clonefrom);
483         }
484         
485         return true;
486 }
487
488 function gzdecode($data,&$filename='',&$error='',$maxlength=null)\r
489 {\r
490         $len = strlen($data);\r
491         if ($len < 18 || strcmp(substr($data,0,2),"\x1f\x8b")) {\r
492                 $error = "Not in GZIP format.";\r
493                 return null;  // Not GZIP format (See RFC 1952)\r
494         }\r
495         $method = ord(substr($data,2,1));  // Compression method\r
496         $flags  = ord(substr($data,3,1));  // Flags\r
497         if ($flags & 31 != $flags) {\r
498                 $error = "Reserved bits not allowed.";\r
499                 return null;\r
500         }\r
501         // NOTE: $mtime may be negative (PHP integer limitations)\r
502         $mtime = unpack("V", substr($data,4,4));\r
503         $mtime = $mtime[1];\r
504         $xfl   = substr($data,8,1);\r
505         $os    = substr($data,8,1);\r
506         $headerlen = 10;\r
507         $extralen  = 0;\r
508         $extra     = "";\r
509         if ($flags & 4) {\r
510                 // 2-byte length prefixed EXTRA data in header\r
511                 if ($len - $headerlen - 2 < 8) {\r
512                         return false;  // invalid\r
513                 }\r
514                 $extralen = unpack("v",substr($data,8,2));\r
515                 $extralen = $extralen[1];\r
516                 if ($len - $headerlen - 2 - $extralen < 8) {\r
517                         return false;  // invalid\r
518                 }\r
519                 $extra = substr($data,10,$extralen);\r
520                 $headerlen += 2 + $extralen;\r
521         }\r
522         $filenamelen = 0;\r
523         $filename = "";\r
524         if ($flags & 8) {\r
525                 // C-style string\r
526                 if ($len - $headerlen - 1 < 8) {\r
527                         return false; // invalid\r
528                 }\r
529                 $filenamelen = strpos(substr($data,$headerlen),chr(0));\r
530                 if ($filenamelen === false || $len - $headerlen - $filenamelen - 1 < 8) {\r
531                         return false; // invalid\r
532                 }\r
533                 $filename = substr($data,$headerlen,$filenamelen);\r
534                 $headerlen += $filenamelen + 1;\r
535         }\r
536         $commentlen = 0;\r
537         $comment = "";\r
538         if ($flags & 16) {\r
539                 // C-style string COMMENT data in header\r
540                 if ($len - $headerlen - 1 < 8) {\r
541                         return false;    // invalid\r
542                 }\r
543                 $commentlen = strpos(substr($data,$headerlen),chr(0));\r
544                 if ($commentlen === false || $len - $headerlen - $commentlen - 1 < 8) {\r
545                         return false;    // Invalid header format\r
546                 }\r
547                 $comment = substr($data,$headerlen,$commentlen);\r
548                 $headerlen += $commentlen + 1;\r
549         }\r
550         $headercrc = "";\r
551         if ($flags & 2) {\r
552                 // 2-bytes (lowest order) of CRC32 on header present\r
553                 if ($len - $headerlen - 2 < 8) {\r
554                         return false;    // invalid\r
555                 }\r
556                 $calccrc = crc32(substr($data,0,$headerlen)) & 0xffff;\r
557                 $headercrc = unpack("v", substr($data,$headerlen,2));\r
558                 $headercrc = $headercrc[1];\r
559                 if ($headercrc != $calccrc) {\r
560                         $error = "Header checksum failed.";\r
561                         return false;    // Bad header CRC\r
562                 }\r
563                 $headerlen += 2;\r
564         }\r
565         // GZIP FOOTER\r
566         $datacrc = unpack("V",substr($data,-8,4));\r
567         $datacrc = sprintf('%u',$datacrc[1] & 0xFFFFFFFF);\r
568         $isize = unpack("V",substr($data,-4));\r
569         $isize = $isize[1];\r
570         // decompression:\r
571         $bodylen = $len-$headerlen-8;\r
572         if ($bodylen < 1) {\r
573                 // IMPLEMENTATION BUG!\r
574                 return null;\r
575         }\r
576         $body = substr($data,$headerlen,$bodylen);\r
577         $data = "";\r
578         if ($bodylen > 0) {\r
579                 switch ($method) {\r
580                         case 8:\r
581                                 // Currently the only supported compression method:\r
582                                 $data = gzinflate($body,$maxlength);\r
583                                 break;\r
584                         default:\r
585                                 $error = "Unknown compression method.";\r
586                                 return false;\r
587                 }\r
588         }  // zero-byte body content is allowed\r
589         // Verifiy CRC32\r
590         $crc   = sprintf("%u",crc32($data));\r
591         $crcOK = $crc == $datacrc;\r
592         $lenOK = $isize == strlen($data);\r
593         if (!$lenOK || !$crcOK) {\r
594                 $error = ( $lenOK ? '' : 'Length check FAILED. ') . ( $crcOK ? '' : 'Checksum FAILED.');\r
595                 return false;\r
596         }\r
597         return $data;\r
598 }
599 ?>