1 var fs = require("fs");
2 var http = require("http");
3 var url = require("url");
4 var path = require("path");
6 function upstreamRequest(unify) {
7 // first do a head request
8 console.log("upsteram as ", unify.requestFor);
13 if(unify.topPath !=null) if(unify.topPath != "") if(typeof global.repoproxy.repo[unify.topPath] != "undefined") {
14 var uplink = global.repoproxy.repo[unify.topPath].url;
15 xpath = uplink + unify.subPath;
18 //unify.b.write("would send to '" + xpath + "'");
21 // not doing this properly yet...
22 if(typeof global.repoproxy.downloads[unify.fullFilePath] != undefined && global.repoproxy.downloads[unify.fullFilePath] == 1) {
23 console.log("request for file thats being downloaded already, doing inline request");
28 console.log("sending off to '%s'", xpath);
30 var headReq = url.parse(xpath);
31 headReq["method"] = "HEAD";
33 getup = http.request(headReq, function(res) {
34 //res.setEncoding("utf8");
37 console.log("status code is ", typeof res.statusCode);
38 switch(res.statusCode) {
39 // TODO: this 301 directory redirect thing needs to work better
43 var loc = res.headers.location.substr(res.headers.location.length-4);
44 var against_t = xpath + "/";
45 var against = against_t.substr(against_t.length-4);
48 console.log("got a redirect, upstream for loc => loc/ assuming its a directory");
50 unify.b.writeHead(302, { "Location": unify.originalReq + "/" });
52 console.log("checked '%s' against '%s', was false, sending 404", loc, against);
53 unify.b.writeHead(404, {"Content-Type": "text/plain"});
54 unify.b.write("404 Not Found\n");
61 unify.b.writeHead(404, {"Content-Type": "text/plain"});
62 unify.b.write("404 Not Found\n");
68 if(unify.isDirectoryRequest) {
69 serviceDirectory(unify);
72 // this is where it gets ugly
73 var filesize = res.headers["content-length"];
74 console.log("do ugly write: ", unify);
75 //unify.b.write(data);
76 var metafilename = unify.fullPathDirName + "/.meta."+ path.basename(unify.requestFor) +".filesize";
77 var metafile = fs.createWriteStream(metafilename);
78 metafile.write(filesize);
80 getAndService(unify, xpath, filesize);
85 console.log(".... data");
86 //unify.b.write(data);
89 //console.log("res is now ", res);
94 //console.log("getup: ", getup);
97 exports.upstreamRequest = upstreamRequest;
99 function getAndService(unify, xpath, filesize) {
101 console.log("calling in here with filesize, ", filesize)
102 unify.b.writeHead(200, {'Content-Length' : filesize});
105 global.repoproxy.downloads[unify.fullFilePath] = 1;
108 http.get(xpath, function(res) {
110 var file = fs.createWriteStream(unify.fullFilePath);
112 //console.log("res: ", res);
114 //res.setEncoding("utf8");
116 res.on("data", function(data) {
117 //console.log("chunk");
122 res.on("end", function() {
123 console.log("end...");
126 global.repoproxy.downloads[unify.fullFilePath] = 0;
129 res.on("error", function(err) {
130 console.log("res threw error... ", err);
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);
142 fsizef.on("data", function(data) {
146 fsizef.on("end", function() {
148 unify.b.writeHead(200, {"Content-Length" : fsize });
150 // now we go into the file reading loop.
151 console.log("start of inline services");
152 // we loop every 0.5s and do our thing
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) {
158 if(stats["size"] > sentSoFar) {
159 // if file size changed between last chunk and this chunk, send the chunks
162 // open the file, send the data
163 var rs = fs.createReadStream(unify.fullFilePath, {start: sentSoFar, end: stats["size"]});
165 rs.on("data", function(thisdata) {
166 //console.log("inline chunk: ", thisdata.length);
167 unify.b.write(thisdata);
170 rs.on("end", function() {
171 sentSoFar = stats["size"];
172 // every second, we start again
173 if(sentSoFar != fsize) {
174 setTimeout(sendPieces, 1000);
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
186 // we bombed out somehow
190 setTimeout(sendPieces, 1000);
194 console.log("inline service - we're in a very bad place");
200 setTimeout(sendPieces, 100);
204 // the service file routine .... PLEASE KILL ME!
205 function serviceFile(unify) {
207 // for now, ignore range.
208 // however we need to check if a metadata file exists describing the filesize, check if its all correct
209 // and if not, erase the file (and metafile) and forward the request back to upstream request
212 checkFile(unify, function() {
214 // file should already exist, so we just poop it out
215 var inp = fs.createReadStream(unify.fullFilePath);
216 //inp.setEncoding("utf8");
217 inp.on("data", function(data) {
221 inp.on("end", function(closed) {
227 exports.serviceFile = serviceFile;
230 function checkFile(unify, callback) {
231 // in here we do the metadata checks
232 var metafilename = unify.fullPathDirName + "/.meta."+ path.basename(unify.requestFor) +".filesize";
234 fs.exists(metafilename, function(existence) {
236 var fsizef = fs.createReadStream(metafilename);
238 fsizef.on("data", function(data) {
242 fsizef.on("end", function() {
243 fs.stat(unify.fullFilePath, function(err, stats) {
244 var rfsize = stats["size"];
245 if(rfsize != fsize.trim()) {
246 // remove the file and start again
247 console.log("reported filesizes dont match, '%s', '%s', removing file and starting again", rfsize, stats["size"]);
249 fs.unlink(metafilename, function(){
250 fs.unlink(unify.fullFilePath, function(){
251 upstreamRequest(unify);
255 upstreamRequest(unify);
259 unify.b.writeHead(200, {"Content-Length" : unify.fileSize})
265 console.log("file, '%s' exists but has no filesize meta data, assuming it was put here manually and servicing", unify.fullFilePath);
266 unify.b.writeHead(200, {"Content-Length" : unify.fileSize})
272 function makeCacheDir(path) {
273 console.log("attempting to create... '%s' as '%s'", path.fullPathDirName, path.subPathDirName);
275 var startAt = path.topFullPath;
276 var nextbits = path.subPathDirName.split("/");
277 for(var i=0; i < nextbits.length; i++) {
278 startAt += "/" + nextbits[i];
279 console.log("attempt mkdir on '%s'", startAt);
281 fs.mkdirSync(startAt);
283 //console.log("e in mkdir, ", e);
289 function serviceDirectory(unify) {
293 res.write("<html><h1>Directory listing for " + unify.originalReq + "</h1><hr><pre>");
294 if(unify.originalReq != "/") res.write("<a href=\"..\">Parent</a>\n\n");
295 fs.readdir(unify.fullFilePath, function(err, files) {
296 console.log("doing directory listing on: ", unify.fullFilePath);
299 // TODO: make this work asynchronously...
300 for(var i=0; i<files.length; i++) {
301 // avoiding statSync is too hard for now, will fix later TODO: fix this sync bit
302 var stats = fs.statSync(unify.fullFilePath+"/"+files[i]);
304 if(files[i].match(/^\..*/) == null) {
305 if(stats.isDirectory()) {
307 res.write("Directory: <a href=\""+files[i]+"/\">"+files[i]+"/</a>\n");
309 } else if(stats.isFile()) {
310 var padlength = 80 - (files[i].length) - stats.size.toString().length;
313 padding = new Array(padlength).join(" ");
315 res.write("File: <a href=\""+files[i]+"\">"+files[i]+"</a>"+padding+stats.size+" bytes\n");
319 console.log("ignoring file, ", files[i]);
323 if(nfiles == 0) res.write("Empty directory....\n");
325 res.write("<hr></pre>");
328 res.write("we have entered bizaro world...\n");
335 exports.serviceDirectory = serviceDirectory;