1 var fs = require("fs");
2 var http = require("http");
3 var url = require("url");
4 var path = require("path");
6 function maintainCache() {
7 // TODO i should check that im already running here and exit if i am
8 console.log("Cache maintainence routine starting...");
9 console.log("Cache maintainence routine ended...");
12 exports.startTimer = function() {
13 // our once-a-day cache maintainer
14 var cacheTimer = global.repoproxy.scancache*3600*1000;
15 //var cacheTimer = global.repoproxy.scancache*100;
16 setInterval(maintainCache, cacheTimer);
19 function upstreamRequest(unify) {
20 // first do a head request
21 console.log("upsteram as ", unify.requestFor);
26 if(unify.topPath !=null) if(unify.topPath != "") if(typeof global.repoproxy.repo[unify.topPath] != "undefined") {
27 var uplink = global.repoproxy.repo[unify.topPath].url;
28 xpath = uplink + unify.subPath;
31 //unify.b.write("would send to '" + xpath + "'");
34 // not doing this properly yet...
35 if(typeof global.repoproxy.downloads[unify.fullFilePath] != undefined && global.repoproxy.downloads[unify.fullFilePath] == 1) {
36 console.log("request for file thats being downloaded already, doing inline request");
41 console.log("sending off to '%s'", xpath);
43 var headReq = url.parse(xpath);
44 headReq["method"] = "HEAD";
46 getup = http.request(headReq, function(res) {
47 //res.setEncoding("utf8");
50 console.log("status code is ", typeof res.statusCode);
51 switch(res.statusCode) {
52 // TODO: this 301 directory redirect thing needs to work better
56 var loc = res.headers.location.substr(res.headers.location.length-4);
57 var against_t = xpath + "/";
58 var against = against_t.substr(against_t.length-4);
61 console.log("got a redirect, upstream for loc => loc/ assuming its a directory");
63 unify.b.writeHead(302, { "Location": unify.originalReq + "/" });
65 console.log("checked '%s' against '%s', was false, sending 404", loc, against);
66 unify.b.writeHead(404, {"Content-Type": "text/plain"});
67 unify.b.write("404 Not Found\n");
74 unify.b.writeHead(404, {"Content-Type": "text/plain"});
75 unify.b.write("404 Not Found\n");
81 if(unify.isDirectoryRequest) {
82 serviceDirectory(unify);
85 // this is where it gets ugly
86 var filesize = res.headers["content-length"];
87 console.log("do ugly write: ", unify);
88 //unify.b.write(data);
89 var metafilename = unify.fullPathDirName + "/.meta."+ path.basename(unify.requestFor) +".filesize";
90 var metafile = fs.createWriteStream(metafilename);
91 metafile.write(filesize);
93 getAndService(unify, xpath, filesize);
98 console.log(".... data");
99 //unify.b.write(data);
102 //console.log("res is now ", res);
107 //console.log("getup: ", getup);
110 exports.upstreamRequest = upstreamRequest;
112 function getAndService(unify, xpath, filesize) {
114 console.log("calling in here with filesize, ", filesize)
115 unify.b.writeHead(200, {'Content-Length' : filesize});
118 global.repoproxy.downloads[unify.fullFilePath] = 1;
121 http.get(xpath, function(res) {
123 var file = fs.createWriteStream(unify.fullFilePath);
125 //console.log("res: ", res);
127 //res.setEncoding("utf8");
129 res.on("data", function(data) {
130 //console.log("chunk");
135 res.on("end", function() {
136 console.log("end...");
139 global.repoproxy.downloads[unify.fullFilePath] = 0;
142 res.on("error", function(err) {
143 console.log("res threw error... ", err);
148 // this is nasty nasty thing that can go horribly wrong in some ways, but currently works...
149 function inlineService(unify) {
150 // this method is called when we need to service a file thats being downloaded by something else
151 var metafilename = unify.fullPathDirName + "/.meta."+ path.basename(unify.requestFor) +".filesize";
152 var fsizef = fs.createReadStream(metafilename);
154 fsizef.on("data", function(data) {
158 fsizef.on("end", function() {
160 unify.b.writeHead(200, {"Content-Length" : fsize });
162 // now we go into the file reading loop.
163 console.log("start of inline services");
164 // we loop every 0.5s and do our thing
166 function sendPieces() {
167 // this is going to be so fun i want to play real life frogger in real life traffic...
168 fs.stat(unify.fullFilePath, function(err, stats) {
170 if(stats["size"] > sentSoFar) {
171 // open the file, send the data
172 var rs = fs.createReadStream(unify.fullFilePath, {start: sentSoFar, end: stats["size"]});
174 rs.on("data", function(thisdata) {
175 //console.log("inline chunk: ", thisdata.length);
176 unify.b.write(thisdata);
179 rs.on("end", function() {
180 sentSoFar = stats["size"];
181 // every second, we start again
182 if(sentSoFar != fsize) {
183 setTimeout(sendPieces, 1000);
191 console.log("inline service - we're in a very bad place");
197 setTimeout(sendPieces, 100);
201 // the service file routine .... PLEASE KILL ME!
202 function serviceFile(unify) {
204 // for now, ignore range.
205 // however we need to check if a metadata file exists describing the filesize, check if its all correct
206 // and if not, erase the file (and metafile) and forward the request back to upstream request
209 checkFile(unify, function() {
211 // file should already exist, so we just poop it out
212 var inp = fs.createReadStream(unify.fullFilePath);
213 //inp.setEncoding("utf8");
214 inp.on("data", function(data) {
218 inp.on("end", function(closed) {
224 exports.serviceFile = serviceFile;
227 function checkFile(unify, callback) {
228 // in here we do the metadata checks
229 var metafilename = unify.fullPathDirName + "/.meta."+ path.basename(unify.requestFor) +".filesize";
231 fs.exists(metafilename, function(existence) {
233 var fsizef = fs.createReadStream(metafilename);
235 fsizef.on("data", function(data) {
239 fsizef.on("end", function() {
240 fs.stat(unify.fullFilePath, function(err, stats) {
241 var rfsize = stats["size"];
242 if(rfsize != fsize.trim()) {
243 // remove the file and start again
244 console.log("reported filesizes dont match, '%s', '%s', removing file and starting again", rfsize, stats["size"]);
246 fs.unlink(metafilename, function(){
247 fs.unlink(unify.fullFilePath, function(){
248 upstreamRequest(unify);
252 upstreamRequest(unify);
256 unify.b.writeHead(200, {"Content-Length" : unify.fileSize})
262 console.log("file, '%s' exists but has no filesize meta data, assuming it was put here manually and servicing", unify.fullFilePath);
263 unify.b.writeHead(200, {"Content-Length" : unify.fileSize})
269 function makeCacheDir(path) {
270 console.log("attempting to create... '%s' as '%s'", path.fullPathDirName, path.subPathDirName);
272 var startAt = path.topFullPath;
273 var nextbits = path.subPathDirName.split("/");
274 for(var i=0; i < nextbits.length; i++) {
275 startAt += "/" + nextbits[i];
276 console.log("attempt mkdir on '%s'", startAt);
278 fs.mkdirSync(startAt);
280 //console.log("e in mkdir, ", e);
286 function serviceDirectory(unify) {
290 res.write("<html><h1>Directory listing for " + unify.originalReq + "</h1><hr><pre>");
291 if(unify.originalReq != "/") res.write("<a href=\"..\">Parent</a>\n\n");
292 fs.readdir(unify.fullFilePath, function(err, files) {
293 console.log("doing directory listing on: ", unify.fullFilePath);
296 // TODO: make this work asynchronously...
297 for(var i=0; i<files.length; i++) {
298 // avoiding statSync is too hard for now, will fix later TODO: fix this sync bit
299 var stats = fs.statSync(unify.fullFilePath+"/"+files[i]);
301 if(files[i].match(/^\..*/) == null) {
302 if(stats.isDirectory()) {
304 res.write("Directory: <a href=\""+files[i]+"/\">"+files[i]+"/</a>\n");
306 } else if(stats.isFile()) {
307 var padlength = 80 - (files[i].length) - stats.size.toString().length;
310 padding = new Array(padlength).join(" ");
312 res.write("File: <a href=\""+files[i]+"\">"+files[i]+"</a>"+padding+stats.size+" bytes\n");
316 console.log("ignoring file, ", files[i]);
320 if(nfiles == 0) res.write("Empty directory....\n");
322 res.write("<hr></pre>");
325 res.write("we have entered bizaro world...\n");
332 exports.serviceDirectory = serviceDirectory;