fixing multiple / in paths
[nodejs-repoproxy.git] / lib / cache.js
1 var fs = require("fs");
2 var http = require("http");
3 var url = require("url");
4 var path = require("path");
5 var crypto = require("crypto");
6 var log = require("./log.js");
7
8 function upstreamRequest(unify) {
9         // first do a head request
10         log.debug("upsteram as ", unify.requestFor);
11         
12         var endData = false;
13         var xpath = "";
14         var filefd = null;
15         if(unify.topPath !=null) if(unify.topPath != "") if(typeof global.repoproxy.repo[unify.topPath] != "undefined") {
16                 var uplink = global.repoproxy.repo[unify.topPath].url;
17                 xpath = uplink + unify.subPath;
18         }
19         
20         //unify.b.write("would send to '" + xpath + "'");
21         //unify.b.end();
22         
23         // not doing this properly yet...
24         if(typeof global.repoproxy.downloads[unify.fullFilePath] != undefined && global.repoproxy.downloads[unify.fullFilePath] == 1) {
25                 log.debug("request for file thats being downloaded already, doing inline request");
26                 inlineService(unify);
27                 return;
28         }
29         
30         log.debug("sending off to '%s'", xpath);
31         
32         var headReq = url.parse(xpath);
33         headReq["method"] = "HEAD";
34         
35         getup = http.request(headReq, function(res) {
36                 //res.setEncoding("utf8");
37                 
38                 if(!endData) {
39                         log.debug("status code is ", typeof res.statusCode);
40                         switch(res.statusCode) {
41                         // TODO: this 301 directory redirect thing needs to work better
42                         case 301:
43                         case 302:
44                                 
45                                 var loc = res.headers.location.substr(res.headers.location.length-4);
46                                 var against_t = xpath + "/";
47                                 var against = against_t.substr(against_t.length-4);
48                                 
49                                 if(loc == against) {
50                                         log.debug("got a redirect, upstream for loc => loc/ assuming its a directory");
51                                         makeCacheDir(unify);
52                                         unify.b.writeHead(302, { "Location": unify.originalReq + "/" });
53                                 } else {
54                                         log.debug("checked '%s' against '%s', was false, sending 404", loc, against);
55                                         unify.b.writeHead(404, {"Content-Type": "text/plain"});
56                                         unify.b.write("404 Not Found\n");
57                                 }
58                                 unify.b.end();
59                                 endData = true;
60                                 break;
61                                 
62                         case 404:
63                                 unify.b.writeHead(404, {"Content-Type": "text/plain"});
64                                 unify.b.write("404 Not Found\n");
65                                 unify.b.end();
66                                 endData = true;
67                                 break;
68                         case 200:
69                                 makeCacheDir(unify);
70                                 if(unify.isDirectoryRequest) {
71                                         serviceDirectory(unify);                                        
72                                         endData = true;
73                                 } else {
74                                         // this is where it gets ugly
75                                         var filesize = res.headers["content-length"];
76                                         log.debug("do ugly write: ", unify);
77                                         //unify.b.write(data);
78                                         var metafilename = unify.fullPathDirName + "/.meta."+ path.basename(unify.requestFor) +".filesize";
79                                         var metafile = fs.createWriteStream(metafilename);
80                                         metafile.write(filesize);
81                                         metafile.end();
82                                         getAndService(unify, xpath, filesize);
83                                         
84                                 }
85                                 break;
86                         default:
87                                 log.debug(".... data");
88                                 //unify.b.write(data);
89                         }
90                 }               
91                 //log.debug("res is now ", res);
92         });
93         
94         getup.end();
95         
96         //log.debug("getup: ", getup);
97 }
98
99 exports.upstreamRequest = upstreamRequest;
100
101 function getAndService(unify, xpath, filesize) {
102         
103         log.debug("calling in here with filesize, ", filesize)
104         unify.b.writeHead(200, {'Content-Length' : filesize});
105
106         global.repoproxy.downloads[unify.fullFilePath] = 1;
107         
108         http.get(xpath, function(res) {
109
110             var file = fs.createWriteStream(unify.fullFilePath);
111         
112             //log.debug("res: ", res);
113         
114             //res.setEncoding("utf8");
115         
116             res.on("data", function(data) {
117                     //log.debug("chunk");
118                     file.write(data);
119                     unify.b.write(data);
120             });
121         
122             res.on("end", function() {
123                     log.debug("end...");
124                     unify.b.end();
125                     file.end();
126                     global.repoproxy.downloads[unify.fullFilePath] = 0;
127             });
128             
129             res.on("error", function(err) {
130                 log.debug("res threw error... ", err);
131             });
132         });
133 }
134
135 // this is nasty nasty thing that can go horribly wrong in some ways, but currently works...
136 function inlineService(unify) {
137         // this method is called when we need to service a file thats being downloaded by something else
138         var metafilename = unify.fullPathDirName + "/.meta."+ path.basename(unify.requestFor) +".filesize";
139         var fsizef = fs.createReadStream(metafilename);
140         var fsize = "";
141         var lastchunk = 0;
142         fsizef.on("data", function(data) {
143                 fsize += data;
144         });
145         
146         fsizef.on("end", function() {
147                 var sentSoFar = 0;
148                 unify.b.writeHead(200, {"Content-Length" : fsize });
149                 
150                 // now we go into the file reading loop.
151                 log.debug("start of inline services");
152                 // we loop every 0.5s and do our thing
153                 
154                 function sendPieces() {
155                         // this is going to be so fun i want to play real life frogger in real life traffic...
156                         fs.stat(unify.fullFilePath, function(err, stats) {
157                                 if(err == null) {
158                                         if(stats["size"] > sentSoFar) {
159                                                 // if file size changed between last chunk and this chunk, send the chunks
160                                                 
161                                                 lastChunk = 0;
162                                                 // open the file, send the data
163                                                 var rs = fs.createReadStream(unify.fullFilePath, {start: sentSoFar, end: stats["size"]});
164                                                 
165                                                 rs.on("data", function(thisdata) {
166                                                         //log.debug("inline chunk: ", thisdata.length);
167                                                         unify.b.write(thisdata);
168                                                 });
169                                                 
170                                                 rs.on("end", function() {
171                                                         sentSoFar = stats["size"];
172                                                         // every second, we start again
173                                                         if(sentSoFar != fsize) {
174                                                                 setTimeout(sendPieces, 1000);
175                                                         } else {
176                                                                 // we're done!
177                                                                 unify.b.end();
178                                                         }
179                                                 });
180                                         } else {
181                                                 // if file size did not change between last timeout and this one, incremement the chunk counter
182                                                 // if we reach 60, we had a problem, and so we bomb out
183                                                 
184                                                 lastChunk++;
185                                                 
186                                                 // we bombed out somehow
187                                                 if(lastChunk > 60) {
188                                                         unify.b.end();
189                                                 } else {
190                                                         setTimeout(sendPieces, 1000);
191                                                 }
192                                         }
193                                 } else {
194                                         log.error("inline service - we're in a very bad place, how we ended up here we dont know, but we need to crash");
195                                         process.exit(10);
196                                 }
197                         });
198                         
199                 }
200                 
201                 setTimeout(sendPieces, 100);
202         });
203 }
204
205 // the service file routine .... PLEASE KILL ME!
206 function serviceFile(unify) {
207         
208         // for now, ignore range.
209         // however we need to check if a metadata file exists describing the filesize, check if its all correct
210         // and if not, erase the file (and metafile) and forward the request back to upstream request
211
212         
213         checkFile(unify, function() {
214                 
215                 // file should already exist, so we just poop it out
216                 var inp = fs.createReadStream(unify.fullFilePath);
217                 //inp.setEncoding("utf8");
218                 inp.on("data", function(data) {
219                         unify.b.write(data);
220                 });
221                 
222                 inp.on("end", function(closed) {
223                         unify.b.end();
224                 });
225         });
226 }
227
228 exports.serviceFile = serviceFile;
229
230
231 function checkFile(unify, callback) {
232         // in here we do the metadata checks
233         var metafilename = unify.fullPathDirName + "/.meta."+ path.basename(unify.requestFor) +".filesize";
234         
235         fs.exists(metafilename, function(existence) {
236                 if(existence) {
237                         var fsizef = fs.createReadStream(metafilename);
238                         var fsize = "";
239                         fsizef.on("data", function(data) {
240                                 fsize += data;
241                         });
242                         
243                         fsizef.on("end", function() {
244                                 fs.stat(unify.fullFilePath, function(err, stats) {
245                                         var rfsize = stats["size"];
246                                         if(rfsize != fsize.trim()) {
247                                                 // remove the file and start again
248                                                 log.debug("reported filesizes dont match, '%s', '%s', removing file and starting again", rfsize, stats["size"]);
249                                                 try {
250                                                         fs.unlink(metafilename, function(){
251                                                                 fs.unlink(unify.fullFilePath, function(){
252                                                                         upstreamRequest(unify);                                                 
253                                                                 })
254                                                         });
255                                                 } catch(e) {
256                                                         upstreamRequest(unify);
257                                                 }
258                                         } else {
259                                                 // we're good
260                                                 unify.b.writeHead(200, {"Content-Length" : unify.fileSize})
261                                                 callback();
262                                         }
263                                 });
264                         });
265                 } else {
266                         log.debug("file, '%s' exists but has no filesize meta data, assuming it was put here manually and servicing", unify.fullFilePath);
267                         unify.b.writeHead(200, {"Content-Length" : unify.fileSize})
268                         callback();
269                 }
270         });
271 }
272
273 function makeCacheDir(path) {
274         log.debug("attempting to create... '%s' as '%s'", path.fullPathDirName, path.subPathDirName);
275         
276         var startAt = path.topFullPath;
277         var nextbits = path.subPathDirName.split("/");
278         for(var i=0; i < nextbits.length; i++) {
279                 startAt += "/" + nextbits[i];
280                 log.debug("attempt mkdir on '%s'", startAt);
281                 try {
282                         fs.mkdirSync(startAt);
283                 } catch(e) {
284                         //log.debug("e in mkdir, ", e);
285                 }
286         }
287         //process.exit(0);
288 }
289
290 function serviceDirectory(unify) {
291         var nfiles = 0;
292         var res = unify.b;
293         
294         res.write("<html><h1>Directory listing for " + unify.originalReq + "</h1><hr><pre>");
295         if(unify.originalReq != "/") res.write("<a href=\"..\">Parent</a>\n\n");
296         fs.readdir(unify.fullFilePath, function(err, files) {
297                 log.debug("doing directory listing on: ", unify.fullFilePath);
298                 if(err == null) {
299                         
300                         // TODO: make this work asynchronously...
301                         for(var i=0; i<files.length; i++) {
302                                 // avoiding statSync is too hard for now, will fix later TODO: fix this sync bit
303                                 var stats = fs.statSync(unify.fullFilePath+"/"+files[i]);
304                                 
305                                 if(files[i].match(/^\..*/) == null) {
306                                         if(stats.isDirectory()) {
307                                                 
308                                                 res.write("Directory: <a href=\""+files[i]+"/\">"+files[i]+"/</a>\n");
309                                                 nfiles++;
310                                         } else if(stats.isFile()) {
311                                                 var padlength = 80 - (files[i].length) - stats.size.toString().length;
312                                                 var padding = "";
313                                                 if(padlength > 0) {
314                                                         padding = new Array(padlength).join(" ");
315                                                 }
316                                                 res.write("File:      <a href=\""+files[i]+"\">"+files[i]+"</a>"+padding+stats.size+" bytes\n");
317                                                 nfiles++;
318                                         }
319                                 } else {
320                                         log.debug("ignoring file, ", files[i]);
321                                 }
322                         }
323                         
324                         if(nfiles == 0) res.write("Empty directory....\n");
325                         
326                         res.write("<hr></pre>");
327                         res.end();
328                 } else {
329                         res.write("we have entered bizaro world...\n");
330                         res.write("</pre>");
331                         res.end();
332                 }
333         });
334 }
335
336 function moveToCleanup(file_or_dir) {
337         // err..?
338         var cleanup = global.repoproxy.cacheDir + "/.cleanup";
339         var ctime = new Date().getTime();
340         var encoded = (++global.repoproxy.fileid).toString();
341         var toloc = cleanup + "/" + ctime.toString() + "." + encoded;
342         
343         //log.debug("Moving %s to %s for cleanup", file_or_dir.replace(/\/$/, ""), toloc);
344         
345         fs.renameSync(file_or_dir.replace(/\/$/, ""), toloc);
346 }
347
348
349 exports.serviceDirectory = serviceDirectory;
350 exports.moveToCleanup = moveToCleanup;