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");
7 function upstreamRequest(unify) {
8 // first do a head request
9 console.log("upsteram as ", unify.requestFor);
14 if(unify.topPath !=null) if(unify.topPath != "") if(typeof global.repoproxy.repo[unify.topPath] != "undefined") {
15 var uplink = global.repoproxy.repo[unify.topPath].url;
16 xpath = uplink + unify.subPath;
19 //unify.b.write("would send to '" + xpath + "'");
22 // not doing this properly yet...
23 if(typeof global.repoproxy.downloads[unify.fullFilePath] != undefined && global.repoproxy.downloads[unify.fullFilePath] == 1) {
24 console.log("request for file thats being downloaded already, doing inline request");
29 console.log("sending off to '%s'", xpath);
31 var headReq = url.parse(xpath);
32 headReq["method"] = "HEAD";
34 getup = http.request(headReq, function(res) {
35 //res.setEncoding("utf8");
38 console.log("status code is ", typeof res.statusCode);
39 switch(res.statusCode) {
40 // TODO: this 301 directory redirect thing needs to work better
44 var loc = res.headers.location.substr(res.headers.location.length-4);
45 var against_t = xpath + "/";
46 var against = against_t.substr(against_t.length-4);
49 console.log("got a redirect, upstream for loc => loc/ assuming its a directory");
51 unify.b.writeHead(302, { "Location": unify.originalReq + "/" });
53 console.log("checked '%s' against '%s', was false, sending 404", loc, against);
54 unify.b.writeHead(404, {"Content-Type": "text/plain"});
55 unify.b.write("404 Not Found\n");
62 unify.b.writeHead(404, {"Content-Type": "text/plain"});
63 unify.b.write("404 Not Found\n");
69 if(unify.isDirectoryRequest) {
70 serviceDirectory(unify);
73 // this is where it gets ugly
74 var filesize = res.headers["content-length"];
75 console.log("do ugly write: ", unify);
76 //unify.b.write(data);
77 var metafilename = unify.fullPathDirName + "/.meta."+ path.basename(unify.requestFor) +".filesize";
78 var metafile = fs.createWriteStream(metafilename);
79 metafile.write(filesize);
81 getAndService(unify, xpath, filesize);
86 console.log(".... data");
87 //unify.b.write(data);
90 //console.log("res is now ", res);
95 //console.log("getup: ", getup);
98 exports.upstreamRequest = upstreamRequest;
100 function getAndService(unify, xpath, filesize) {
102 console.log("calling in here with filesize, ", filesize)
103 unify.b.writeHead(200, {'Content-Length' : filesize});
106 global.repoproxy.downloads[unify.fullFilePath] = 1;
109 http.get(xpath, function(res) {
111 var file = fs.createWriteStream(unify.fullFilePath);
113 //console.log("res: ", res);
115 //res.setEncoding("utf8");
117 res.on("data", function(data) {
118 //console.log("chunk");
123 res.on("end", function() {
124 console.log("end...");
127 global.repoproxy.downloads[unify.fullFilePath] = 0;
130 res.on("error", function(err) {
131 console.log("res threw error... ", err);
136 // this is nasty nasty thing that can go horribly wrong in some ways, but currently works...
137 function inlineService(unify) {
138 // this method is called when we need to service a file thats being downloaded by something else
139 var metafilename = unify.fullPathDirName + "/.meta."+ path.basename(unify.requestFor) +".filesize";
140 var fsizef = fs.createReadStream(metafilename);
143 fsizef.on("data", function(data) {
147 fsizef.on("end", function() {
149 unify.b.writeHead(200, {"Content-Length" : fsize });
151 // now we go into the file reading loop.
152 console.log("start of inline services");
153 // we loop every 0.5s and do our thing
155 function sendPieces() {
156 // this is going to be so fun i want to play real life frogger in real life traffic...
157 fs.stat(unify.fullFilePath, function(err, stats) {
159 if(stats["size"] > sentSoFar) {
160 // if file size changed between last chunk and this chunk, send the chunks
163 // open the file, send the data
164 var rs = fs.createReadStream(unify.fullFilePath, {start: sentSoFar, end: stats["size"]});
166 rs.on("data", function(thisdata) {
167 //console.log("inline chunk: ", thisdata.length);
168 unify.b.write(thisdata);
171 rs.on("end", function() {
172 sentSoFar = stats["size"];
173 // every second, we start again
174 if(sentSoFar != fsize) {
175 setTimeout(sendPieces, 1000);
182 // if file size did not change between last timeout and this one, incremement the chunk counter
183 // if we reach 60, we had a problem, and so we bomb out
187 // we bombed out somehow
191 setTimeout(sendPieces, 1000);
195 console.log("inline service - we're in a very bad place");
201 setTimeout(sendPieces, 100);
205 // the service file routine .... PLEASE KILL ME!
206 function serviceFile(unify) {
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
213 checkFile(unify, function() {
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) {
222 inp.on("end", function(closed) {
228 exports.serviceFile = serviceFile;
231 function checkFile(unify, callback) {
232 // in here we do the metadata checks
233 var metafilename = unify.fullPathDirName + "/.meta."+ path.basename(unify.requestFor) +".filesize";
235 fs.exists(metafilename, function(existence) {
237 var fsizef = fs.createReadStream(metafilename);
239 fsizef.on("data", function(data) {
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 console.log("reported filesizes dont match, '%s', '%s', removing file and starting again", rfsize, stats["size"]);
250 fs.unlink(metafilename, function(){
251 fs.unlink(unify.fullFilePath, function(){
252 upstreamRequest(unify);
256 upstreamRequest(unify);
260 unify.b.writeHead(200, {"Content-Length" : unify.fileSize})
266 console.log("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})
273 function makeCacheDir(path) {
274 console.log("attempting to create... '%s' as '%s'", path.fullPathDirName, path.subPathDirName);
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 console.log("attempt mkdir on '%s'", startAt);
282 fs.mkdirSync(startAt);
284 //console.log("e in mkdir, ", e);
290 function serviceDirectory(unify) {
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 console.log("doing directory listing on: ", unify.fullFilePath);
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]);
305 if(files[i].match(/^\..*/) == null) {
306 if(stats.isDirectory()) {
308 res.write("Directory: <a href=\""+files[i]+"/\">"+files[i]+"/</a>\n");
310 } else if(stats.isFile()) {
311 var padlength = 80 - (files[i].length) - stats.size.toString().length;
314 padding = new Array(padlength).join(" ");
316 res.write("File: <a href=\""+files[i]+"\">"+files[i]+"</a>"+padding+stats.size+" bytes\n");
320 console.log("ignoring file, ", files[i]);
324 if(nfiles == 0) res.write("Empty directory....\n");
326 res.write("<hr></pre>");
329 res.write("we have entered bizaro world...\n");
336 function moveToCleanup(file_or_dir) {
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;
343 //console.log("Moving %s to %s for cleanup", file_or_dir.replace(/\/$/, ""), toloc);
345 fs.renameSync(file_or_dir.replace(/\/$/, ""), toloc);
348 function cleanupRoutine() {
353 exports.serviceDirectory = serviceDirectory;
354 exports.moveToCleanup = moveToCleanup;