-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathServerComparer.cs
More file actions
203 lines (184 loc) · 8.21 KB
/
Copy pathServerComparer.cs
File metadata and controls
203 lines (184 loc) · 8.21 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
using System.Collections.Specialized;
using System.Net;
using CCExtractorTester.Analyzers;
using System.IO;
using System.Collections.Generic;
using System;
using System.Text;
using System.Net;
using System.Globalization;
namespace CCExtractorTester.Comparers
{
/// <summary>
/// Class for sending data back to a server instead of doing the comparison locally.
/// </summary>
public class ServerComparer : IFileComparable
{
private class UploadFile
{
public UploadFile()
{
ContentType = "application/octet-stream";
}
public string Name { get; set; }
public string Filename { get; set; }
public string ContentType { get; set; }
public Stream Stream { get; set; }
}
private byte[] UploadFiles(string address, IEnumerable<UploadFile> files, NameValueCollection values)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var request = WebRequest.Create(address);
request.Method = "POST";
var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", NumberFormatInfo.InvariantInfo);
request.ContentType = "multipart/form-data; boundary=" + boundary;
boundary = "--" + boundary;
using (var requestStream = request.GetRequestStream())
{
// Write the values
foreach (string name in values.Keys)
{
var buffer = Encoding.ASCII.GetBytes(boundary + "\r\n");
requestStream.Write(buffer, 0, buffer.Length);
buffer = Encoding.ASCII.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"{1}{1}", name, "\r\n"));
requestStream.Write(buffer, 0, buffer.Length);
buffer = Encoding.UTF8.GetBytes(values[name] + "\r\n");
requestStream.Write(buffer, 0, buffer.Length);
}
// Write the files
foreach (var file in files)
{
var buffer = Encoding.ASCII.GetBytes(boundary + "\r\n");
requestStream.Write(buffer, 0, buffer.Length);
buffer = Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}", file.Name, file.Filename, "\r\n"));
requestStream.Write(buffer, 0, buffer.Length);
buffer = Encoding.ASCII.GetBytes(string.Format("Content-Type: {0}{1}{1}", file.ContentType, "\r\n"));
requestStream.Write(buffer, 0, buffer.Length);
file.Stream.CopyTo(requestStream);
buffer = Encoding.ASCII.GetBytes("\r\n");
requestStream.Write(buffer, 0, buffer.Length);
}
var boundaryBuffer = Encoding.ASCII.GetBytes(boundary + "--");
requestStream.Write(boundaryBuffer, 0, boundaryBuffer.Length);
}
using (var response = request.GetResponse())
using (var responseStream = response.GetResponseStream())
using (var stream = new MemoryStream())
{
responseStream.CopyTo(stream);
return stream.ToArray();
}
}
/// <summary>
/// The URL where the class will send status updates to.
/// </summary>
private string reportUrl;
private static string userAgent = "CCX/CI_BOT";
/// <summary>
/// Generates an new instance of this class.
/// </summary>
/// <param name="reportUrl">The URL where the class will send status updates to.</param>
public ServerComparer(string reportUrl)
{
this.reportUrl = reportUrl;
}
#region IFileComparable implementation
/// <summary>
/// Compares the files provided in the data and add to an internal result.
/// </summary>
/// <param name="data">The data for this entry.</param>
public void CompareAndAddToResult(CompareData data)
{
// Check for equality by hash
if (!data.Dummy && !Hasher.filesAreEqual(data.CorrectFile, data.ProducedFile))
{
// Guard: if no output file was produced, skip upload.
// When ProducedFile is empty (output missing), File.Open("") throws
// ArgumentException which is swallowed by the caller's catch-all
// handler, resulting in no TestResultFile row being written.
// This prevents the ArgumentException from propagating to the
// caller's catch block.
if (string.IsNullOrEmpty(data.ProducedFile) || !File.Exists(data.ProducedFile))
{
return;
}
// Upload result
using (FileStream stream = File.Open(data.ProducedFile, FileMode.Open))
{
UploadFile[] files = new[] {
new UploadFile {
Name = "file", //Path.GetFileNameWithoutExtension(data.ProducedFile),
Filename = Path.GetFileName(data.ProducedFile),
ContentType = "application/octet-stream",
Stream = stream
}
};
NameValueCollection nv = new NameValueCollection {
{ "type", "upload" },
{ "test_id", data.TestID.ToString() },
{ "test_file_id", data.TestFileID.ToString() }
};
byte[] result = UploadFiles(reportUrl, files, nv);
}
/*using (var wb = new WebClient())
{
wb.Headers.Add("user-agent", userAgent);
// TODO: check if this works
var response = wb.UploadFile(reportUrl, data.ProducedFile);
}*/
}
else
{
// Post equality status
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (var wb = new WebClient())
{
wb.Headers.Add("user-agent", userAgent);
var d = new NameValueCollection();
d["type"] = "equality";
d["test_id"] = data.TestID.ToString();
d["test_file_id"] = data.TestFileID.ToString();
var response = wb.UploadValues(reportUrl, "POST", d);
}
}
}
/// <summary>
/// Gets the success number.
/// </summary>
/// <returns>The success number.</returns>
public int GetSuccessNumber()
{
return -1; // Cannot be implemented in this class
}
/// <summary>
/// Saves the report to a given file, with some extra data provided.
/// </summary>
/// <param name="pathToFolder">Path to folder to save the report in</param>
/// <param name="data">The extra result data that should be in the report.</param>
public string SaveReport(string pathToFolder, ResultData data)
{
// Do nothing
return "";
}
#endregion
/// <summary>
/// Specific method that sends the runtime to the server for a given sample.
/// </summary>
/// <param name="rd">The run data instance which contains the exit code and runtime.</param>
/// <param name="testId">The id of the test</param>
public void SendExitCodeAndRuntime(RunData rd, int testId)
{
// Post equality status
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (var wb = new WebClient())
{
var d = new NameValueCollection();
d["exitCode"] = rd.ExitCode.ToString();
d["runTime"] = Convert.ToInt32(rd.Runtime.TotalMilliseconds).ToString();
d["test_id"] = testId.ToString();
d["type"] = "finish";
var response = wb.UploadValues(reportUrl, "POST", d);
}
}
}
}