-
-
Notifications
You must be signed in to change notification settings - Fork 793
/
RequestHandler.cpp
307 lines (271 loc) · 9.63 KB
/
RequestHandler.cpp
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
/*
* Stellarium Remote Control plugin
* Copyright (C) 2015 Florian Schaukowitsch
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA.
*/
#include "RequestHandler.hpp"
#include "httpserver/staticfilecontroller.h"
#include "templateengine/template.h"
#include "APIController.hpp"
#include "LocationService.hpp"
#include "LocationSearchService.hpp"
#include "MainService.hpp"
#include "ObjectService.hpp"
#include "ScriptService.hpp"
#include "SimbadService.hpp"
#include "StelActionService.hpp"
#include "StelPropertyService.hpp"
#include "ViewService.hpp"
#include "StelApp.hpp"
#include "StelTranslator.hpp"
#include "StelModuleMgr.hpp"
#include <QDir>
#include <QFile>
#include <QPluginLoader>
const QByteArray RequestHandler::AUTH_REALM = "Basic realm=\"Stellarium remote control\"";
class HtmlTranslationProvider : public ITemplateTranslationProvider
{
public:
HtmlTranslationProvider(StelTranslator* localInstance)
{
rcTranslator = localInstance;
}
QString getTranslation(const QString &key) override
{
//try to get a RemoteControl specific translation first
QString trans = rcTranslator->tryQtranslate(key);
if(trans.isNull())
trans = StelTranslator::globalTranslator->qtranslate(key);
//HTML escape + single quote escape
return trans.toHtmlEscaped().replace('\'',"'");
}
private:
StelTranslator* rcTranslator;
};
class JsTranslationProvider : public ITemplateTranslationProvider
{
public:
JsTranslationProvider(StelTranslator* localInstance)
{
rcTranslator = localInstance;
}
QString getTranslation(const QString &key) override
{
//try to get a RemoteControl specific translation first
QString trans = rcTranslator->tryQtranslate(key);
if(trans.isNull())
trans = StelTranslator::globalTranslator->qtranslate(key);
//JS escape single/double quotes
return trans.replace('\'',"\\'").replace('"',"\\\"");
}
private:
StelTranslator* rcTranslator;
};
#if (QT_VERSION>=QT_VERSION_CHECK(5,14,0))
RequestHandler::RequestHandler(const StaticFileControllerSettings& settings, QObject* parent) : HttpRequestHandler(parent), usePassword(false), enableCors(false), templateMutex()
#else
RequestHandler::RequestHandler(const StaticFileControllerSettings& settings, QObject* parent) : HttpRequestHandler(parent), usePassword(false), enableCors(false), templateMutex(QMutex::Recursive)
#endif
{
apiController = new APIController(QByteArray("/api/").size(),this);
//register the services
//they "live" in the main thread in the QObject sense, but their service methods are actually
//executed in the HTTP handler threads
apiController->registerService(new MainService(apiController));
apiController->registerService(new ObjectService(apiController));
#ifdef ENABLE_SCRIPTING
apiController->registerService(new ScriptService(apiController));
#endif
apiController->registerService(new SimbadService(apiController));
apiController->registerService(new StelActionService(apiController));
apiController->registerService(new StelPropertyService(apiController));
apiController->registerService(new LocationService(apiController));
apiController->registerService(new LocationSearchService(apiController));
apiController->registerService(new ViewService(apiController));
connect(&StelApp::getInstance().getModuleMgr(), SIGNAL(extensionsAdded(QObjectList)), this, SLOT(addExtensionServices(QObjectList)));
addExtensionServices(StelApp::getInstance().getModuleMgr().getExtensionList());
staticFiles = new StaticFileController(settings,this);
connect(&StelApp::getInstance(),SIGNAL(languageChanged()),this,SLOT(refreshTemplates()));
refreshTemplates();
}
RequestHandler::~RequestHandler()
{
}
void RequestHandler::addExtensionServices(QObjectList services)
{
for (auto* obj : services)
{
RemoteControlServiceInterface* sv = qobject_cast<RemoteControlServiceInterface*>(obj);
if(sv)
{
qDebug()<<"Registering RemoteControl extension service:"<<sv->getPath();
apiController->registerService(sv);
}
}
}
void RequestHandler::update(double deltaTime)
{
apiController->update(deltaTime);
}
void RequestHandler::service(HttpRequest &request, HttpResponse &response)
{
#define SERVER_HEADER "Stellarium RemoteControl " REMOTECONTROL_PLUGIN_VERSION
response.setHeader("Server",SERVER_HEADER);
if(QString::compare(request.getMethod(),"OPTIONS",Qt::CaseInsensitive)==0) {
handleCorsPreflightRequest(request,response);
return;
}
//try to support keep-alive connections
if(QString::compare(request.getHeader("Connection"),"keep-alive",Qt::CaseInsensitive)==0)
response.setHeader("Connection","keep-alive");
else
response.setHeader("Connection","close");
if(enableCors)
{
response.setHeader("Access-Control-Allow-Origin",corsOrigin.toUtf8());
response.setHeader("Access-Control-Allow-Methods","GET, PUT, POST, HEAD, OPTIONS");
response.setHeader("Vary","Origin");
}
if(usePassword)
{
//Check if the browser provided correct password, else reject request
if(request.getHeader("Authorization") != passwordReply)
{
response.setStatus(401,"Not Authorized");
response.setHeader("WWW-Authenticate",AUTH_REALM);
response.write("HTTP 401 Not Authorized",true);
return;
}
}
//QByteArray rawPath = request.getRawPath();
QByteArray path = request.getPath();
//qDebug()<<"Request path:"<<rawPath<<" decoded:"<<path;
if(path.startsWith("/api/"))
{
//this is an API request, pass it on
apiController->service(request,response);
}
else
{
if(path.isEmpty() || path == "/" || path == "/index.html")
{
//transparently redirect to index.html
path = "/index.html";
}
//make sure we can access the template map
templateMutex.lock();
if(templateMap.contains(path))
{
#ifndef QT_NO_DEBUG
//force fresh loading for each request in debug mode
//to allow for immediate display of changes
refreshTemplates();
#endif
QByteArray content = templateMap[path].toUtf8();
templateMutex.unlock();
//get a mime type
QByteArray mime = StaticFileController::getContentType(path,"utf-8");
if(!mime.isEmpty())
response.setHeader("Content-Type",mime);
//serve the stored template
response.write(content,true);
}
else
{
templateMutex.unlock();
//let the static file controller handle the request
staticFiles->service(request,response);
}
}
}
void RequestHandler::setUsePassword(bool v)
{
usePassword = v;
}
void RequestHandler::setPassword(const QString &pw)
{
password = pw;
//pre-create the expected response string
QByteArray arr = password.toUtf8();
arr.prepend(':');
passwordReply = "Basic " + arr.toBase64();
}
void RequestHandler::setEnableCors(bool v)
{
enableCors = v;
}
void RequestHandler::setCorsOrigin(const QString &origin)
{
corsOrigin = origin;
}
void RequestHandler::refreshTemplates()
{
//multiple threads can potentially enter here,
//so this requires locking
QMutexLocker locker(&templateMutex);
//remove old translations
templateMap.clear();
//create a translator for remote control specific stuff, with the current language
StelTranslator rcTrans("stellarium-remotecontrol",StelTranslator::globalTranslator->getTrueLocaleName());
JsTranslationProvider jsTranslator(&rcTrans);
HtmlTranslationProvider htmlTranslator(&rcTrans);
QDir docRoot = QDir(staticFiles->getDocRoot());
//load the translate_files list
QFile transFileList(docRoot.absoluteFilePath("translate_files"));
if(transFileList.open(QFile::ReadOnly))
{
QTextStream text(&transFileList);
//read line by line, ignoring whitespace and comments
while(!text.atEnd())
{
QString line = text.readLine().trimmed();
if(line.isEmpty() || line.startsWith('#'))
continue;
//load file and translate
QFile f(docRoot.absoluteFilePath(line));
if(f.exists())
{
//use the HTML escapes by default,
//but use JS escapes for js files
ITemplateTranslationProvider* transProv = &htmlTranslator;
if(line.endsWith(".js"))
transProv = &jsTranslator;
Template tmp(f);
tmp.translate(*transProv);
//check if the file was correctly loaded
if(!tmp.isEmpty())
{
templateMap.insert('/'+line.toUtf8(),tmp);
}
}
else
qWarning()<<"[RemoteControl] Translatable file"<<f.fileName()<<"does not exist!";
}
transFileList.close();
}
else
{
qWarning()<<"[RemoteControl] "<<transFileList.fileName()<<" could not be opened, can not automatically translate files with StelTranslator!";
}
}
void RequestHandler::handleCorsPreflightRequest(HttpRequest &request, HttpResponse &response) {
response.setStatus(204,"No Content");
response.setHeader("Access-Control-Allow-Origin",corsOrigin.toUtf8());
response.setHeader("Access-Control-Allow-Methods","GET, POST");
response.setHeader("Access-Control-Allow-Headers",request.getHeader("Access-Control-Request-Headers"));
response.setHeader("Access-Control-Max-Age","0");
response.setHeader("Vary","Origin");
}