core&judge&ui: hack submission

This commit is contained in:
undefined committed 2022-09-06 13:02:46 +08:00
1 parent 07ab4f1bbd
commit 4e0c9bb00a
17 files changed
+256 -128

No files matched your search

+1 -1
View File
@@ -110,7 +110,7 @@ class SystemScriptHandler extends SystemHandler {
logger.warn('You are using the legacy script validation API, which will be dropped in the future.');
validate(global.Hydro.script[id].validate, args);
}
const rid = await record.add(domainId, -1, this.user._id, '-', id, false, raw);
const rid = await record.add(domainId, -1, this.user._id, '-', id, false, { input: raw, type: 'pretest' });
const report = (data) => judge.next({ domainId, rid, ...data });
report({ message: `Running script: ${id} `, status: STATUS.STATUS_JUDGING });
const start = Date.now();
+68 -8
View File
@@ -11,11 +11,11 @@ import {
BadRequestError, ContestNotAttendedError, ContestNotEndedError,
ContestNotFoundError, ContestNotLiveError,
ForbiddenError, NoProblemError, NotFoundError,
PermissionError, ProblemNotFoundError, SolutionNotFoundError,
PermissionError, ProblemNotFoundError, RecordNotFoundError, SolutionNotFoundError,
ValidationError,
} from '../error';
import {
ProblemDoc, ProblemSearchOptions, ProblemStatusDoc, User,
ProblemDoc, ProblemSearchOptions, ProblemStatusDoc, RecordDoc, User,
} from '../interface';
import paginate from '../lib/paginate';
import { isPid, parsePid as convertPid } from '../lib/validator';
@@ -498,9 +498,12 @@ export class ProblemSubmitHandler extends ProblemDetailHandler {
throw new BadRequestError('unable to run pretest');
}
}
await this.limitRate('add_record', 60, system.get('limit.submission_user'), true);
await this.limitRate('add_record', 60, system.get('limit.submission'));
const files: Record<string, string> = {};
if (!code) {
const file = this.request.files?.file;
if (!file) throw new ValidationError('code');
if (!file || file.size === 0) throw new ValidationError('code');
const config = this.response.body.pdoc.config;
if (typeof config !== 'object' || config === null) throw new BadRequestError('Incorrect problem config');
const sizeLimit = config.type === 'submit_answer' ? 128 * 1024 * 1024 : 65535;
@@ -508,15 +511,16 @@ export class ProblemSubmitHandler extends ProblemDetailHandler {
if (file.size > 65535 || await isBinaryFile(file.filepath, file.size)) {
const id = nanoid();
await storage.put(`submission/${this.user._id}/${id}`, file.filepath, this.user._id);
code = `@@hydro_submission_file@@${this.user._id}/${id}#${file.originalFilename}`;
files.code = `${this.user._id}/${id}#${file.originalFilename}`;
} else {
// TODO auto detect & convert encoding
code = await readFile(file.filepath, 'utf-8');
}
} else if (code.startsWith('@@hydro_submission_file@@')) throw new ValidationError('code');
await this.limitRate('add_record', 60, system.get('limit.submission_user'), true);
await this.limitRate('add_record', 60, system.get('limit.submission'));
const rid = await record.add(domainId, this.pdoc.docId, this.user._id, lang, code, true, pretest ? input : tid, tid && !pretest);
}
const rid = await record.add(
domainId, this.pdoc.docId, this.user._id, lang, code, true,
pretest ? { input, type: 'pretest' } : { contest: tid, files, type: tid ? 'contest' : 'judge' },
);
const rdoc = await record.get(domainId, rid);
if (!pretest) {
await Promise.all([
@@ -537,6 +541,61 @@ export class ProblemSubmitHandler extends ProblemDetailHandler {
}
}
export class ProblemHackHandler extends ProblemDetailHandler {
rdoc: RecordDoc;
@param('rid', Types.ObjectID)
@param('tid', Types.ObjectID, true)
async prepare(domainId: string, rid: ObjectID, tid?: ObjectID) {
this.rdoc = await record.get(domainId, rid);
if (!this.rdoc || this.rdoc.pid !== this.pdoc.docId
|| this.rdoc.contest?.toString() !== tid?.toString()) throw new RecordNotFoundError(domainId, rid);
if (tid) {
if (this.tdoc.rule !== 'codeforces') throw new ForbiddenError('This contest is not hackable.');
if (!contest.isOngoing(this.tdoc, this.tsdoc)) throw new ContestNotLiveError(this.tdoc.docId);
}
if (this.rdoc.uid === this.user._id) throw new BadRequestError('You cannot hack your own submission');
if (this.psdoc.status !== STATUS.STATUS_ACCEPTED) throw new ForbiddenError('You must accept this problem before hacking.');
if (this.rdoc.status !== STATUS.STATUS_ACCEPTED) throw new ForbiddenError('You cannot hack a unsuccessful submission.');
}
async get() {
this.response.template = 'problem_hack.html';
this.response.body = {
pdoc: this.pdoc,
udoc: this.udoc,
title: this.pdoc.title,
page_name: this.tdoc ? 'contest_detail_problem_hack' : 'problem_hack',
};
}
@param('input', Types.String, true)
@param('tid', Types.ObjectID, true)
async post(domainId: string, input = '', tid?: ObjectID) {
await this.limitRate('add_record', 60, system.get('limit.submission_user'), true);
await this.limitRate('add_record', 60, system.get('limit.submission'));
const id = `${this.user._id}/${nanoid()}`;
console.log(input);
if (this.request.files?.file?.size > 0) {
const file = this.request.files.file;
if (!file || file.size > 128 * 1024 * 1024) throw new ValidationError('input');
await storage.put(`submission/${id}`, file.filepath, this.user._id);
} else if (input) {
await storage.put(`submission/${id}`, Buffer.from(input), this.user._id);
}
const rid = await record.add(
domainId, this.pdoc.docId, this.user._id,
this.rdoc.lang, this.rdoc.code, true,
{ contest: tid, type: 'hack', files: { hack: `${id}#input.txt` } },
);
const rdoc = await record.get(domainId, rid);
// TODO contest: update status;
bus.broadcast('record/change', rdoc);
this.response.body = { rid };
this.response.redirect = this.url('record_detail', { rid });
}
}
export class ProblemManageHandler extends ProblemDetailHandler {
async prepare() {
if (!this.user.own(this.pdoc, PERM.PERM_EDIT_PROBLEM_SELF)) this.checkPerm(PERM.PERM_EDIT_PROBLEM);
@@ -935,6 +994,7 @@ export async function apply() {
Route('problem_random', '/problem/random', ProblemRandomHandler, PERM.PERM_VIEW_PROBLEM);
Route('problem_detail', '/p/:pid', ProblemDetailHandler, PERM.PERM_VIEW_PROBLEM);
Route('problem_submit', '/p/:pid/submit', ProblemSubmitHandler, PERM.PERM_SUBMIT_PROBLEM);
Route('problem_hack', '/p/:pid/hack/:rid', ProblemHackHandler, PERM.PERM_SUBMIT_PROBLEM);
Route('problem_edit', '/p/:pid/edit', ProblemEditHandler);
Route('problem_config', '/p/:pid/config', ProblemConfigHandler);
Route('problem_files', '/p/:pid/files', ProblemFilesHandler, PERM.PERM_VIEW_PROBLEM);
+43 -40
View File
@@ -107,13 +107,34 @@ class RecordListHandler extends Handler {
}
class RecordDetailHandler extends Handler {
rdoc: RecordDoc;
@param('rid', Types.ObjectID)
async prepare(domainId: string, rid: ObjectID) {
this.rdoc = await record.get(domainId, rid);
if (!this.rdoc) throw new RecordNotFoundError(rid);
}
async download() {
for (const file of ['code', 'hack']) {
if (!this.rdoc.files?.[file]) continue;
const [id, filename] = this.rdoc.files?.[file]?.split('#') || [];
// eslint-disable-next-line no-await-in-loop
this.response.redirect = await storage.signDownloadLink(`submission/${id}`, filename || file, true, 'user');
return;
}
const lang = langs[this.rdoc.lang]?.pretest || this.rdoc.lang;
this.response.body = this.rdoc.code;
this.response.type = 'text/plain';
this.response.disposition = `attachment; filename="${langs[lang].code_file || `foo.${this.rdoc.lang}`}"`;
}
@param('rid', Types.ObjectID)
@param('download', Types.Boolean)
// eslint-disable-next-line consistent-return
async get(domainId: string, rid: ObjectID, download = false) {
const rdoc = await record.get(domainId, rid);
if (!rdoc) throw new RecordNotFoundError(rid);
const rdoc = this.rdoc;
let tdoc;
if (rdoc.contest?.toHexString() === '000000000000000000000000') {
if (rdoc.contest?.toString() === '000000000000000000000000') {
if (rdoc.uid !== this.user._id) throw new PermissionError(PERM.PERM_READ_RECORD_CODE);
} else if (rdoc.contest) {
tdoc = await contest.get(domainId, rdoc.contest);
@@ -136,21 +157,9 @@ class RecordDetailHandler extends Handler {
canViewCode ||= this.user.hasPerm(PERM.PERM_READ_RECORD_CODE_ACCEPT) && self?.status === STATUS.STATUS_ACCEPTED;
if (!canViewCode) {
rdoc.code = '';
rdoc.files = {};
rdoc.compilerTexts = [];
}
if (download && rdoc.code.startsWith('@@hydro_submission_file@@')) {
const [id, filename] = rdoc.code.split('@@hydro_submission_file@@')[1].split('#');
this.response.redirect = await storage.signDownloadLink(`submission/${id}`, filename || 'code', true, 'judge');
return;
}
if (download) {
const lang = langs[rdoc.lang]?.pretest || rdoc.lang;
this.response.body = rdoc.code;
this.response.type = 'text/plain';
this.response.disposition = `attachment; filename="${langs[lang].code_file || `foo.${rdoc.lang}`}"`;
return;
}
} else if (download) return await this.download();
if (pdoc && !(rdoc.contest && this.user._id === rdoc.uid)) {
if (!problem.canViewBy(pdoc, this.user)) throw new PermissionError(PERM.PERM_VIEW_PROBLEM_HIDDEN);
}
@@ -165,34 +174,28 @@ class RecordDetailHandler extends Handler {
async postRejudge(domainId: string, rid: ObjectID) {
this.checkPerm(PERM.PERM_REJUDGE);
const priority = await record.submissionPriority(this.user._id, -20);
const rdoc = await record.get(domainId, rid);
if (rdoc) {
const isContest = rdoc.contest && rdoc.contest.toHexString() !== '000000000000000000000000';
await record.reset(domainId, rid, true);
await record.judge(domainId, rid, priority, isContest ? { detail: false } : {});
}
const isContest = this.rdoc.contest && this.rdoc.contest.toString() !== '000000000000000000000000';
await record.reset(domainId, rid, true);
await record.judge(domainId, rid, priority, isContest ? { detail: false } : {});
this.back();
}
@param('rid', Types.ObjectID)
async postCancel(domainId: string, rid: ObjectID) {
const rdoc = await record.get(domainId, rid);
if (rdoc) {
const $set = {
status: STATUS.STATUS_CANCELED,
score: 0,
time: 0,
memory: 0,
testCases: [{
id: 0, subtaskId: 0, status: 9, score: 0, time: 0, memory: 0, message: 'score canceled',
}],
};
const [latest] = await Promise.all([
record.update(domainId, rid, $set),
TaskModel.deleteMany({ rid: rdoc._id }),
]);
if (latest) await postJudge(latest);
}
const $set = {
status: STATUS.STATUS_CANCELED,
score: 0,
time: 0,
memory: 0,
testCases: [{
id: 0, subtaskId: 0, status: 9, score: 0, time: 0, memory: 0, message: 'score canceled',
}],
};
const [latest] = await Promise.all([
record.update(domainId, rid, $set),
TaskModel.deleteMany({ rid: this.rdoc._id }),
]);
if (latest) await postJudge(latest);
this.back();
}
}