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