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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
|
use chrono::NaiveDateTime;
use git2::Commit;
use git2::FileMode;
use git2::ObjectType;
use git2::Oid;
use git2::Repository;
use git2::Tree;
use git2::TreeEntry;
use hyper::header;
use hyper::http::request::Parts;
use serde::Deserialize;
use sputnik::html_escape;
use sputnik::request::SputnikParts;
use std::str::from_utf8;
use crate::action_links;
use crate::controller::Controller;
use crate::diff::diff;
use crate::forms;
use crate::get_renderer;
use crate::ActionParam;
use crate::Context;
use crate::Error;
use crate::HyperResponse;
use crate::Page;
use crate::RenderMode;
use crate::Response;
pub(crate) fn get_blob<C: Controller>(
entr: TreeEntry,
params: ActionParam,
controller: &C,
ctx: Context,
parts: &Parts,
) -> Result<Response, Error> {
match params.action.as_ref() {
"view" => view_blob(entr, params, controller, ctx, parts),
"edit" => edit_blob(entr, params, controller, ctx, parts),
"upload" => Ok(forms::upload_form(true, controller, &ctx, parts).into()),
"log" => log_blob(entr, params, controller, ctx, parts),
"diff" => diff_blob(entr, params, controller, ctx, parts),
"raw" => raw_blob(entr, params, controller, ctx, parts).map(|r| r.into()),
"run" => run_blob(entr, params, controller, ctx, parts).map(|r| r.into()),
"move" => move_blob(entr, params, controller, ctx, parts),
"remove" => remove_blob(entr, params, controller, ctx, parts),
_ => Err(Error::BadRequest("unknown action".into())),
}
}
fn view_blob<C: Controller>(
entr: TreeEntry,
params: ActionParam,
controller: &C,
ctx: Context,
parts: &Parts,
) -> Result<Response, Error> {
let mut page = Page {
title: ctx.path.file_name().unwrap().to_owned(),
header: action_links(¶ms.action, controller, &ctx, parts),
..Default::default()
};
if let Some(access_info_html) = controller.access_info_html(&ctx, parts) {
page.body.push_str(&access_info_html);
}
if entr.filemode() == FileMode::Link.into() {
// TODO: indicate and link symbolic link
}
let blob = ctx.repo.find_blob(entr.id()).unwrap();
if let Some(mime) = mime_guess::from_path(&ctx.path).first() {
if mime.type_() == "image" {
page.body
.push_str("<div class=img-container><img src=?action=raw></div>");
return Ok(page.into());
}
}
match from_utf8(blob.content()) {
Ok(text) => {
if let Some(renderer) = get_renderer(&ctx.path) {
renderer(text, &mut page, RenderMode::View, &ctx);
} else {
page.body
.push_str(&format!("<pre>{}</pre>", html_escape(text)));
}
}
Err(_) => page.body.push_str("failed to decode file as UTF-8"),
}
Ok(page.into())
}
fn edit_blob<C: Controller>(
entr: TreeEntry,
_params: ActionParam,
controller: &C,
ctx: Context,
parts: &Parts,
) -> Result<Response, Error> {
if !controller.may_write_path(&ctx, parts) {
return Err(Error::Unauthorized(
"you are not authorized to edit this file".into(),
));
}
let blob = ctx.repo.find_blob(entr.id()).unwrap();
if let Ok(text) = from_utf8(blob.content()) {
Ok(forms::edit_text_form(
&forms::EditForm {
text: text.to_string(),
oid: Some(entr.id().to_string()),
..Default::default()
},
None,
controller,
&ctx,
parts,
)
.into())
} else {
Ok(forms::upload_form(true, controller, &ctx, parts).into())
}
}
fn log_blob<C: Controller>(
_entr: TreeEntry,
params: ActionParam,
controller: &C,
ctx: Context,
parts: &Parts,
) -> Result<Response, Error> {
let filename = ctx.path.file_name().unwrap();
let mut page = Page {
title: format!("Log for {}", filename),
header: action_links(¶ms.action, controller, &ctx, parts),
..Default::default()
};
let mut walk = ctx.repo.revwalk()?;
let branch_head = ctx.branch_head()?;
walk.push(branch_head.id())?;
let mut prev_commit = branch_head;
let mut prev_blobid = Some(prev_commit.tree()?.get_path(ctx.path.as_ref())?.id());
let mut commits = Vec::new();
// TODO: paginate
for oid in walk.flatten().skip(1) {
let commit = ctx.repo.find_commit(oid)?;
if let Ok(entr) = commit.tree()?.get_path(ctx.path.as_ref()) {
let blobid = entr.id();
if Some(blobid) != prev_blobid {
commits.push(prev_commit);
prev_blobid = Some(blobid);
}
prev_commit = commit;
} else {
if prev_blobid.is_some() {
commits.push(prev_commit);
}
prev_commit = commit;
prev_blobid = None;
}
}
if prev_commit.parent_count() == 0 && prev_commit.tree()?.get_path(ctx.path.as_ref()).is_ok() {
// the very first commit of the branch
commits.push(prev_commit);
}
page.body.push_str(
"<form><input type=hidden name=action value=diff>\
<button>Compare selected revisions</button>",
);
let mut prev_date = None;
for c in commits {
let date = NaiveDateTime::from_timestamp(c.time().seconds(), 0).date();
if Some(date) != prev_date {
if prev_date != None {
page.body.push_str("</ul>");
}
page.body.push_str(&format!(
"<h2 class=regular-text>{}</h2><ul class=rev-list>",
date.format("%b %d, %Y")
));
}
page.body.push_str(&format!(
"<li>\
<input type=radio name=oldid required value={0}>\
<input type=radio name=id required value={0}> ",
c.id().to_string()
));
page.body.push_str(&format!(
"<a href='?action=diff&id={}'>{}: {}</a></li>",
html_escape(c.id().to_string()),
html_escape(c.author().name().unwrap_or_default()),
html_escape(c.summary().unwrap_or_default()),
));
prev_date = Some(date);
}
page.body.push_str("</ul></form>");
Ok(page.into())
}
#[derive(Deserialize)]
struct DiffParams {
id: String,
oldid: Option<String>,
}
fn find_commit<'a>(repo: &'a Repository, id: &str, branch_head: &Oid) -> Option<Commit<'a>> {
let oid = Oid::from_str(id).ok()?;
repo.find_commit(oid)
.ok()
// disallow viewing commits from other branches you shouldn't have access to
.filter(|c| oid == *branch_head || repo.graph_descendant_of(*branch_head, c.id()).unwrap())
}
fn diff_blob<C: Controller>(
_entr: TreeEntry,
action_param: ActionParam,
controller: &C,
ctx: Context,
parts: &Parts,
) -> Result<Response, Error> {
let params: DiffParams = parts.query()?;
let branch_commit = ctx.branch_head()?;
let mut commit = find_commit(&ctx.repo, ¶ms.id, &branch_commit.id())
.ok_or_else(|| Error::NotFound("commit not found".into()))?;
let old_commit = if let Some(oldid) = ¶ms.oldid {
let other_commit = find_commit(&ctx.repo, &oldid, &branch_commit.id())
.ok_or_else(|| Error::NotFound("commit not found".into()))?;
if other_commit.time() > commit.time() {
// TODO: redirect instead
let c = commit;
commit = other_commit;
Some(c)
} else {
Some(other_commit)
}
} else {
// TODO: what if there are multiple parents?
commit.parents().next()
};
let blob_id = if let Ok(entry) = commit.tree()?.get_path(ctx.path.as_ref()) {
entry.id()
} else {
return Ok(Page {
title: format!("Commit for {}", ctx.path.file_name().unwrap()),
body: "file removed".into(),
header: action_links(&action_param.action, controller, &ctx, parts),
..Default::default()
}
.into());
};
let old_blob_id = old_commit
.and_then(|p| p.tree().unwrap().get_path(ctx.path.as_ref()).ok())
.map(|e| e.id());
if Some(blob_id) == old_blob_id {
return Err(Error::NotFound("no difference".into()));
}
let mut page = Page {
title: format!(
"{} for {}",
if params.oldid.is_some() {
"Diff"
} else {
"Commit"
},
ctx.path.file_name().unwrap()
),
header: action_links(&action_param.action, controller, &ctx, parts),
..Default::default()
};
page.body.push_str("<div>");
if params.oldid.is_none() {
page.body.push_str(&format!(
"<h1>{}</h1>{} committed on {}",
html_escape(commit.summary().unwrap_or_default()),
html_escape(commit.author().name().unwrap_or_default()),
NaiveDateTime::from_timestamp(commit.time().seconds(), 0).format("%b %d, %Y, %H:%M")
));
}
// TODO: if UTF-8 decoding fails, link ?action=raw&rev=
if let Some(old_blob_id) = old_blob_id {
page.body.push_str(&diff(
from_utf8(ctx.repo.find_blob(old_blob_id)?.content())?,
from_utf8(ctx.repo.find_blob(blob_id)?.content())?,
))
} else {
page.body.push_str(&diff(
"",
from_utf8(ctx.repo.find_blob(blob_id)?.content())?,
));
}
page.body.push_str("</div>");
Ok(page.into())
}
fn build_raw_response(
entr: TreeEntry,
ctx: &Context,
parts: &Parts,
) -> Result<HyperResponse, Error> {
if let Some(etag) = parts
.headers
.get(header::IF_NONE_MATCH)
.and_then(|v| v.to_str().ok())
{
if etag.trim_start_matches("W/").trim_matches('"') == entr.id().to_string() {
return Err(Error::NotModified);
}
}
let blob = ctx.repo.find_blob(entr.id()).unwrap();
let mut resp = HyperResponse::new(blob.content().to_owned().into());
resp.headers_mut()
.insert(header::ETAG, format!("\"{}\"", entr.id()).parse().unwrap());
resp.headers_mut()
.insert(header::CACHE_CONTROL, "no-cache".parse().unwrap());
Ok(resp)
}
fn raw_blob<C: Controller>(
entr: TreeEntry,
_params: ActionParam,
_controller: &C,
ctx: Context,
parts: &Parts,
) -> Result<HyperResponse, Error> {
let mut resp = build_raw_response(entr, &ctx, parts)?;
if let Some(mime) = mime_guess::from_path(&ctx.path).first() {
if mime.type_() == "text" {
// workaround for Firefox, which downloads non-plain text subtypes
// instead of displaying them (https://bugzilla.mozilla.org/1319262)
resp.headers_mut()
.insert(header::CONTENT_TYPE, "text/plain".parse().unwrap());
} else {
resp.headers_mut()
.insert(header::CONTENT_TYPE, mime.to_string().parse().unwrap());
}
}
Ok(resp)
}
fn run_blob<C: Controller>(
entr: TreeEntry,
_params: ActionParam,
_controller: &C,
ctx: Context,
parts: &Parts,
) -> Result<HyperResponse, Error> {
if ctx.path.extension() != Some("html") {
return Err(Error::BadRequest(
"run action only available for .html files".into(),
));
}
let mut resp = build_raw_response(entr, &ctx, parts)?;
resp.headers_mut()
.insert(header::CONTENT_TYPE, "text/html".parse().unwrap());
// We want users to be able to view .html applications of other users
// without having to worry about the application accessing their private
// files. So we set the CSP: sandbox header which makes browsers treat
// the page as a unique origin as per the same-origin policy.
resp.headers_mut().insert(
header::CONTENT_SECURITY_POLICY,
"sandbox allow-scripts;".parse().unwrap(),
);
Ok(resp)
}
fn move_blob<C: Controller>(
_entr: TreeEntry,
_params: ActionParam,
controller: &C,
ctx: Context,
parts: &Parts,
) -> Result<Response, Error> {
if !controller.may_move_path(&ctx, parts) {
return Err(Error::Unauthorized(
"you are not authorized to move this file".into(),
));
}
let filename = ctx.path.file_name().unwrap();
return forms::move_form(
filename,
&forms::MoveForm {
dest: ctx.path.as_str().to_owned(),
msg: None,
},
None,
controller,
&ctx,
parts,
);
}
fn remove_blob<C: Controller>(
entr: TreeEntry,
params: ActionParam,
controller: &C,
ctx: Context,
parts: &Parts,
) -> Result<Response, Error> {
if !controller.may_move_path(&ctx, parts) {
return Err(Error::Unauthorized(
"you are not authorized to remove this file".into(),
));
}
let filename = ctx.path.file_name().unwrap();
let page = Page {
title: format!("Remove {}", filename),
header: action_links(¶ms.action, controller, &ctx, parts),
body: "<form method=post autocomplete=off>\
<label>Message <input name=msg autofocus></label>\
<button>Remove</button></form>"
.into(),
..Default::default()
};
Ok(page.into())
}
pub fn view_tree<C: Controller>(
tree: Option<Tree>,
controller: &C,
ctx: &Context,
parts: &Parts,
) -> Result<Response, Error> {
let mut page = Page {
title: ctx.path.as_str().to_string(),
..Default::default()
};
page.body.push_str("<ul>");
if parts.uri.path() != "/" {
page.body
.push_str("<li><a href='..' title='go to parent directory'>../</a></li>");
}
if let Some(tree) = &tree {
let mut entries: Vec<_> = tree.iter().collect();
entries.sort_by_key(|a| a.kind().unwrap().raw());
for entry in entries {
// if the name isn't valid utf8 we skip the entry
if let Some(name) = entry.name() {
if entry.kind() == Some(ObjectType::Tree) {
page.body.push_str(&format!(
"<li><a href='{0}/'>{0}/</a></li>",
html_escape(name)
));
} else {
page.body.push_str(&format!(
"<li><a href='{0}'>{0}</a></li>",
html_escape(name)
));
}
}
}
}
page.body.push_str("</ul>");
controller.before_return_tree_page(&mut page, tree, ctx, parts);
Ok(page.into())
}
|