4cb53b844e944b366bb4fa689dae9b7082b4cdd7
[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)
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 .= "php $cmdpath pre-receive ";
38         $script .= '$START $END $REF'."\n\n";
39         fwrite($fp, $script);
40         
41         fclose($fp);
42         
43         chmod("$repopath/hooks/pre-receive", 0755);
44
45
46         $fp = fopen("$repopath/hooks/update", "w");
47         
48         if(!$fp) // error_log("could not create update hook");
49         
50         // TODO: think about this one
51         $script = "#!/bin/bash\n\n";
52         $script .= "php $cmdpath update ";
53         $script .= '$1 $2 $3'."\n\n";
54         fwrite($fp, $script);
55         
56         fclose($fp);
57         
58         chmod("$repopath/hooks/update", 0755);
59 }
60
61 function gwvpmini_gitBackendInterface()
62 {
63         // and this is where i re-code the git backend interface from scratch
64         global $BASE_URL, $cmd_line_tool;
65         
66         header_remove("Pragma");\r
67         header_remove("Cache-Control");\r
68         header_remove("Set-Cookie");\r
69         header_remove("Expires");\r
70         header_remove("X-Powered-By");\r
71         header_remove("Vary");\r
72         
73         
74         $repo_base = gwvpmini_getConfigVal("repodir");
75         
76         // TODO: we need to stop passing the repo name around as "repo.git", it needs to be just "repo"
77         
78         
79         /* bizare git problem that ignores 403's or continues on with a push despite them 
80         // error_log("FLAP for ".$_SERVER["REQUEST_URI"]);
81         if(isset($_REQUEST)) {
82                 $dump = print_r($_REQUEST, true);
83                 // error_log("FLAP, $dump");
84         }
85         if(isset($_SERVER["PHP_AUTH_USER"])) {
86                 // error_log("FLAP: donut hole");
87         }*/
88         
89
90         
91         $repo = "";
92         $repoid = false;
93         $newloc = "/";
94         if(isset($_REQUEST["q"])) {
95                 $query = $_REQUEST["q"];
96                 $qspl = explode("/", $query);
97                 // TODO do this with 
98                 $repo = preg_replace("/\.git$/", "", $qspl[1]);
99                 $repoid = gwvpmini_GetRepoId($repo);
100                 for($i=2; $i < count($qspl); $i++) {
101                         $newloc .= "/".$qspl[$i];
102                 }
103         }
104         
105         if($repoid == false) {
106                 gwvpmini_fourZeroFour();
107                 return;
108         }
109         
110         // we do an update server cause its weird and i cant figure out when it actually needs to happen
111         chdir("$repo_base/$repo.git");
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);
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         
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         //}
187         
188         gwvpmini_callGitBackend($person, $repo);
189         
190         //if($write) {
191                 //}
192         return;
193         //}
194
195         // if we made it this far, we a read and we have permissions to do so, just search the file from the repo
196         /*if(file_exists("$repo_base/$repo.git/$newloc")) {
197                 // error_log("would ask $repo for $repo.git/$newloc from $repo_base/$repo.git/$newloc");
198                 $fh = fopen("$repo_base/$repo.git/$newloc", "rb");
199                 
200                 // error_log("pushing file");
201                 while(!feof($fh)) {
202                         echo fread($fh, 8192);
203                 }
204         } else {
205                 // error_log("would ask $repo for $repo/$newloc from $repo_base/$repo/$newloc, NE");
206                 gwvpmini_fourZeroFour();
207                 return;
208         }*/
209         
210 }
211
212 function gwvpmini_canManageRepo($userid, $repoid)
213 {
214         // only the owner or an admin can do these tasks
215         // error_log("Checking repoid, $repoid against userid $userid");
216         
217         if(gwvpmini_IsUserAdmin(null, null, $userid)) return true;
218         if(gwvpmini_IsRepoOwner($userid, $repoid)) return true;
219         return false;
220 }
221
222 function gwvpmini_callGitBackend($username, $repo)
223 {
224         // this is where things become a nightmare
225                 $fh   = fopen('php://input', "r");
226                 
227                 $repo_base = gwvpmini_getConfigVal("repodir");\r
228                 
229                 
230                 $ruri = $_SERVER["REQUEST_URI"];
231                 $strrem = "git/$repo.git";
232                 $euri = str_replace($strrem, "", $_REQUEST["q"]);
233                 //$euri = preg_replace("/^git\/$repo\.git/", "", $_REQUEST["q"]);
234                 
235                 
236                 
237                 $rmeth = $_SERVER["REQUEST_METHOD"];
238                 
239                 $qs = "";
240                 foreach($_REQUEST as $key => $var) {
241                         if($key != "q") {
242                                 //// error_log("adding, $var from $key");
243                                 if($qs == "") $qs.="$key=$var";
244                                 else $qs.="&$key=$var";
245                         }
246                 }
247                 
248                 //sleep(2);
249                 
250                 $userdets = gwvpmini_getUser($username);
251                 
252                 // this is where the fun, it ends.
253                 $myoutput = "";
254                 unset($myoutput);
255                 
256                 // this be nasty!
257                 
258                 // setup env
259                 if(isset($procenv))     unset($procenv);
260                 $procenv["GATEWAY_INTERFACE"] = "CGI/1.1";
261                 $procenv["PATH_TRANSLATED"] = "/$repo_base/$repo.git/$euri";
262                 $procenv["REQUEST_METHOD"] = "$rmeth";
263                 $procenv["GIT_COMMITTER_NAME"] = $userdets["fullname"];
264                 $procenv["GIT_COMMITTER_EMAIL"] = $userdets["email"];
265                 $procenv["GIT_HTTP_EXPORT_ALL"] = "1";
266                 $procenv["QUERY_STRING"] = "$qs";
267                 $procenv["HTTP_USER_AGENT"] = "git/1.7.1";
268                 $procenv["REMOTE_USER"] = "$username";
269                 $procenv["REMOTE_ADDR"] = $_SERVER["REMOTE_ADDR"];
270                 $procenv["AUTH_TYPE"] = "Basic";
271                 
272                 //// error_log("PROCENV: ".print_r($procenv,true));
273                 
274                 if(isset($_SERVER["CONTENT_TYPE"])) { 
275                         $procenv["CONTENT_TYPE"] = $_SERVER["CONTENT_TYPE"];
276                 } else {
277                         //$procenv["CONTENT_TYPE"] = "";
278                 }
279                 if(isset($_SERVER["CONTENT_LENGTH"])) { 
280                         $procenv["CONTENT_LENGTH"] = $_SERVER["CONTENT_LENGTH"];
281                 }
282                 
283                 // error_log("path trans'd is /$repo_base/$repo.git/$euri from $ruri with ".$_REQUEST["q"]." $strrem");
284                 
285                 
286                 
287
288                 $pwd = "/$repo_base/";
289                 
290                 $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);
291                 
292                 $untilblank = false;
293                 while(!$untilblank&&!feof($pipes[1])) {
294                         $lines_t = fgets($pipes[1]);
295                         $lines = trim($lines_t);
296                         // error_log("got line: $lines");
297                         if($lines_t == "\r\n") {
298                                 $untilblank = true;
299                                 // error_log("now blank");
300                         } else header($lines);
301                         if($lines === false) {
302                                 // error_log("got an unexpexted exit...");
303                                 exit(0);
304                         }
305                         
306                 }
307                 
308
309                 $firstline = true;
310                 $continue = true;
311                 
312                 if(!stream_set_blocking($fh,0)) {
313                         // error_log("cant set input non-blocking");
314                 }
315
316                 if(!stream_set_blocking($pipes[1],0)) {
317                         // error_log("cant set pipe1 non-blocking");
318                 }
319                 
320                 
321                 $stlimit = 0;
322                 $fp = fopen("/tmp/gitup.".rand(0,4000000), "w");
323                 // i was going to use stream_select, but i feel this works better like this
324                 while($continue) {
325                         // do client
326                         if(!feof($fh)) {
327                                 $from_client_data = fread($fh,8192);
328                                 if($from_client_data !== false) {
329                                         fwrite($pipes[0], $from_client_data);
330                                         fwrite($fp, $from_client_data);
331                                 }
332                                 fflush($pipes[0]);
333                                 //fwrite($fl, $from_client_data);
334                                 $client_len = strlen($from_client_data);
335                         } else {
336                                 // error_log("client end");
337                                 $client_len = 0;
338                                 //$continue = false;
339                         }
340                         
341                         // do cgi
342                         // sometimes, we get a \r\n from the cgi, i do not know why she swallowed the fly,
343                         // but i do know that the fgets for the headers above should have comsued that
344                         if(!feof($pipes[1])) {
345                                 $from_cgi_data_t = fread($pipes[1],8192);
346                                 $from_cgi_data = $from_cgi_data_t;
347                                 
348                                 // i dont know if this will solve it... it coudl cause some serious issues elsewhere
349                                 // TODO: this is a hack, i need to know why the fgets above doesn consume the \r\n even tho it reads it
350                                 // i.e. why the pointer doesnt increment over it, cause the freads above then get them again.
351                                 if($firstline) {
352                                         if(strlen($from_cgi_data_t)>0) {
353                                                 // i dont get why this happens, and its very frustrating.. im not sure if its a bug in php
354                                                 // or something the git-http-backend thing is doing..
355                                                 // TODO: find out why this happens
356                                                 $from_cgi_data = preg_replace("/^\r\n/", "", $from_cgi_data_t);
357                                                 if(strlen($from_cgi_data)!=strlen($from_cgi_data_t)) {
358                                                         // error_log("MOOOKS - we did trunc");
359                                                 } else {
360                                                         // error_log("MOOOKS - we did not trunc");
361                                                 }
362                                                 $firstline = false;
363                                         }
364                                 }
365                                 
366                                 if($from_cgi_data !== false) {
367                                         echo $from_cgi_data;
368                                         flush();
369                                 }
370                                 $cgi_len = strlen($from_cgi_data);
371                         } else {
372                                 // error_log("cgi end");
373                                 $cgi_len = 0;
374                         }
375                         
376                         if(feof($pipes[1])) $continue = false;
377                         else {
378                                 if($client_len == 0 && $cgi_len == 0) {
379                                         usleep(200000);
380                                         // error_log("sleep tick");
381                                         $stlimit++;
382                                         if($stlimit > 2) $continue = false;
383                                 } else {
384                                         $stlimit = 0;
385                                         // error_log("sizes: $client_len, $cgi_len");
386                                         if($cgi_len > 0) {
387                                                 // error_log("from cgi: \"$from_cgi_data\"");
388                                         }
389                                 }
390                         }
391                         
392                 }
393                 
394                 
395                 //fclose($fl);
396                 fclose($fh);
397                 fclose($pipes[1]);
398                 fclose($pipes[0]);      
399 }
400
401
402
403 function gwvpmini_repoExists($name)
404 {
405         $repo_base = gwvpmini_getConfigVal("repodir");
406         
407         if(file_exists("$repo_base/$name.git")) return true;
408         else return false;
409 }
410
411 // default perms:
412 // 0 - anyone can clone/read, only owner can write
413 // 1 - noone can clone/read, repo is visible (i.e. name), only owner can read/write repo
414 // 2 - only owner can see anything
415 function gwvpmini_createGitRepo($name, $ownerid, $desc)
416 {
417         $repo_base = gwvpmini_getConfigVal("repodir");
418         
419         // phew, this works, but i tell you this - bundles arent quite as nice as they should be
420         // error_log("would create $repo_base/$name.git");
421         exec("/usr/bin/git init $repo_base/$name.git --bare > /tmp/gitlog 2>&1");
422         chdir("$repo_base/$name.git");
423         exec("/usr/bin/git update-server-info");
424
425         // gwvpmini_AddRepo($reponame, $repodesc, $repoowner, $defaultperms = 0)
426         gwvpmini_AddRepo($name, $desc, $ownerid);
427         
428         return true;
429 }
430
431
432 ?>