-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp-server-static.js
More file actions
275 lines (245 loc) · 8.07 KB
/
http-server-static.js
File metadata and controls
275 lines (245 loc) · 8.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
// https://adrianmejia.com/building-a-node-js-static-file-server-files-over-http-using-es6/
const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path');
const open = require('open');
const portscanner = require('portscanner');
// Garmin Connect
const gc = require('./src/gc.js');
let gc_config = {};
try {
gc_config = JSON.parse(fs.readFileSync('./src/config.json', 'utf8'));
} catch {
gc_config = { downloadDir: "./../fitalyser/myactivities/"};
fs.writeFileSync(
'./src/config.json', JSON.stringify(gc_config), function(err) {
if(err) {console.log("Error by writing gc_config")}
});
}
try {
gc_config.maxLocalActivityId = parseInt(
fs.readFileSync(gc_config.downloadDir + "/maxLocalActivityId", 'utf8')
);
} catch {
gc_config.maxLocalActivityId = 0;
}
/*let config = {};
try {
config = require('./credentials.json');
} catch (e) {
config = require('./mycredentials.json');
}
const
username = config.username,
password = config.password;
*/
const debug = false; // true or false
const verboseLogin = true;
let
loginFlag = false,
loginInfo = {},
loginCounter = 0;
userinfo = {},
activitiesList = [];
//var port = process.argv[2] || 4001;
portscanner.findAPortNotInUse(3000, 3999, '127.0.0.1', function (error, port) {
console.log('AVAILABLE PORT AT: ' + port);
// you can pass the parameter in the command line. e.g. node static_server.js 3000
// maps file extention to MIME types
// full list can be found here: https://www.freeformatter.com/mime-types-list.html
const mimeType = {
'.ico': 'image/x-icon',
'.html': 'text/html',
'.js': 'text/javascript',
'.cjs': 'application/javascript',
'.json': 'application/json',
'.css': 'text/css',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.wav': 'audio/wav',
'.mp3': 'audio/mpeg',
'.svg': 'image/svg+xml',
'.pdf': 'application/pdf',
'.zip': 'application/zip',
'.doc': 'application/msword',
'.eot': 'application/vnd.ms-fontobject',
'.ttf': 'application/x-font-ttf'
};
//'.fit': 'application/octet-stream' // not needed. fit extension must be added as binary
var params = {};
var foo;
const parseParams = function (s) {
s.split("&").forEach(e => {
let d = e.split("=");
params[`${d[0]}`] = decodeURIComponent(`${d[1]}`);
})
};
http.createServer(function (req, res) {
console.log(`${req.method} ${req.url}`);
if (`${req.method}` === "POST") {
let data = '';
req.on('data', chunk => {
data += chunk;
})
req.on('end', () => {
//let params = JSON.parse(data);
//console.log(params);
//data = (data);
console.log("data: " + data);
params = {};
parseParams(data.slice(data.indexOf("?") + 1));
console.log("post params:")
console.log(params)
foo = params.foo || "";
if ((!loginFlag) && foo === "login") {
loginCounter++;
if (loginCounter === 1) {
console.log("start login ...")
var loginStatus;
if (debug) {
loginStatus = gc.loginTest(params.username, params.password, verboseLogin)
} else {
loginStatus = gc.login(params.username, params.password, verboseLogin)
}
loginStatus.then(r => {
console.log("... end login")
//console.log("resolve loginTest");
console.log(r);
loginFlag = true;
loginInfo = r;
//let t = JSON.stringify(r);
//res.end(t);
})
} else
console.log(" ... process login ...")
}
})
}
if (`${req.method}` === "GET") {
let a = req.url;
params = {};
parseParams(a.slice(a.indexOf("?") + 1));
console.log("get params:")
console.log(params)
}
// Garmin Connect functions
foo = params.foo || "";
if (foo.length > 0) {
console.log(" foo: " + foo);
if (foo === "status") {
let r = {
loginFlag: loginFlag,
};
if (loginFlag) {
if (loginInfo.login === "OK") {
r.config = gc_config;
} else {
r.error = loginInfo.error;
loginFlag = false;
loginInfo = {};
loginCounter = 0;
}
}
console.log(r);
let t = JSON.stringify(r);
res.end(t);
}
if (loginFlag) {
switch (foo) {
case "maxLocalActivityId":
let r = {text: "maxLocalActivityId is updated"};
fs.writeFileSync(
gc_config.downloadDir + "/maxLocalActivityId",
params.maxLocalActivityId, function(error) {
if(error) {
console.log("Error by writing: " + gc_config.downloadDir + "/maxLocalActivityId");
r.text = "Error at updating maxLocalActivityId. File is blocked ?"
}
});
let t = JSON.stringify(r);
res.end(t);
break;
case "userinfo":
if (debug) {
userinfo = gc.userinfoTest();
} else {
userinfo = gc.userinfo();
}
userinfo.then(r => {
console.log(r)
let t = JSON.stringify(r);
res.end(t);
})
break;
case "activitiesList":
activitiesList = gc.activitiesList(params.start_index, params.max_limit);
activitiesList.then(r => {
r.forEach(el => {
let id = el.activityId;
console.log("activityID: " + id);
});
let t = JSON.stringify(r);
res.end(t);
})
break;
case "downloadActivity":
//let downloadDir = "./";
// activitiesList mus be resolved
//let activity = activitiesList[0];
//console.log(params.downloadDir);
gc.downloadActivity(params.downloadDir, params.fileName, params.id)
.then(r => {
//console.log(r + " is downloaded")
console.log(r);
let t = JSON.stringify( { text: r } );
res.end(t);
});
break;
}
}
} else {
const parsedUrl = url.parse(req.url);
// extract URL path
// Avoid https://en.wikipedia.org/wiki/Directory_traversal_attack
// e.g curl --path-as-is http://localhost:9000/../fileInDanger.txt
// by limiting the path to current directory only
const sanitizePath = path.normalize(parsedUrl.pathname).replace(/^(\.\.[\/\\])+/, '');
let pathname = path.join(__dirname, sanitizePath);
//console.log("before: " + pathname);
pathname = pathname.replace(/LevelUp/g, '/../');
//console.log("after:" + pathname);
// the simplest, nο sanitizePath. does not work ?
//let pathname = path.join(__dirname, parsedUrl.pathname);
//dirty way
//if (path.parse(pathname).ext === ".fit")
// pathname = path.join(__dirname, '..', '..', sanitizePath);
fs.exists(pathname, function (exist) {
if (!exist) {
// if the file is not found, return 404
res.statusCode = 404;
res.end(`File ${pathname} not found!`);
return;
}
// if is a directory, then look for index.html
if (fs.statSync(pathname).isDirectory()) {
pathname += './index.html';
}
// read file from file system
fs.readFile(pathname, function (err, data) {
if (err) {
res.statusCode = 500;
res.end(`Error getting the file: ${err}.`);
} else {
// based on the URL path, extract the file extention. e.g. .js, .doc, ...
const ext = path.parse(pathname).ext;
res.setHeader('Content-type', mimeType[ext] || 'text/plain');
res.end(data);
}
});
});
}
}).listen(parseInt(port));
console.log(`Server listening on port ${port}`);
open(`http://127.0.0.1:${port}/`)
})