66aabb405278eaada606adb2017a23956ee18e69
[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");\r
70         
71         
72         $repo_base = gwvpmini_getConfigVal("repodir");
73         
74         // TODO: we need to stop passing the repo name around as "repo.git", it needs to be just "repo"
75         
76         
77         /* bizare git problem that ignores 403's or continues on with a push despite them 
78         // error_log("FLAP for ".$_SERVER["REQUEST_URI"]);
79         if(isset($_REQUEST)) {
80                 $dump = print_r($_REQUEST, true);
81                 // error_log("FLAP, $dump");
82         }
83         if(isset($_SERVER["PHP_AUTH_USER"])) {
84                 // error_log("FLAP: donut hole");
85         }*/
86         
87         error_log("REQUESTINBACKEND: ".print_r($_REQUEST, true));
88         
89         $repo = "";
90         $repoid = false;
91         $newloc = "/";
92         if(isset($_REQUEST["q"])) {
93                 $query = $_REQUEST["q"];
94                 $qspl = explode("/", $query);
95                 // TODO do this with 
96                 $repo = preg_replace("/\.git$/", "", $qspl[1]);
97                 $repoid = gwvpmini_GetRepoId($repo);
98                 for($i=2; $i < count($qspl); $i++) {
99                         $newloc .= "/".$qspl[$i];
100                 }
101         }
102         
103         if($repoid == false) {
104                 gwvpmini_fourZeroFour();
105                 return;
106         }
107         
108         // we do an update server cause its weird and i cant figure out when it actually needs to happen
109         chdir("$repo_base/$repo.git");
110         // dont believe i have to do this
111         //exec("/usr/bin/git update-server-info");
112         
113         if(!file_exists("$repo_base/$repo.git/hooks/pre-receive") || !file_exists("$repo_base/$repo.git/hooks/update")) {
114                 // error_log("WRITING HOOKS");
115                 gwvpmini_CreateRepoHooks("$repo_base/$repo.git", $cmd_line_tool, $repo);
116         }
117         
118         
119         // so now we have the repo
120         // next we determine if this is a read or a write
121         
122         // TODO: WE NEED TO FIX THIS, IT DOESNT ALWAYS DETECT a "WRITE"
123         $write = false;
124         if(isset($_REQUEST["service"])) {
125                 if($_REQUEST["service"] == "git-receive-pack") {
126                         // error_log("got write as receivepack in post");
127                         $write = true;
128                 }
129         }
130         if(preg_match("/.*git-receive-pack$/", $_REQUEST["q"])) $write = true;
131         //$write = true;
132         // 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
133         // no, this isnt a solution cause auth'd read attempts will come up as writes...
134         //if(isset($_SERVER["PHP_AUTH_USER"])) {
135                 //$write = true;
136         //}
137         
138         
139         $person = gwvpmini_checkBasicAuthLogin();
140         //$write = true;
141         // next, figure out permissions for repo
142         $rid = gwvpmini_GetRepoId($repo);
143         $uid = -1;
144         // error_log("AT THIS POINT WE HAVE $uid, $rid, $repo $person");
145         
146         if(!$person) {
147                 if($write) {
148                         // error_log("ASK FOR BASIC AUTH");
149                         gwvpmini_AskForBasicAuth();
150                         return;
151                 } else {
152                         $perm = gwvpmini_GetRepoPerm($rid, "a");
153                         if($perm < 1) {
154                                 // error_log("ASK FOR BASIC AUTH 2");
155                                 gwvpmini_AskForBasicAuth();
156                                 return;
157                         }
158                 }
159         } else {
160                 $uid = gwvpmini_GetUserId($person);
161                 $perm = gwvpmini_GetRepoPerm($rid, $uid);
162                 if($write) {
163                         if($perm < 2) {
164                                 // error_log("SEND FOFF");
165                                 gwvpmini_fourZeroThree();
166                                 return;
167                         }
168                 } else {
169                         if($perm < 1) {
170                                 gwvpmini_fourZeroThree();
171                                 return;
172                         }
173                 }
174         }
175         
176         // if its a write, we push for authentication
177         
178         //if($write) {
179         if(!$person) {
180                 $person = "anonymous";
181         }
182         
183         // if its a write, we check (before and after) the branch/tag info to see if they were updated
184         if($write) {
185                 error_log("REQUESTINBACKEND: processed as write");
186         } else {
187                 error_log("REQUESTINBACKEND: processed as read");
188         }
189         
190         gwvpmini_callGitBackend($person, $repo);
191         
192         //if($write) {
193                 //}
194         return;
195         //}
196
197         // if we made it this far, we a read and we have permissions to do so, just search the file from the repo
198         /*if(file_exists("$repo_base/$repo.git/$newloc")) {
199                 // error_log("would ask $repo for $repo.git/$newloc from $repo_base/$repo.git/$newloc");
200                 $fh = fopen("$repo_base/$repo.git/$newloc", "rb");
201                 
202                 // error_log("pushing file");
203                 while(!feof($fh)) {
204                         echo fread($fh, 8192);
205                 }
206         } else {
207                 // error_log("would ask $repo for $repo/$newloc from $repo_base/$repo/$newloc, NE");
208                 gwvpmini_fourZeroFour();
209                 return;
210         }*/
211         
212 }
213
214 function gwvpmini_canManageRepo($userid, $repoid)
215 {
216         // only the owner or an admin can do these tasks
217         // error_log("Checking repoid, $repoid against userid $userid");
218         
219         if(gwvpmini_IsUserAdmin(null, null, $userid)) return true;
220         if(gwvpmini_IsRepoOwner($userid, $repoid)) return true;
221         return false;
222 }
223
224 function gwvpmini_callGitBackend($username, $repo)
225 {
226         // this is where things become a nightmare
227                 $fh   = fopen('php://input', "r");
228                 
229                 $repo_base = gwvpmini_getConfigVal("repodir");\r
230                 
231                 
232                 $ruri = $_SERVER["REQUEST_URI"];
233                 $strrem = "git/$repo.git";
234                 $euri = str_replace($strrem, "", $_REQUEST["q"]);
235                 //$euri = preg_replace("/^git\/$repo\.git/", "", $_REQUEST["q"]);
236                 
237                 
238                 
239                 $rmeth = $_SERVER["REQUEST_METHOD"];
240                 
241                 $qs = "";
242                 foreach($_REQUEST as $key => $var) {
243                         if($key != "q") {
244                                 //// error_log("adding, $var from $key");
245                                 if($qs == "") $qs.="$key=$var";
246                                 else $qs.="&$key=$var";
247                         }
248                 }
249                 
250                 //sleep(2);
251                 
252                 $userdets = gwvpmini_getUser($username);
253                 
254                 // this is where the fun, it ends.
255                 $myoutput = "";
256                 unset($myoutput);
257                 
258                 // this be nasty!
259                 
260                 // setup env
261                 if(isset($procenv))     unset($procenv);
262                 $procenv["GATEWAY_INTERFACE"] = "CGI/1.1";
263                 $procenv["PATH_TRANSLATED"] = "/$repo_base/$repo.git/$euri";
264                 $procenv["REQUEST_METHOD"] = "$rmeth";
265                 $procenv["GIT_COMMITTER_NAME"] = $userdets["fullname"];
266                 $procenv["GIT_COMMITTER_EMAIL"] = $userdets["email"];
267                 $procenv["GIT_HTTP_EXPORT_ALL"] = "1";
268                 $procenv["QUERY_STRING"] = "$qs";
269                 $procenv["HTTP_USER_AGENT"] = "git/1.7.1";
270                 $procenv["REMOTE_USER"] = "$username";
271                 $procenv["REMOTE_ADDR"] = $_SERVER["REMOTE_ADDR"];
272                 $procenv["AUTH_TYPE"] = "Basic";
273                 
274                 //// error_log("PROCENV: ".print_r($procenv,true));
275                 
276                 if(isset($_SERVER["CONTENT_TYPE"])) { 
277                         $procenv["CONTENT_TYPE"] = $_SERVER["CONTENT_TYPE"];
278                 } else {
279                         //$procenv["CONTENT_TYPE"] = "";
280                 }
281                 if(isset($_SERVER["CONTENT_LENGTH"])) { 
282                         $procenv["CONTENT_LENGTH"] = $_SERVER["CONTENT_LENGTH"];
283                 }
284                 
285                 // error_log("path trans'd is /$repo_base/$repo.git/$euri from $ruri with ".$_REQUEST["q"]." $strrem");
286                 
287                 
288                 
289
290                 $pwd = "/$repo_base/";
291                 
292                 $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);
293                 
294                 $untilblank = false;
295                 while(!$untilblank&&!feof($pipes[1])) {
296                         $lines_t = fgets($pipes[1]);
297                         $lines = trim($lines_t);
298                         // error_log("got line: $lines");
299                         if($lines_t == "\r\n") {
300                                 $untilblank = true;
301                                 // error_log("now blank");
302                         } else header($lines);
303                         if($lines === false) {
304                                 // error_log("got an unexpexted exit...");
305                                 exit(0);
306                         }
307                         
308                 }
309                 
310
311                 $firstline = true;
312                 $continue = true;
313                 
314                 if(!stream_set_blocking($fh,0)) {
315                         // error_log("cant set input non-blocking");
316                 }
317
318                 if(!stream_set_blocking($pipes[1],0)) {
319                         // error_log("cant set pipe1 non-blocking");
320                 }
321                 
322                 
323                 $stlimit = 0;
324                 $fp = fopen("/tmp/gitup.".rand(0,4000000), "w");
325                 // i was going to use stream_select, but i feel this works better like this
326                 while($continue) {
327                         // do client
328                         if(!feof($fh)) {
329                                 $from_client_data = fread($fh,8192);
330                                 if($from_client_data !== false) {
331                                         fwrite($pipes[0], $from_client_data);
332                                         fwrite($fp, $from_client_data);
333                                 }
334                                 fflush($pipes[0]);
335                                 //fwrite($fl, $from_client_data);
336                                 $client_len = strlen($from_client_data);
337                         } else {
338                                 // error_log("client end");
339                                 $client_len = 0;
340                                 //$continue = false;
341                         }
342                         
343                         // do cgi
344                         // sometimes, we get a \r\n from the cgi, i do not know why she swallowed the fly,
345                         // but i do know that the fgets for the headers above should have comsued that
346                         if(!feof($pipes[1])) {
347                                 $from_cgi_data_t = fread($pipes[1],8192);
348                                 $from_cgi_data = $from_cgi_data_t;
349                                 
350                                 // i dont know if this will solve it... it coudl cause some serious issues elsewhere
351                                 // TODO: this is a hack, i need to know why the fgets above doesn consume the \r\n even tho it reads it
352                                 // i.e. why the pointer doesnt increment over it, cause the freads above then get them again.
353                                 if($firstline) {
354                                         if(strlen($from_cgi_data_t)>0) {
355                                                 // i dont get why this happens, and its very frustrating.. im not sure if its a bug in php
356                                                 // or something the git-http-backend thing is doing..
357                                                 // TODO: find out why this happens
358                                                 $from_cgi_data = preg_replace("/^\r\n/", "", $from_cgi_data_t);
359                                                 if(strlen($from_cgi_data)!=strlen($from_cgi_data_t)) {
360                                                         // error_log("MOOOKS - we did trunc");
361                                                 } else {
362                                                         // error_log("MOOOKS - we did not trunc");
363                                                 }
364                                                 $firstline = false;
365                                         }
366                                 }
367                                 
368                                 if($from_cgi_data !== false) {
369                                         echo $from_cgi_data;
370                                         flush();
371                                 }
372                                 $cgi_len = strlen($from_cgi_data);
373                         } else {
374                                 // error_log("cgi end");
375                                 $cgi_len = 0;
376                         }
377                         
378                         if(feof($pipes[1])) $continue = false;
379                         else {
380                                 if($client_len == 0 && $cgi_len == 0) {
381                                         usleep(200000);
382                                         // error_log("sleep tick");
383                                         $stlimit++;
384                                         if($stlimit > 50) $continue = false;
385                                 } else {
386                                         $stlimit = 0;
387                                         // error_log("sizes: $client_len, $cgi_len");
388                                         if($cgi_len > 0) {
389                                                 // error_log("from cgi: \"$from_cgi_data\"");
390                                         }
391                                 }
392                         }
393                         
394                 }
395                 
396                 
397                 //fclose($fl);
398                 fclose($fh);
399                 fclose($pipes[1]);
400                 fclose($pipes[0]);      
401 }
402
403
404
405 function gwvpmini_repoExists($name)
406 {
407         $repo_base = gwvpmini_getConfigVal("repodir");
408         
409         if(file_exists("$repo_base/$name.git")) return true;
410         else return false;
411 }
412
413 // default perms:
414 // 0 - anyone can clone/read, only owner can write
415 // 1 - noone can clone/read, repo is visible (i.e. name), only owner can read/write repo
416 // 2 - only owner can see anything
417 function gwvpmini_createGitRepo($name, $ownerid, $desc, $defperms, $clonefrom, $isremoteclone)
418 {
419         global $cmd_line_tool;
420         
421         $repo_base = gwvpmini_getConfigVal("repodir");
422         
423         if($clonefrom !== false) {
424                 error_log("how did i end up in clonefrom? $clonefrom");
425                 if(!$isremoteclone) {
426                         exec("/usr/bin/git clone --bare $repo_base/$clonefrom.git $repo_base/$name.git >> /tmp/gitlog 2>&1");
427                         gwvpmini_AddRepo($name, $desc, $ownerid, $defperms, $clonefrom);
428                 } else {
429                         // we do this from an outside call in the background
430                         $cmd = "/usr/bin/php $cmd_line_tool $clonefrom $name backgroundclone >> /tmp/gitlog 2>&1 &";
431                         error_log("cmd called as $cmd");
432                         exec($cmd);
433                         gwvpmini_AddRepo($name, $desc, $ownerid, $defperms, $clonefrom);
434                         $rn = gwvpmini_getRepo(null, $name, null);
435                         $rid = $rn["id"];
436                         gwvpmini_SetRepoCloning($rid);
437                         gwvpmini_SendMessage("info", "Background clone initiated for $name ($rid) from $clonefrom... your repo will be available once the background clone is finished");
438                         return false;
439                 }
440         } else {
441         
442         // phew, this works, but i tell you this - bundles arent quite as nice as they should be
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         
448                 // gwvpmini_AddRepo($reponame, $repodesc, $repoowner, $defaultperms = 0)
449                 gwvpmini_AddRepo($name, $desc, $ownerid, $defperms, $clonefrom);
450         }
451         
452         return true;
453 }
454
455
456 ?>