forked from reprappro/RepRapFirmware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebserver.cpp
2511 lines (2247 loc) · 63 KB
/
Webserver.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
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/****************************************************************************************************
RepRapFirmware - Webserver
This class serves a single-page web applications to the attached network. This page forms the user's
interface with the RepRap machine. This software interprests returned values from the page and uses it
to generate G Codes, which it sends to the RepRap. It also collects values from the RepRap like
temperature and uses those to construct the web page.
The page itself - reprap.htm - uses Jquery.js to perform AJAX. See:
http://jquery.com/
-----------------------------------------------------------------------------------------------------
Version 0.2
10 May 2013
Adrian Bowyer
RepRap Professional Ltd
http://reprappro.com
Licence: GPL
-----------------------------------------------------------------------------------------------------
The supported requests are GET requests for files (for which the root is the www directory on the
SD card), and the following. These all start with "/rr_". Ordinary files used for the web interface
must not have names starting "/rr_" or they will not be found.
rr_connect?password=xxx
Sent by the web interface software to establish an initial connection, indicating that
any state variables relating to the web interface (e.g. file upload in progress) should
be reset. This only happens if the password could be verified.
rr_fileinfo Returns file information about the file being printed.
rr_fileinfo?name=xxx
Returns file information about a file on the SD card or a JSON-encapsulated response
with err = 1 if the passed filename was invalid.
rr_status New-style status response, in which temperatures, axis positions and extruder positions
are returned in separate variables. Another difference is that extruder positions are
returned as absolute positions instead of relative to the previous gcode. A client
may also request different status responses by specifying the "type" keyword, followed
by a custom status response type. Also see "M105 S1".
rr_files?dir=xxx
Returns a listing of the filenames in the /gcode directory of the SD card. 'dir' is a
directory path relative to the root of the SD card. If the 'dir' variable is not present,
it defaults to the /gcode directory.
rr_reply Returns the last-known G-code reply as plain text (not encapsulated as JSON).
rr_upload?name=xxx
Upload a specified file using a POST request. The payload of this request has to be
the file content. Only one file may be uploaded at once. When the upload has finished,
a JSON response with the variable "err" will be returned, which will be 0 if the job
has finished without problems, it will be set to 1 otherwise.
rr_upload_begin?name=xxx
Indicates that we wish to upload the specified file. xxx is the filename relative
to the root of the SD card. The directory component of the filename must already
exist. Returns variables ubuff (= max upload data we can accept in the next message)
and err (= 0 if the file was created successfully, nonzero if there was an error).
rr_upload_data?data=xxx
Provides a data block for the file upload. Returns the samwe variables as rr_upload_begin,
except that err is only zero if the file was successfully created and there has not been
a file write error yet. This response is returned before attempting to write this data block.
rr_upload_end
Indicates that we have finished sending upload data. The server closes the file and reports
the overall status in err. It may also return ubuff again.
rr_upload_cancel
Indicates that the user wishes to cancel the current upload. Returns err and ubuff.
rr_delete?name=xxx
Delete file xxx. Returns err (zero if successful).
rr_mkdir?dir=xxx
Create a new directory xxx. Return err (zero if successful).
rr_move?old=xxx&new=yyy
Rename an old file xxx to yyy. May also be used to move a file to another directory.
****************************************************************************************************/
#include "RepRapFirmware.h"
//***************************************************************************************************
static const char* overflowResponse = "overflow";
static const char* badEscapeResponse = "bad escape";
const float pasvPortTimeout = 10.0; // seconds to wait for the FTP data port
//********************************************************************************************
//
//**************************** Generic Webserver implementation ******************************
//
//********************************************************************************************
// Constructor and initialisation
Webserver::Webserver(Platform* p, Network *n) : platform(p), network(n),
webserverActive(false), readingConnection(NULL)
{
httpInterpreter = new HttpInterpreter(p, this, n);
ftpInterpreter = new FtpInterpreter(p, this, n);
telnetInterpreter = new TelnetInterpreter(p, this, n);
}
void Webserver::Init()
{
// initialise the webserver class
gcodeReadIndex = gcodeWriteIndex = 0;
lastTime = platform->Time();
longWait = lastTime;
webserverActive = true;
// initialise all protocol handlers
httpInterpreter->ResetState();
httpInterpreter->ResetSessions();
ftpInterpreter->ResetState();
telnetInterpreter->ResetState();
}
// Deal with input/output from/to the client (if any)
void Webserver::Spin()
{
// Before we process an incoming Request, we must ensure that the webserver
// is active and that all upload buffers are empty.
if (webserverActive && httpInterpreter->FlushUploadData() && ftpInterpreter->FlushUploadData())
{
// Check if we can purge any HTTP sessions
httpInterpreter->CheckSessions();
// We must ensure that we have exclusive access to LWIP
if (!network->Lock())
{
platform->ClassReport(longWait);
return;
}
// See if we have new data to process
NetworkTransaction *req = network->GetTransaction(readingConnection);
if (req != NULL)
{
if (!req->LostConnection())
{
// Take care of different protocol types here
ProtocolInterpreter *interpreter;
uint16_t localPort = req->GetLocalPort();
switch (localPort)
{
case ftpPort: /* FTP */
interpreter = ftpInterpreter;
break;
case telnetPort: /* Telnet */
interpreter = telnetInterpreter;
break;
default: /* HTTP and FTP data */
if (localPort == network->GetHttpPort())
{
interpreter = httpInterpreter;
}
else
{
interpreter = ftpInterpreter;
}
break;
}
// For protocols other than HTTP it is important to send a HELO message
TransactionStatus status = req->GetStatus();
if (status == connected)
{
interpreter->ConnectionEstablished();
// Close this request unless ConnectionEstablished() has already used it for sending
if (req == network->GetTransaction())
{
network->CloseTransaction();
}
}
// Graceful disconnects are handled here, because prior NetworkTransactions might still contain valid
// data. That's why it's a bad idea to close these connections immediately in the Network class.
else if (status == disconnected)
{
// CloseRequest() will call the disconnect events and close the connection
network->CloseTransaction();
}
// Check for fast uploads
else if (interpreter->DoingFastUpload())
{
if (!interpreter->DoFastUpload())
{
// Ensure this connection won't block everything if anything goes wrong
readingConnection = NULL;
}
}
// Check if we need to send data to a Telnet client
else if (interpreter == telnetInterpreter && telnetInterpreter->HasRemainingData())
{
network->SendAndClose(NULL, true);
telnetInterpreter->RemainingDataSent();
}
// Process other messages
else
{
char c;
for (uint16_t i=0; i<500; i++)
{
if (req->Read(c))
{
// Each ProtocolInterpreter must take care of the current NetworkTransaction and remove
// it from the ready transactions by either calling SendAndClose() or CloseRequest().
if (interpreter->CharFromClient(c))
{
readingConnection = NULL;
break;
}
}
else
{
// We ran out of data before finding a complete request.
// This happens when the incoming message length exceeds the TCP MSS.
// Check if we need to process another packet on the same connection.
readingConnection = (interpreter->NeedMoreData()) ? req->GetConnection() : NULL;
network->CloseTransaction();
break;
}
}
}
}
else
{
platform->Message(HOST_MESSAGE, "Webserver: Skipping zombie request with status %d\n", req->GetStatus());
network->CloseTransaction();
}
}
network->Unlock();
platform->ClassReport(longWait);
}
}
void Webserver::Exit()
{
httpInterpreter->CancelUpload();
ftpInterpreter->CancelUpload();
platform->Message(BOTH_MESSAGE, "Webserver class exited.\n");
webserverActive = false;
}
void Webserver::Diagnostics()
{
platform->AppendMessage(BOTH_MESSAGE, "Webserver Diagnostics:\n");
}
// Process a null-terminated gcode
// We intercept four G/M Codes so we can deal with file manipulation and emergencies. That
// way things don't get out of sync, and - as a file name can contain
// a valid G code (!) - confusion is avoided.
void Webserver::ProcessGcode(const char* gc)
{
if (StringStartsWith(gc, "M112") && !isdigit(gc[4])) // emergency stop
{
reprap.EmergencyStop();
gcodeReadIndex = gcodeWriteIndex; // clear the buffer
reprap.GetGCodes()->Reset();
}
else if (StringStartsWith(gc, "M503") && !isdigit(gc[4])) // echo config.g file
{
FileStore *configFile = platform->GetFileStore(platform->GetSysDir(), platform->GetConfigFile(), false);
if (configFile == NULL)
{
ResponseToWebInterface("Configuration file not found", true);
}
else
{
reprap.MessageToGCodeReply("");
char c;
bool readingWhitespace = false;
while (configFile->Read(c))
{
if (!readingWhitespace || (c != ' ' && c != '\t'))
{
reprap.AppendCharToStatusResponse(c);
}
readingWhitespace = (c == ' ' || c == '\t');
}
configFile->Close();
telnetInterpreter->HandleGcodeReply(reprap.GetGcodeReply().Pointer());
}
}
else
{
StoreGcodeData(gc, strlen(gc) + 1);
}
}
// Feeding G Codes to the GCodes class
bool Webserver::GCodeAvailable()
{
return gcodeReadIndex != gcodeWriteIndex;
}
char Webserver::ReadGCode()
{
char c;
if (gcodeReadIndex == gcodeWriteIndex)
{
c = 0;
}
else
{
c = gcodeBuffer[gcodeReadIndex];
gcodeReadIndex = (gcodeReadIndex + 1u) % gcodeBufferLength;
}
return c;
}
// Process a received string of gcodes
void Webserver::LoadGcodeBuffer(const char* gc)
{
char gcodeTempBuf[GCODE_LENGTH];
uint16_t gtp = 0;
bool inComment = false;
for (;;)
{
char c = *gc++;
if (c == 0)
{
gcodeTempBuf[gtp] = 0;
ProcessGcode(gcodeTempBuf);
return;
}
if (c == '\n')
{
gcodeTempBuf[gtp] = 0;
ProcessGcode(gcodeTempBuf);
gtp = 0;
inComment = false;
}
else
{
if (c == ';')
{
inComment = true;
}
if (gtp == ARRAY_UPB(gcodeTempBuf))
{
// gcode is too long, we haven't room for another character and a null
if (c != ' ' && !inComment)
{
platform->Message(BOTH_ERROR_MESSAGE, "Webserver: GCode local buffer overflow.\n");
return;
}
// else we're either in a comment or the current character is a space.
// If we're in a comment, we'll silently truncate it.
// If the current character is a space, we'll wait until we see a non-comment character before reporting an error,
// in case the next character is end-of-line or the start of a comment.
}
else
{
gcodeTempBuf[gtp++] = c;
}
}
}
}
// Process a received string of gcodes
void Webserver::StoreGcodeData(const char* data, size_t len)
{
if (len > GetGcodeBufferSpace())
{
platform->Message(BOTH_ERROR_MESSAGE, "GCode buffer overflow in Webserver!\n");
}
else
{
size_t remaining = gcodeBufferLength - gcodeWriteIndex;
if (len <= remaining)
{
memcpy(gcodeBuffer + gcodeWriteIndex, data, len);
}
else
{
memcpy(gcodeBuffer + gcodeWriteIndex, data, remaining);
memcpy(gcodeBuffer, data + remaining, len - remaining);
}
gcodeWriteIndex = (gcodeWriteIndex + len) % gcodeBufferLength;
}
}
// Handle immediate disconnects here (cs will be freed after this call)
void Webserver::ConnectionLost(const ConnectionState *cs)
{
// See which connection caused this event
uint32_t remoteIP = cs->GetRemoteIP();
uint16_t remotePort = cs->GetRemotePort();
uint16_t localPort = cs->GetLocalPort();
// Inform protocol handlers that this connection has been lost
ProtocolInterpreter *interpreter;
switch (localPort)
{
case ftpPort: /* FTP */
interpreter = ftpInterpreter;
break;
case telnetPort: /* Telnet */
interpreter = telnetInterpreter;
break;
default: /* HTTP and FTP data */
if (localPort == network->GetHttpPort())
{
interpreter = httpInterpreter;
break;
}
else if (localPort == network->GetDataPort())
{
interpreter = ftpInterpreter;
break;
}
platform->Message(BOTH_ERROR_MESSAGE, "Webserver: Connection closed at local port %d, but no handler found!\n", localPort);
return;
}
if (reprap.Debug(moduleWebserver))
{
platform->Message(HOST_MESSAGE, "Webserver: ConnectionLost called with port %d\n", localPort);
}
interpreter->ConnectionLost(remoteIP, remotePort, localPort);
// If our reading connection is lost, it will be no longer important which connection is read from first.
if (cs == readingConnection)
{
readingConnection = NULL;
}
}
void Webserver::ResponseToWebInterface(const char *s, bool error)
{
if (!webserverActive)
{
return;
}
if (strlen(s) == 0 && !error)
{
reprap.MessageToGCodeReply(s);
telnetInterpreter->HandleGcodeReply("ok\r\n");
}
else
{
if (error)
{
reprap.MessageToGCodeReply("Error: ");
reprap.AppendMessageToGCodeReply(s);
telnetInterpreter->HandleGcodeReply("Error: ");
telnetInterpreter->HandleGcodeReply(s);
}
else
{
reprap.MessageToGCodeReply(s);
telnetInterpreter->HandleGcodeReply(s);
}
}
}
void Webserver::AppendResponseToWebInterface(const char *s)
{
if (!webserverActive)
{
return;
}
reprap.AppendMessageToGCodeReply(s);
telnetInterpreter->HandleGcodeReply(s);
}
//********************************************************************************************
//
//********************** Generic Procotol Interpreter implementation *************************
//
//********************************************************************************************
ProtocolInterpreter::ProtocolInterpreter(Platform *p, Webserver *ws, Network *n)
: platform(p), webserver(ws), network(n)
{
uploadState = notUploading;
uploadPointer = NULL;
uploadLength = 0;
filenameBeingUploaded[0] = 0;
}
// Start writing to a new file
bool ProtocolInterpreter::StartUpload(FileStore *file)
{
CancelUpload();
if (file != NULL)
{
fileBeingUploaded.Set(file);
uploadState = uploadOK;
return true;
}
uploadState = uploadError;
platform->Message(HOST_MESSAGE, "Could not open file while starting upload!\n");
return false;
}
// Process a received buffer of upload data
bool ProtocolInterpreter::StoreUploadData(const char* data, unsigned int len)
{
if (uploadState == uploadOK)
{
uploadPointer = data;
uploadLength = len;
return true;
}
return false;
}
// Try to flush upload buffer and return true if all data has been flushed
bool ProtocolInterpreter::FlushUploadData()
{
if (uploadState == uploadOK && uploadLength != 0)
{
// Write some uploaded data to file (never write more than 256 bytes at once)
unsigned int len = min<unsigned int>(uploadLength, 256);
if (!fileBeingUploaded.Write(uploadPointer, len))
{
platform->Message(HOST_MESSAGE, "Could not flush upload data!\n");
uploadState = uploadError;
}
uploadPointer += len;
uploadLength -= len;
return (uploadLength == 0);
}
return true;
}
void ProtocolInterpreter::CancelUpload()
{
if (fileBeingUploaded.IsLive())
{
fileBeingUploaded.Close(); // cancel any pending file upload
if (strlen(filenameBeingUploaded) != 0)
{
platform->GetMassStorage()->Delete("0:/", filenameBeingUploaded);
}
}
filenameBeingUploaded[0] = 0;
uploadPointer = NULL;
uploadLength = 0;
uploadState = notUploading;
}
bool ProtocolInterpreter::DoFastUpload()
{
NetworkTransaction *req = network->GetTransaction();
if (IsUploading())
{
char *buffer;
unsigned int len;
if (req->ReadBuffer(buffer, len))
{
StoreUploadData(buffer, len);
}
else
{
network->CloseTransaction();
}
}
else if (req->DataLength() > 0)
{
platform->Message(HOST_MESSAGE, "Webserver: Closing invalid data connection\n");
network->SendAndClose(NULL);
return false;
}
return true;
}
void ProtocolInterpreter::FinishUpload(uint32_t fileLength)
{
// Write the remaining data
if (uploadState == uploadOK)
{
while (uploadLength > 0)
{
unsigned int len = min<unsigned int>(uploadLength, 256);
if (!fileBeingUploaded.Write(uploadPointer, len))
{
uploadState = uploadError;
platform->Message(HOST_MESSAGE, "Could not write remaining data while finishing upload!\n");
break;
}
uploadLength -= len;
uploadPointer += len;
}
}
uploadPointer = NULL;
uploadLength = 0;
if (uploadState == uploadOK && !fileBeingUploaded.Flush())
{
uploadState = uploadError;
platform->Message(HOST_MESSAGE, "Could not flush remaining data while finishing upload!\n");
}
// Check the file length is as expected
if (uploadState == uploadOK && fileLength != 0 && fileBeingUploaded.Length() != fileLength)
{
uploadState = uploadError;
platform->Message(HOST_MESSAGE, "Uploaded file size is different (%u vs. expected %u Bytes)!\n", fileBeingUploaded.Length(), fileLength);
}
// Close the file
if (!fileBeingUploaded.Close())
{
uploadState = uploadError;
platform->Message(HOST_MESSAGE, "Could not close the upload file while finishing upload!\n");
}
// Delete file if an error has occurred
if (uploadState == uploadError && strlen(filenameBeingUploaded) != 0)
{
platform->GetMassStorage()->Delete("0:/", filenameBeingUploaded);
}
filenameBeingUploaded[0] = 0;
}
//********************************************************************************************
//
// *********************** HTTP interpreter for the Webserver class **************************
//
//********************************************************************************************
Webserver::HttpInterpreter::HttpInterpreter(Platform *p, Webserver *ws, Network *n)
: ProtocolInterpreter(p, ws, n), state(doingCommandWord)
{
uploadingTextData = false;
numContinuationBytes = 0;
}
// File Uploads
bool Webserver::HttpInterpreter::DoFastUpload()
{
bool success = ProtocolInterpreter::DoFastUpload();
uploadedBytes += uploadLength;
// See if we can finish it this time
if (uploadedBytes >= postFileLength)
{
// Reset POST upload state for this client
uint32_t remoteIP = network->GetTransaction()->GetRemoteIP();
for(size_t i=0; i<numActiveSessions; i++)
{
if (sessions[i].ip == remoteIP && sessions[i].isPostUploading)
{
sessions[i].isPostUploading = false;
break;
}
}
// We're done, flush the remaining upload data and send the JSON response
FinishUpload(postFileLength);
SendJsonResponse("upload");
uploadState = notUploading;
}
return success;
}
bool Webserver::HttpInterpreter::DoingFastUpload() const
{
if (state == doingPost)
{
// Always finish the current request before checking for fast POST uploads
return false;
}
uint32_t remoteIP = network->GetTransaction()->GetRemoteIP();
uint16_t remotePort = network->GetTransaction()->GetRemotePort();
for(size_t i=0; i<numActiveSessions; i++)
{
if (sessions[i].ip == remoteIP && sessions[i].isPostUploading)
{
return (remotePort == sessions[i].postPort);
}
}
return false;
}
bool Webserver::HttpInterpreter::StartUpload(FileStore *file)
{
numContinuationBytes = 0;
return ProtocolInterpreter::StartUpload(file);
}
bool Webserver::HttpInterpreter::StoreUploadData(const char* data, unsigned int len)
{
if (uploadState == uploadOK)
{
uploadPointer = data;
uploadLength = len;
// Count the number of UTF8 continuation bytes. We may need it to adjust the expected file length.
if (uploadingTextData)
{
while (len != 0)
{
if ((*data & 0xC0) == 0x80)
{
++numContinuationBytes;
}
++data;
--len;
}
}
return true;
}
return false;
}
void Webserver::HttpInterpreter::CancelUpload()
{
CancelUpload(network->GetTransaction()->GetRemoteIP());
}
void Webserver::HttpInterpreter::CancelUpload(uint32_t remoteIP)
{
for(size_t i=0; i<numActiveSessions; i++)
{
if (sessions[i].ip == remoteIP && sessions[i].isPostUploading)
{
sessions[i].isPostUploading = false;
sessions[i].lastQueryTime = platform->Time();
break;
}
}
ProtocolInterpreter::CancelUpload();
}
// Output to the client
// Start sending a file or a JSON response.
void Webserver::HttpInterpreter::SendFile(const char* nameOfFileToSend)
{
if (StringEquals(nameOfFileToSend, "/"))
{
nameOfFileToSend = INDEX_PAGE;
}
FileStore *fileToSend = platform->GetFileStore(platform->GetWebDir(), nameOfFileToSend, false);
if (fileToSend == NULL)
{
nameOfFileToSend = FOUR04_FILE;
fileToSend = platform->GetFileStore(platform->GetWebDir(), nameOfFileToSend, false);
if (fileToSend == NULL)
{
RejectMessage("not found", 404);
return;
}
}
NetworkTransaction *req = network->GetTransaction();
req->Write("HTTP/1.1 200 OK\n");
const char* contentType;
bool zip = false;
if (StringEndsWith(nameOfFileToSend, ".png"))
{
contentType = "image/png";
}
else if (StringEndsWith(nameOfFileToSend, ".ico"))
{
contentType = "image/x-icon";
}
else if (StringEndsWith(nameOfFileToSend, ".js"))
{
contentType = "application/javascript";
}
else if (StringEndsWith(nameOfFileToSend, ".css"))
{
contentType = "text/css";
}
else if (StringEndsWith(nameOfFileToSend, ".htm") || StringEndsWith(nameOfFileToSend, ".html"))
{
contentType = "text/html";
}
else if (StringEndsWith(nameOfFileToSend, ".zip"))
{
contentType = "application/zip";
zip = true;
}
else
{
contentType = "application/octet-stream";
}
req->Printf("Content-Type: %s\n", contentType);
if (zip && fileToSend != NULL)
{
req->Write("Content-Encoding: gzip\n");
req->Printf("Content-Length: %lu", fileToSend->Length());
}
req->Write("Connection: close\n\n");
network->SendAndClose(fileToSend);
}
void Webserver::HttpInterpreter::SendGCodeReply()
{
NetworkTransaction *req = network->GetTransaction();
req->Write("HTTP/1.1 200 OK\n");
req->Write("Content-Type: text/plain\n");
req->Printf("Content-Length: %u\n", reprap.GetGcodeReply().strlen());
req->Write("Connection: close\n\n");
req->Write(reprap.GetGcodeReply());
network->SendAndClose(NULL);
}
void Webserver::HttpInterpreter::SendJsonResponse(const char* command)
{
// rr_reply is treated differently, because it (currently) responds as "text/plain"
if (IsAuthenticated() && StringEquals(command, "reply"))
{
SendGCodeReply();
return;
}
// See if we can find a suitable JSON response
NetworkTransaction *req = network->GetTransaction();
bool keepOpen = false;
bool mayKeepOpen;
bool found;
char jsonResponseBuffer[jsonReplyLength];
StringRef jsonResponse(jsonResponseBuffer, ARRAY_SIZE(jsonResponseBuffer));
if (numQualKeys == 0)
{
found = GetJsonResponse(command, jsonResponse, "", "", 0, mayKeepOpen);
}
else
{
found = GetJsonResponse(command, jsonResponse, qualifiers[0].key, qualifiers[0].value, qualifiers[1].key - qualifiers[0].value - 1, mayKeepOpen);
}
if (found)
{
jsonResponseBuffer[ARRAY_UPB(jsonResponseBuffer)] = 0;
if (reprap.Debug(moduleWebserver))
{
platform->Message(HOST_MESSAGE, "JSON response: %s queued\n", jsonResponseBuffer);
}
}
else
{
jsonResponseBuffer[0] = 0;
platform->Message(HOST_MESSAGE, "KnockOut request: %s not recognised\n", command);
}
if (mayKeepOpen)
{
// Check that the browser wants to persist the connection too
for (size_t i = 0; i < numHeaderKeys; ++i)
{
if (StringEquals(headers[i].key, "Connection"))
{
// Comment out the following line to disable persistent connections
keepOpen = StringEquals(headers[i].value, "keep-alive");
break;
}
}
}
req->Write("HTTP/1.1 200 OK\n");
req->Write("Content-Type: application/json\n");
req->Printf("Content-Length: %u\n", jsonResponse.strlen());
req->Printf("Connection: %s\n\n", keepOpen ? "keep-alive" : "close");
req->Write(jsonResponse);
network->SendAndClose(NULL, keepOpen);
}
//----------------------------------------------------------------------------------------------------
// Input from the client
// Get the Json response for this command.
// 'value' is null-terminated, but we also pass its length in case it contains embedded nulls, which matters when uploading files.
bool Webserver::HttpInterpreter::GetJsonResponse(const char* request, StringRef& response, const char* key, const char* value, size_t valueLength, bool& keepOpen)
{
keepOpen = false; // assume we don't want to persist the connection
bool found = true; // assume success
if (!IsAuthenticated() && reprap.NoPasswordSet())
{
// Try to allocate a new HTTP session even if this is no connect request,
// because we may need to know if a POST upload is in progress.
Authenticate();
}
if (StringEquals(request, "connect") && StringEquals(key, "password"))
{
if (IsAuthenticated())
{
// This IP is already authenticated, no need to check the password again
response.copy("{\"err\":0}");
}
else if (reprap.CheckPassword(value))
{
if (Authenticate())
{
// This is only possible if we have at least one HTTP session left
response.copy("{\"err\":0}");
}
else
{
// Otherwise report an error
response.copy("{\"err\":2}");
}
}
else
{
// Wrong password
response.copy("{\"err\":1}");
}
}
else if (!IsAuthenticated())
{
// Don't respond if this IP is not authenticated
found = false;
}
else
{
UpdateAuthentication();
if (StringEquals(request, "disconnect"))
{
RemoveAuthentication();
response.copy("{\"err\":0}");
}
else if (StringEquals(request, "status"))
{
int type = 0;
if (StringEquals(key, "type"))
{
// New-style JSON status responses
type = atoi(value);
if (type < 1 || type > 3)
{
type = 1;
}
reprap.GetStatusResponse(response, type, true);
}
else
{
// Deprecated
reprap.GetLegacyStatusResponse(response, 1, 0);
}
}
else if (StringEquals(request, "gcode") && StringEquals(key, "gcode"))
{
webserver->LoadGcodeBuffer(value);
response.printf("{\"buff\":%u}", webserver->GetGcodeBufferSpace());
}
else if (StringEquals(request, "upload"))