-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathWorkerThread.cpp
More file actions
3554 lines (2977 loc) · 134 KB
/
Copy pathWorkerThread.cpp
File metadata and controls
3554 lines (2977 loc) · 134 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
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
/*=====================================================================
WorkerThread.cpp
------------------
Copyright Glare Technologies Limited 2018 -
=====================================================================*/
#include "WorkerThread.h"
#include "ServerWorldState.h"
#include "Server.h"
#include "Screenshot.h"
#include "SubEthTransaction.h"
#include "MeshLODGenThread.h"
#include "WorkerThreadUploadPhotoHandling.h"
#include "LLMThread.h"
#include "../webserver/LoginHandlers.h"
#include "../shared/Protocol.h"
#include "../shared/ProtocolStructs.h"
#include "../shared/UID.h"
#include "../shared/WorldObject.h"
#include "../shared/MessageUtils.h"
#include "../shared/FileTypes.h"
#include "../shared/LuaScriptEvaluator.h"
#include "../shared/ObjectEventHandlers.h"
#include <vec3.h>
#include <ConPrint.h>
#include <Clock.h>
#include <AESEncryption.h>
#include <SHA256.h>
#include <Base64.h>
#include <Exception.h>
#include <MySocket.h>
#include <URL.h>
#include <Lock.h>
#include <StringUtils.h>
#include <CryptoRNG.h>
#include <SocketBufferOutStream.h>
#include <PlatformUtils.h>
#include <KillThreadMessage.h>
#include <Parser.h>
#include <FileUtils.h>
#include <MemMappedFile.h>
#include <FileOutStream.h>
#include <FileChecksum.h>
#include <networking/RecordingSocket.h>
#include <maths/CheckedMaths.h>
#include <openssl/err.h>
#include <algorithm>
#include <RuntimeCheck.h>
#include <Timer.h>
#include <zstd.h>
static const bool VERBOSE = false;
static const int MAX_STRING_LEN = 10000;
static const bool CAPTURE_TRACES = false; // If true, records a trace of data read from the socket, for fuzz seeding.
WorkerThread::WorkerThread(const Reference<SocketInterface>& socket_, Server* server_, bool is_websocket_connection_)
: socket(socket_),
server(server_),
scratch_packet(SocketBufferOutStream::DontUseNetworkByteOrder),
fuzzing(false),
write_trace(false),
is_websocket_connection(is_websocket_connection_)
{
//if(VERBOSE) print("event_fd.efd: " + toString(event_fd.efd));
if(CAPTURE_TRACES)
socket = new RecordingSocket(socket);
}
WorkerThread::~WorkerThread()
{
}
// Checks if the resource is present on the server, if not, sends a GetFile message (or rather enqueues to send) to the client.
void WorkerThread::sendGetFileMessageIfNeeded(const URLString& resource_URL)
{
if(!ResourceManager::isValidURL(resource_URL))
throw glare::Exception("Invalid URL: '" + toStdString(resource_URL) + "'");
// If this is a web URL, then we don't need to get it from the client.
if(hasPrefix(resource_URL, "http://") || hasPrefix(resource_URL, "https://"))
return;
// See if we have this file on the server already
{
const ResourceRef resource = server->world_state->resource_manager->getExistingResourceForURL(resource_URL);
if(resource && resource->isPresent())
{
// Check hash?
// conPrintIfNotFuzzing("resource file with URL '" + toStdString(resource_URL) + "' already present on disk.");
}
else
{
conPrintIfNotFuzzing("resource with URL '" + toStdString(resource_URL) + "' not present, sending GetFile message to client.");
// We need the file from the client.
// Send the client a 'get file' message
MessageUtils::initPacket(scratch_packet, Protocol::GetFile);
scratch_packet.writeStringLengthFirst(resource_URL);
MessageUtils::updatePacketLengthField(scratch_packet);
this->enqueueDataToSend(scratch_packet);
}
}
}
static void writeErrorMessageToClient(SocketInterfaceRef& socket, const std::string& msg)
{
SocketBufferOutStream packet(SocketBufferOutStream::DontUseNetworkByteOrder);
MessageUtils::initPacket(packet, Protocol::ErrorMessageID);
packet.writeStringLengthFirst(msg);
MessageUtils::updatePacketLengthField(packet);
socket->writeData(packet.buf.data(), packet.buf.size());
socket->flush();
}
// Enqueues packet to all WorkerThreads connected to the same world.
void WorkerThread::enqueuePacketToBroadcast(const SocketBufferOutStream& packet_buffer)
{
server->enqueuePacketToBroadcastForWorld(packet_buffer, this->cur_world_state.ptr());
}
void WorkerThread::handleResourceUploadConnection()
{
//conPrintIfNotFuzzing("handleResourceUploadConnection()");
socket->flush();
try
{
const std::string username = socket->readStringLengthFirst(MAX_STRING_LEN);
const std::string password = socket->readStringLengthFirst(MAX_STRING_LEN);
//conPrintIfNotFuzzing("\tusername: '" + username + "'");
UserID client_user_id = UserID::invalidUserID();
std::string client_user_name;
{
Lock lock(server->world_state->mutex);
auto res = server->world_state->name_to_users.find(username);
if(res != server->world_state->name_to_users.end())
{
User* user = res->second.getPointer();
if(user->isPasswordValid(password))
{
// Password is valid, log user in.
client_user_id = user->id;
client_user_name = user->name;
}
}
}
// If the client connected via a websocket, they can be logged in with a session cookie.
// Note that this may only work if the websocket connects over TLS.
{
Lock lock(server->world_state->mutex);
User* cookie_logged_in_user = LoginHandlers::getLoggedInUser(*server->world_state, this->websocket_request_info);
if(cookie_logged_in_user != NULL)
{
conPrint("handleResourceUploadConnection: logged in via cookie.");
client_user_id = cookie_logged_in_user->id;
client_user_name = cookie_logged_in_user->name;
}
}
if(!client_user_id.valid())
{
conPrintIfNotFuzzing("\tLogin failed.");
socket->writeUInt32(Protocol::LogInFailure); // Note that this is not a framed message.
socket->writeStringLengthFirst("Login failed.");
socket->writeData(scratch_packet.buf.data(), scratch_packet.buf.size());
socket->flush();
return;
}
if(server->world_state->isInReadOnlyMode())
{
conPrint("\tin read only-mode..");
socket->writeUInt32(Protocol::ServerIsInReadOnlyMode); // Note that this is not a framed message.
socket->writeStringLengthFirst("Server is in read-only mode, can't upload files.");
socket->writeData(scratch_packet.buf.data(), scratch_packet.buf.size());
socket->flush();
return;
}
const URLString URL = toURLString(socket->readStringLengthFirst(MAX_STRING_LEN));
//conPrintIfNotFuzzing("\tURL: '" + URL + "'");
/*if(!ResourceManager::isValidURL(URL))
{
conPrint("Invalid URL '" + URL + "'");
throw glare::Exception("Invalid URL '" + URL + "'");
}*/
// See if we have a resource in the ResourceManager already
ResourceRef resource = server->world_state->resource_manager->getOrCreateResourceForURL(URL); // Will create a new Resource ob if not already inserted.
{
Lock lock(server->world_state->mutex);
server->world_state->addResourceAsDBDirty(resource);
}
if(resource->owner_id == UserID::invalidUserID())
{
// No such resource existed before, client may create this resource.
}
else // else if resource already existed:
{
if(resource->owner_id != client_user_id) // If this resource already exists and was created by someone else:
{
socket->writeUInt32(Protocol::NoWritePermissions); // Note that this is not a framed message.
socket->writeStringLengthFirst("Not allowed to upload resource to URL '" + URL + ", someone else created a resource at this URL already.");
socket->flush();
return;
}
}
const bool valid_extension = FileTypes::hasSupportedExtension(URL);
if(!valid_extension)
{
socket->writeUInt32(Protocol::InvalidFileType); // Note that this is not a framed message.
socket->writeStringLengthFirst("Invalid file extension.");
socket->flush();
return;
}
// resource->setState(Resource::State_Transferring); // Don't set this (for now) or we will have to handle changing it on exceptions below.
const uint64 file_len = socket->readUInt64();
//conPrintIfNotFuzzing("\tfile_len: " + toString(file_len) + " B");
if(file_len == 0)
{
socket->writeUInt32(Protocol::InvalidFileSize); // Note that this is not a framed message.
socket->writeStringLengthFirst("Invalid file len of zero.");
socket->flush();
return;
}
// TODO: cap length in a better way
if(file_len > 1000000000)
{
socket->writeUInt32(Protocol::InvalidFileSize); // Note that this is not a framed message.
socket->writeStringLengthFirst("uploaded file too large.");
socket->flush();
return;
}
// Otherwise upload is allowed:
socket->writeUInt32(Protocol::UploadAllowed);
socket->flush();
// Save to disk
const std::string local_path = server->world_state->resource_manager->pathForURL(URL);
//conPrintIfNotFuzzing("\tStreaming to disk at '" + local_path + "'...");
conPrintIfNotFuzzing("\tStreaming upload to disk at '" + local_path + "' (" + toString(file_len) + " B)...");
if(fuzzing)
{
// Don't write to disk while fuzzing.
uint64 offset = 0;
const uint64 MAX_CHUNK_SIZE = 1ull << 14;
js::Vector<uint8, 16> temp_buf(MAX_CHUNK_SIZE);
while(offset < file_len)
{
const uint64 chunk_size = myMin(file_len - offset, MAX_CHUNK_SIZE);
runtimeCheck(offset + chunk_size <= file_len);
runtimeCheck(chunk_size <= temp_buf.size());
socket->readData(temp_buf.data(), chunk_size);
offset += chunk_size;
}
}
else
{
FileOutStream file(local_path, std::ios::binary | std::ios::trunc); // Remove any existing data in the file
uint64 offset = 0;
const uint64 MAX_CHUNK_SIZE = 1ull << 14;
js::Vector<uint8, 16> temp_buf(MAX_CHUNK_SIZE);
while(offset < file_len)
{
const uint64 chunk_size = myMin(file_len - offset, MAX_CHUNK_SIZE);
runtimeCheck(offset + chunk_size <= file_len);
runtimeCheck(chunk_size <= temp_buf.size());
socket->readData(temp_buf.data(), chunk_size);
file.writeData(temp_buf.data(), chunk_size);
offset += chunk_size;
}
file.close(); // Manually call close, to check for any errors via failbit.
} // End scope for FileOutStream
conPrintIfNotFuzzing("\tReceived file with URL '" + toStdString(URL) + "' from client. (" + toString(file_len) + " B)");
// conPrintIfNotFuzzing("\t!!! file checksum: " + toString(FileChecksum::fileChecksum(local_path)));
resource->owner_id = client_user_id;
resource->setState(Resource::State_Present);
{
Lock lock(server->world_state->mutex);
server->world_state->addResourceAsDBDirty(resource);
}
// Send NewResourceOnServer message to connected clients
{
MessageUtils::initPacket(scratch_packet, Protocol::NewResourceOnServer);
scratch_packet.writeStringLengthFirst(URL);
MessageUtils::updatePacketLengthField(scratch_packet);
server->enqueuePacketToBroadcastForAllWorlds(scratch_packet);
}
// See if this is a resource that is used by an object. If so, send a message to the MeshLodGenThread to generate LOD levels and KTX versions of it if applicable.
{
std::vector<UID> ob_uids; // UIDs of objects which use this resource
{
WorldStateLock lock(server->world_state->mutex);
for(auto world_it = server->world_state->world_states.begin(); world_it != server->world_state->world_states.end(); ++world_it)
{
ServerWorldState* world = world_it->second.ptr();
DependencyURLSet URLs;
const ServerWorldState::ObjectMapType& objects = world->getObjects(lock);
for(auto it = objects.begin(); it != objects.end(); ++it)
{
const WorldObject* ob = it->second.ptr();
URLs.clear();
WorldObject::GetDependencyOptions options;
options.use_basis = false;
options.get_optimised_mesh = false;
ob->getDependencyURLSetForAllLODLevels(options, URLs);
if(URLs.count(DependencyURL(URL)) > 0) // If the object uses the resource with this URL:
{
ob_uids.push_back(ob->uid);
}
}
}
}
for(size_t i=0; i<ob_uids.size(); ++i)
{
CheckGenResourcesForObject* msg = new CheckGenResourcesForObject();
msg->ob_uid = ob_uids[i];
server->enqueueMsgForLodGenThread(msg);
}
// Textures used by e.g. an avatar need to have .basis versions generated. Instead of iterating over objects, just send a CheckGenLodResourcesForURL to MeshLodGenThread.
server->enqueueMsgForLodGenThread(new CheckGenLodResourcesForURL(URL));
}
// Connection will be closed by the client after the client has uploaded the file. Wait for the connection to close.
socket->startGracefulShutdown(); // Tell sockets lib to send a FIN packet to the client.
socket->waitForGracefulDisconnect(); // Wait for a FIN packet from the client. (indicated by recv() returning 0). We can then close the socket without going into a wait state.
}
catch(MySocketExcep& e)
{
if(e.excepType() == MySocketExcep::ExcepType_ConnectionClosedGracefully)
conPrint("Resource upload client from " + IPAddress::formatIPAddressAndPort(socket->getOtherEndIPAddress(), socket->getOtherEndPort()) + " closed connection gracefully.");
else
conPrint("Socket error: " + e.what());
}
catch(glare::Exception& e)
{
conPrintIfNotFuzzing("glare::Exception: " + e.what());
}
catch(std::bad_alloc&)
{
conPrint("WorkerThread: Caught std::bad_alloc.");
}
}
void WorkerThread::handleResourceDownloadConnection()
{
conPrintIfNotFuzzing("handleResourceDownloadConnection()");
try
{
while(!should_quit)
{
const uint32 msg_type = socket->readUInt32();
if(msg_type == Protocol::GetFiles)
{
const uint64 num_resources = socket->readUInt64();
conPrintIfNotFuzzing("Handling GetFiles:\tnum resources requested: " + toString(num_resources));
for(size_t i=0; i<num_resources; ++i)
{
const URLString URL = toURLString(socket->readStringLengthFirst(MAX_STRING_LEN));
conPrintIfNotFuzzing("\tRequested URL: '" + toStdString(URL) + "'");
if(!ResourceManager::isValidURL(URL))
{
conPrint("\tRequested URL was invalid.");
socket->writeUInt32(1); // write error msg to client
}
else
{
// conPrint("\tRequested URL was valid.");
const ResourceRef resource = server->world_state->resource_manager->getExistingResourceForURL(URL);
if(resource.isNull() || (resource->getState() != Resource::State_Present))
{
conPrintIfNotFuzzing("\tRequested URL was not present on disk.");
socket->writeUInt32(1); // write error msg to client
}
else
{
const std::string local_path = server->world_state->resource_manager->getLocalAbsPathForResource(*resource);
// conPrint("\tlocal path: '" + local_path + "'");
try
{
// Load resource off disk
MemMappedFile file(local_path);
// conPrint("\tSending file to client.");
socket->writeUInt32(0); // write OK msg to client
socket->writeUInt64(file.fileSize()); // Write file size
socket->writeData(file.fileData(), file.fileSize()); // Write file data
conPrintIfNotFuzzing("\tSent file '" + local_path + "' to client. (" + toString(file.fileSize()) + " B)");
}
catch(glare::Exception& e)
{
conPrintIfNotFuzzing("\tException while trying to load file for URL: " + e.what());
socket->writeUInt32(1); // write error msg to client
}
}
}
}
}
else if(msg_type == Protocol::CyberspaceGoodbye)
{
socket->startGracefulShutdown(); // Tell sockets lib to send a FIN packet to the client.
socket->waitForGracefulDisconnect(); // Wait for a FIN packet from the client. (indicated by recv() returning 0). We can then close the socket without going into a wait state.
return;
}
else
{
conPrintIfNotFuzzing("handleResourceDownloadConnection(): Unhandled msg type: " + toString(msg_type));
return;
}
}
}
catch(MySocketExcep& e)
{
if(e.excepType() == MySocketExcep::ExcepType_ConnectionClosedGracefully)
conPrint("Resource download client from " + IPAddress::formatIPAddressAndPort(socket->getOtherEndIPAddress(), socket->getOtherEndPort()) + " closed connection gracefully.");
else
conPrint("Socket error: " + e.what());
}
catch(glare::Exception& e)
{
conPrintIfNotFuzzing("glare::Exception: " + e.what());
}
catch(std::bad_alloc&)
{
conPrint("WorkerThread: Caught std::bad_alloc.");
}
}
void WorkerThread::handleScreenshotBotConnection()
{
conPrintIfNotFuzzing("handleScreenshotBotConnection()");
const std::string password = socket->readStringLengthFirst(10000);
if(password != server->world_state->getCredential("screenshot_bot_password"))
throw glare::Exception("screenshot bot password was not correct.");
try
{
while(!should_quit)
{
// Poll server state for a screenshot request
ScreenshotRef screenshot;
{ // lock scope
Lock lock(server->world_state->mutex);
server->world_state->last_screenshot_bot_contact_time = TimeStamp::currentTime();
// Find first screenshot in screenshots map in ScreenshotState_notdone state. NOTE: slow linear scan.
for(auto it = server->world_state->screenshots.begin(); it != server->world_state->screenshots.end(); ++it)
{
if(it->second->state == Screenshot::ScreenshotState_notdone)
{
screenshot = it->second;
break;
}
}
if(screenshot.isNull())
{
// Find first screenshot in map_tile_info map in ScreenshotState_notdone state. NOTE: slow linear scan.
for(auto it = server->world_state->map_tile_info.info.begin(); it != server->world_state->map_tile_info.info.end(); ++it)
{
TileInfo& tile_info = it->second;
if(tile_info.cur_tile_screenshot.nonNull() && tile_info.cur_tile_screenshot->state == Screenshot::ScreenshotState_notdone)
{
screenshot = tile_info.cur_tile_screenshot;
break;
}
}
}
} // End lock scope
if(screenshot.nonNull()) // If there is a screenshot to take:
{
if(!screenshot->is_map_tile)
{
socket->writeUInt32(Protocol::ScreenShotRequest);
socket->writeDouble(screenshot->cam_pos.x);
socket->writeDouble(screenshot->cam_pos.y);
socket->writeDouble(screenshot->cam_pos.z);
socket->writeDouble(screenshot->cam_angles.x);
socket->writeDouble(screenshot->cam_angles.y);
socket->writeDouble(screenshot->cam_angles.z);
socket->writeInt32(screenshot->width_px);
socket->writeInt32(screenshot->highlight_parcel_id);
}
else
{
socket->writeUInt32(Protocol::TileScreenShotRequest);
socket->writeInt32(screenshot->tile_x);
socket->writeInt32(screenshot->tile_y);
socket->writeInt32(screenshot->tile_z);
}
// Read response
const uint32 result = socket->readUInt32();
if(result == Protocol::ScreenShotSucceeded)
{
// Read screenshot data
const uint64 data_len = socket->readUInt64();
if(data_len > 100000000) // ~100MB
throw glare::Exception("data_len was too large");
conPrint("Receiving screenshot of " + toString(data_len) + " B");
std::vector<uint8> data(data_len);
socket->readData(data.data(), data_len);
conPrint("Received screenshot of " + toString(data_len) + " B");
// Generate random path
const int NUM_BYTES = 16;
uint8 pathdata[NUM_BYTES];
CryptoRNG::getRandomBytes(pathdata, NUM_BYTES);
const std::string screenshot_filename = "screenshot_" + StringUtils::convertByteArrayToHexString(pathdata, NUM_BYTES) + ".jpg";
const std::string screenshot_path = server->screenshot_dir + "/" + screenshot_filename;
// Save screenshot to path
if(!fuzzing) // Don't write to disk while fuzzing
FileUtils::writeEntireFile(screenshot_path, data);
conPrint("Saved to disk at " + screenshot_path);
// Add map tile as a resource too, for access by embedded minimap on client.
if(screenshot->is_map_tile)
{
// Copy screenshot into resource dir and add as a resource
const URLString URL = toURLString(screenshot_filename);
ResourceRef resource = server->world_state->resource_manager->getOrCreateResourceForURL(URL); // Will create a new Resource ob if not already inserted.
const std::string local_abs_path = server->world_state->resource_manager->getLocalAbsPathForResource(*resource);
FileUtils::copyFile(screenshot_path, local_abs_path);
resource->owner_id = UserID::invalidUserID();
resource->setState(Resource::State_Present);
{
Lock lock(server->world_state->mutex);
server->world_state->addResourceAsDBDirty(resource);
}
screenshot->URL = URL;
}
screenshot->state = Screenshot::ScreenshotState_done;
screenshot->local_path = screenshot_path;
{
Lock lock(server->world_state->mutex);
server->world_state->addScreenshotAsDBDirty(screenshot);
if(screenshot->is_map_tile) // If we received a tile screenshot, mark map tile info as dirty to get it saved.
server->world_state->map_tile_info.db_dirty = true;
}
}
else
throw glare::Exception("Client reported screenshot taking failed.");
}
else
{
socket->writeUInt32(Protocol::KeepAlive); // Send a keepalive message just to check the socket is still connected.
// There is no current screenshot request, sleep for a while
if(!fuzzing)
PlatformUtils::Sleep(10000);
}
}
}
catch(glare::Exception& e)
{
conPrint("handleScreenshotBotConnection: glare::Exception: " + e.what());
}
catch(std::exception& e)
{
conPrint(std::string("handleScreenshotBotConnection: Caught std::exception: ") + e.what());
}
}
void WorkerThread::handleEthBotConnection()
{
conPrintIfNotFuzzing("handleEthBotConnection()");
try
{
// Do authentication
const std::string password = socket->readStringLengthFirst(10000);
if(password != server->world_state->getCredential("eth_bot_password"))
throw glare::Exception("eth bot password was not correct.");
while(!should_quit)
{
// Poll server state for a request
SubEthTransactionRef trans;
uint64 largest_nonce_used = 0;
{ // lock scope
Lock lock(server->world_state->mutex);
server->world_state->last_eth_bot_contact_time = TimeStamp::currentTime();
// Find first transaction in New state. NOTE: slow linear scan.
for(auto it = server->world_state->sub_eth_transactions.begin(); it != server->world_state->sub_eth_transactions.end(); ++it)
{
if(it->second->state == SubEthTransaction::State_New)
{
trans = it->second;
break;
}
}
// Work out nonce to use for this transaction. First, work out largest nonce used for succesfully submitted transactions
for(auto it = server->world_state->sub_eth_transactions.begin(); it != server->world_state->sub_eth_transactions.end(); ++it)
{
if(it->second->state == SubEthTransaction::State_Completed)
largest_nonce_used = myMax(largest_nonce_used, it->second->nonce);
}
} // End lock scope
const uint64 next_nonce = myMax((uint64)server->world_state->eth_info.min_next_nonce, largest_nonce_used + 1); // min_next_nonce is to reflect any existing transactions on account
if(trans.nonNull()) // If there is a transaction to submit:
{
socket->writeUInt32(Protocol::SubmitEthTransactionRequest);
// Update transaction nonce and submitted_time
{ // lock scope
Lock lock(server->world_state->mutex);
trans->nonce = next_nonce;
trans->submitted_time = TimeStamp::currentTime();
server->world_state->addSubEthTransactionAsDBDirty(trans);
}
writeToStream(*trans, *socket);
// Read response
const uint32 result = socket->readUInt32();
if(result == Protocol::EthTransactionSubmitted)
{
const UInt256 transaction_hash = readUInt256FromStream(*socket);
conPrint("Transaction was submitted.");
// Mark parcel as minted as an NFT
{ // lock scope
WorldStateLock lock(server->world_state->mutex);
trans->state = SubEthTransaction::State_Completed; // State_Submitted;
trans->transaction_hash = transaction_hash;
server->world_state->addSubEthTransactionAsDBDirty(trans);
auto parcel_res = server->world_state->getRootWorldState()->getParcels(lock).find(trans->parcel_id);
if(parcel_res != server->world_state->getRootWorldState()->getParcels(lock).end())
{
Parcel* parcel = parcel_res->second.ptr();
parcel->nft_status = Parcel::NFTStatus_MintedNFT;
server->world_state->getRootWorldState()->addParcelAsDBDirty(parcel, lock);
server->world_state->markAsChanged();
}
} // End lock scope
}
else if(result == Protocol::EthTransactionSubmissionFailed)
{
conPrint("Transaction submission failed.");
const std::string submission_error_message = socket->readStringLengthFirst(10000);
{ // lock scope
Lock lock(server->world_state->mutex);
trans->state = SubEthTransaction::State_Submitted;
trans->transaction_hash = UInt256(0);
trans->submission_error_message = submission_error_message;
server->world_state->addSubEthTransactionAsDBDirty(trans);
}
}
else
throw glare::Exception("Client reported transaction submission failed.");
}
else
{
socket->writeUInt32(Protocol::KeepAlive); // Send a keepalive message just to check the socket is still connected.
// There is no current transaction to process, sleep for a while
if(!fuzzing)
PlatformUtils::Sleep(10000);
}
}
}
catch(glare::Exception& e)
{
conPrintIfNotFuzzing("handleEthBotConnection: glare::Exception: " + e.what());
}
catch(std::exception& e)
{
conPrint(std::string("handleEthBotConnection: Caught std::exception: ") + e.what());
}
}
static bool objectIsInParcelForWhichLoggedInUserHasWritePerms(const WorldObject& ob, const UserID& user_id, ServerWorldState& world_state, WorldStateLock& lock)
{
assert(user_id.valid());
const Vec4f ob_pos = ob.pos.toVec4fPoint();
ServerWorldState::ParcelMapType& parcels = world_state.getParcels(lock);
for(ServerWorldState::ParcelMapType::iterator it = parcels.begin(); it != parcels.end(); ++it)
{
const Parcel* parcel = it->second.ptr();
if(parcel->pointInParcel(ob_pos) && parcel->userHasWritePerms(user_id))
return true;
}
return false;
}
// Is the client connected to a world that the user is the owner of?
static bool connectedToUsersWorld(const UserID& user_id, ServerWorldState& connected_world)
{
assert(user_id.valid());
return connected_world.details.owner_id == user_id;
}
// NOTE: world state mutex should be locked before calling this method.
static bool userHasObjectWritePermissions(const WorldObject& ob, const UserID& user_id, const std::string& user_name, ServerWorldState& world_state, bool allow_light_mapper_bot_full_perms,
WorldStateLock& lock)
{
if(user_id.valid())
{
return (user_id == ob.creator_id) || // If the user created/owns the object
isGodUser(user_id) || // or if the user is the god user (id 0)
(allow_light_mapper_bot_full_perms && (user_name == "lightmapperbot")) || // lightmapper bot has full write permissions for now.
connectedToUsersWorld(user_id, world_state) || // or if the user owns this world
objectIsInParcelForWhichLoggedInUserHasWritePerms(ob, user_id, world_state, lock); // Can modify objects owned by other people if they are in parcels you have write permissions for.
}
else
return false;
}
static bool userConnectedToTheirWorldOrGodUser(const UserID& user_id, ServerWorldState& connected_world)
{
return isGodUser(user_id) || // if the user is the god user (id 0)
connectedToUsersWorld(user_id, connected_world); // or if this is the user's world
}
// Does the user have permission to create a summoned object (e.g. summoned vehicle)?
// For now just check the SUMMONED_FLAG and check the model URL is one of the vehicle model URLs from GUIClient.cpp.
static bool userCanCreateSummonedObject(const WorldObject& ob, const UserID& user_id)
{
if(BitUtils::isBitSet(ob.flags, WorldObject::SUMMONED_FLAG))
{
if(ob.model_url == "deLorean2_0_glb_5923323464955550713.bmesh" || // car
ob.model_url == "optimized_dressed_fix7_offset4_glb_4474648345850208925.bmesh" || // bike
ob.model_url == "peugot_closed_glb_2887717763908023194.bmesh" || // hovercar
ob.model_url == "poweryacht3_2_glb_17116251394697619807.bmesh" || // boat
ob.model_url == "Jet_Ski_obj_3200017390617214853.bmesh") // jetski
return true;
else
return false;
}
else
return false;
}
// Does the user have permission to create the given object with its current transformation?
// NOTE: world state mutex should be locked before calling this method.
static bool userHasObjectCreationPermissions(const WorldObject& ob, const UserID& user_id, ServerWorldState& world_state, WorldStateLock& lock)
{
if(user_id.valid())
{
return isGodUser(user_id) || // if the user is the god user
connectedToUsersWorld(user_id, world_state) || // or if this is the user's world
objectIsInParcelForWhichLoggedInUserHasWritePerms(ob, user_id, world_state, lock) || // Or this object is in a parcel we have write permissions for.
userCanCreateSummonedObject(ob, user_id);
}
else
return false;
}
// This is for editing the parcel itself.
// NOTE: world state mutex should be locked before calling this method.
static bool userHasParcelWritePermissions(const Parcel& parcel, const UserID& user_id, ServerWorldState& world_state)
{
if(user_id.valid())
{
return (user_id == parcel.owner_id) || // If the user created/owns the object
isGodUser(user_id); // or if the user is the god user (id 0)
// TODO: Add if user is a parcel admin also?
}
else
return false;
}
static float maxAudioVolumeForObject(const WorldObject& ob, const UserID& user_id, ServerWorldState& connected_world)
{
return userConnectedToTheirWorldOrGodUser(user_id, connected_world) ? 1000.f : 4.f;
}
static const float chunk_w = 128;
static void markLODChunkAsNeedsRebuildForChangedObject(ServerWorldState* world_state, const WorldObject* ob, WorldStateLock& lock)
{
if(!BitUtils::isBitSet(ob->flags, WorldObject::EXCLUDE_FROM_LOD_CHUNK_MESH))
{
const Vec4f centroid = ob->getCentroidWS();
const int chunk_x = Maths::floorToInt(centroid[0] / chunk_w);
const int chunk_y = Maths::floorToInt(centroid[1] / chunk_w);
const Vec3i chunk_coords(chunk_x, chunk_y, 0);
auto res = world_state->getLODChunks(lock).find(chunk_coords);
if(res != world_state->getLODChunks(lock).end())
{
if(!res->second->needs_rebuild)
{
// conPrint("Marking LODChunk " + chunk_coords.toString() + " as needs_rebuild=true");
res->second->needs_rebuild = true;
}
}
}
}
static void compressWithZstd(const void* src, size_t src_size, int compression_level, js::Vector<uint8, 16>& compressed_data_out)
{
// Compress packet to temp_buf
const size_t compressed_bound = ZSTD_compressBound(src_size);
compressed_data_out.resizeNoCopy(compressed_bound);
const size_t compressed_size = ZSTD_compress(/*dest=*/compressed_data_out.data(), /*dest capacity=*/compressed_data_out.size(), /*src=*/src, /*src size=*/src_size, compression_level);
if(ZSTD_isError(compressed_size))
throw glare::Exception(std::string("Zstd Compression failed: ") + ZSTD_getErrorName(compressed_size));
compressed_data_out.resize(compressed_size);
}
// Sends a bunch of data about a particular world to the client.
// Called when the client connects initially, or when the client changes the current world.
void WorkerThread::sendPerWorldInitialDataToClient(ServerAllWorldsState* world_state,
uint32 client_protocol_version)
{
runtimeCheck(cur_world_state.nonNull());
// Send world settings to client
{
MessageUtils::initPacket(scratch_packet, Protocol::WorldSettingsInitialSendMessage);
{
Lock lock(world_state->mutex);
cur_world_state->world_settings.writeToStream(scratch_packet);
}
MessageUtils::updatePacketLengthField(scratch_packet);
socket->writeData(scratch_packet.buf.data(), scratch_packet.buf.size());
}
// Send the current world details (contains world name, owner, description etc. to client)
{
MessageUtils::initPacket(scratch_packet, Protocol::WorldDetailsInitialSendMessage);
{
Lock lock(world_state->mutex);
cur_world_state->details.writeToNetworkStream(scratch_packet);
}
MessageUtils::updatePacketLengthField(scratch_packet);
socket->writeData(scratch_packet.buf.data(), scratch_packet.buf.size());
}
// Send all current avatar state data to client
{
SocketBufferOutStream packet(SocketBufferOutStream::DontUseNetworkByteOrder);
{ // Lock scope
WorldStateLock lock(world_state->mutex);
const ServerWorldState::AvatarMapType& avatars = cur_world_state->getAvatars(lock);
for(auto it = avatars.begin(); it != avatars.end(); ++it)
{
const Avatar* avatar = it->second.getPointer();
// Write AvatarIsHere message
MessageUtils::initPacket(scratch_packet, Protocol::AvatarIsHere);
writeAvatarToNetworkStream(*avatar, scratch_packet);
MessageUtils::updatePacketLengthField(scratch_packet);
packet.writeData(scratch_packet.buf.data(), scratch_packet.buf.size());
// If the avatar is playing a gesture currently, send an AvatarPerformGesture message for it
if(!avatar->current_gesture_URL.empty())
{
// Enqueue AvatarPerformGesture messages to worker threads to send
MessageUtils::initPacket(scratch_packet, Protocol::AvatarPerformGesture);
writeToStream(avatar->uid, scratch_packet);
scratch_packet.writeStringLengthFirst(avatar->current_gesture_name);
scratch_packet.writeStringLengthFirst(avatar->current_gesture_URL);
scratch_packet.writeUInt32(avatar->current_gesture_flags);
scratch_packet.writeDouble(avatar->current_gesture_start_global_time);
MessageUtils::updatePacketLengthField(scratch_packet);
packet.writeData(scratch_packet.buf.data(), scratch_packet.buf.size());
}
// If the avatar is sitting on a seat, send an AvatarSatOnSeat messages. This is so avatars already sitting on seats when this new users joins will be seen to be sitting on seats.
if(avatar->sitting_on_seat_uid.valid())
{
// Write AvatarSatOnSeat message. NOTE: we may want to replace this with a AvatarIsSittingOnSeat message at some point.
MessageUtils::initPacket(scratch_packet, Protocol::AvatarSatOnSeat);
writeToStream(avatar->uid, scratch_packet);
writeToStream(avatar->sitting_on_seat_uid, scratch_packet);
MessageUtils::updatePacketLengthField(scratch_packet);
packet.writeData(scratch_packet.buf.data(), scratch_packet.buf.size());
}
}
} // End lock scope
socket->writeData(packet.buf.data(), packet.buf.size());
}
// Send all current object data to client