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