OpenTTD
network_client.cpp
Go to the documentation of this file.
1 /* $Id$ */
2 
3 /*
4  * This file is part of OpenTTD.
5  * OpenTTD 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, version 2.
6  * OpenTTD 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.
7  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8  */
9 
12 #include "../stdafx.h"
13 #include "network_gui.h"
14 #include "../saveload/saveload.h"
15 #include "../saveload/saveload_filter.h"
16 #include "../command_func.h"
17 #include "../console_func.h"
18 #include "../strings_func.h"
19 #include "../window_func.h"
20 #include "../company_func.h"
21 #include "../company_base.h"
22 #include "../company_gui.h"
23 #include "../core/random_func.hpp"
24 #include "../date_func.h"
25 #include "../gfx_func.h"
26 #include "../error.h"
27 #include "../rev.h"
28 #include "network.h"
29 #include "network_base.h"
30 #include "network_client.h"
31 #include "../core/backup_type.hpp"
32 #include "../thread.h"
33 
34 #include "table/strings.h"
35 
36 #include "../safeguards.h"
37 
38 /* This file handles all the client-commands */
39 
40 
43  static const size_t CHUNK = 32 * 1024;
44 
45  std::vector<byte *> blocks;
46  byte *buf;
47  byte *bufe;
48  byte **block;
49  size_t written_bytes;
50  size_t read_bytes;
51 
53  PacketReader() : LoadFilter(nullptr), buf(nullptr), bufe(nullptr), block(nullptr), written_bytes(0), read_bytes(0)
54  {
55  }
56 
57  ~PacketReader() override
58  {
59  for (auto p : this->blocks) {
60  free(p);
61  }
62  }
63 
68  void AddPacket(const Packet *p)
69  {
70  assert(this->read_bytes == 0);
71 
72  size_t in_packet = p->size - p->pos;
73  size_t to_write = min((size_t)(this->bufe - this->buf), in_packet);
74  const byte *pbuf = p->buffer + p->pos;
75 
76  this->written_bytes += in_packet;
77  if (to_write != 0) {
78  memcpy(this->buf, pbuf, to_write);
79  this->buf += to_write;
80  }
81 
82  /* Did everything fit in the current chunk, then we're done. */
83  if (to_write == in_packet) return;
84 
85  /* Allocate a new chunk and add the remaining data. */
86  pbuf += to_write;
87  to_write = in_packet - to_write;
88  this->blocks.push_back(this->buf = CallocT<byte>(CHUNK));
89  this->bufe = this->buf + CHUNK;
90 
91  memcpy(this->buf, pbuf, to_write);
92  this->buf += to_write;
93  }
94 
95  size_t Read(byte *rbuf, size_t size) override
96  {
97  /* Limit the amount to read to whatever we still have. */
98  size_t ret_size = size = min(this->written_bytes - this->read_bytes, size);
99  this->read_bytes += ret_size;
100  const byte *rbufe = rbuf + ret_size;
101 
102  while (rbuf != rbufe) {
103  if (this->buf == this->bufe) {
104  this->buf = *this->block++;
105  this->bufe = this->buf + CHUNK;
106  }
107 
108  size_t to_write = min(this->bufe - this->buf, rbufe - rbuf);
109  memcpy(rbuf, this->buf, to_write);
110  rbuf += to_write;
111  this->buf += to_write;
112  }
113 
114  return ret_size;
115  }
116 
117  void Reset() override
118  {
119  this->read_bytes = 0;
120 
121  this->block = this->blocks.data();
122  this->buf = *this->block++;
123  this->bufe = this->buf + CHUNK;
124  }
125 };
126 
127 
132 {
134  if (!_networking) return;
135 
136  const char *filename = "netsave.sav";
137  DEBUG(net, 0, "Client: Performing emergency save (%s)", filename);
138  SaveOrLoad(filename, SLO_SAVE, DFT_GAME_FILE, AUTOSAVE_DIR, false);
139 }
140 
141 
146 ClientNetworkGameSocketHandler::ClientNetworkGameSocketHandler(SOCKET s) : NetworkGameSocketHandler(s), savegame(nullptr), status(STATUS_INACTIVE)
147 {
150 }
151 
154 {
157 
158  delete this->savegame;
159 }
160 
162 {
163  assert(status != NETWORK_RECV_STATUS_OKAY);
164  /*
165  * Sending a message just before leaving the game calls cs->SendPackets.
166  * This might invoke this function, which means that when we close the
167  * connection after cs->SendPackets we will close an already closed
168  * connection. This handles that case gracefully without having to make
169  * that code any more complex or more aware of the validity of the socket.
170  */
171  if (this->sock == INVALID_SOCKET) return status;
172 
173  DEBUG(net, 1, "Closed client connection %d", this->client_id);
174 
175  this->SendPackets(true);
176 
177  /* Wait a number of ticks so our leave message can reach the server.
178  * This is especially needed for Windows servers as they seem to get
179  * the "socket is closed" message before receiving our leave message,
180  * which would trigger the server to close the connection as well. */
182 
183  delete this->GetInfo();
184  delete this;
185 
186  return status;
187 }
188 
194 {
195  /* First, send a CLIENT_ERROR to the server, so he knows we are
196  * disconnection (and why!) */
197  NetworkErrorCode errorno;
198 
199  /* We just want to close the connection.. */
200  if (res == NETWORK_RECV_STATUS_CLOSE_QUERY) {
202  this->CloseConnection(res);
203  _networking = false;
204 
206  return;
207  }
208 
209  switch (res) {
210  case NETWORK_RECV_STATUS_DESYNC: errorno = NETWORK_ERROR_DESYNC; break;
211  case NETWORK_RECV_STATUS_SAVEGAME: errorno = NETWORK_ERROR_SAVEGAME_FAILED; break;
212  case NETWORK_RECV_STATUS_NEWGRF_MISMATCH: errorno = NETWORK_ERROR_NEWGRF_MISMATCH; break;
213  default: errorno = NETWORK_ERROR_GENERAL; break;
214  }
215 
216  /* This means we fucked up and the server closed the connection */
219  SendError(errorno);
220  }
221 
223 
225  this->CloseConnection(res);
226  _networking = false;
227 }
228 
229 
236 {
237  if (my_client->CanSendReceive()) {
239  if (res != NETWORK_RECV_STATUS_OKAY) {
240  /* The client made an error of which we can not recover.
241  * Close the connection and drop back to the main menu. */
242  my_client->ClientError(res);
243  return false;
244  }
245  }
246  return _networking;
247 }
248 
251 {
254 }
255 
261 {
262  _frame_counter++;
263 
265 
266  extern void StateGameLoop();
267  StateGameLoop();
268 
269  /* Check if we are in sync! */
270  if (_sync_frame != 0) {
271  if (_sync_frame == _frame_counter) {
272 #ifdef NETWORK_SEND_DOUBLE_SEED
273  if (_sync_seed_1 != _random.state[0] || _sync_seed_2 != _random.state[1]) {
274 #else
275  if (_sync_seed_1 != _random.state[0]) {
276 #endif
277  NetworkError(STR_NETWORK_ERROR_DESYNC);
278  DEBUG(desync, 1, "sync_err: %08x; %02x", _date, _date_fract);
279  DEBUG(net, 0, "Sync error detected!");
281  return false;
282  }
283 
284  /* If this is the first time we have a sync-frame, we
285  * need to let the server know that we are ready and at the same
286  * frame as he is.. so we can start playing! */
287  if (_network_first_time) {
288  _network_first_time = false;
289  SendAck();
290  }
291 
292  _sync_frame = 0;
293  } else if (_sync_frame < _frame_counter) {
294  DEBUG(net, 1, "Missed frame for sync-test (%d / %d)", _sync_frame, _frame_counter);
295  _sync_frame = 0;
296  }
297  }
298 
299  return true;
300 }
301 
302 
305 
307 static uint32 last_ack_frame;
308 
310 static uint32 _password_game_seed;
313 
318 
321 
323 const char *_network_join_server_password = nullptr;
325 const char *_network_join_company_password = nullptr;
326 
329 
330 /***********
331  * Sending functions
332  * DEF_CLIENT_SEND_COMMAND has no parameters
333  ************/
334 
337 {
339  _network_join_status = NETWORK_JOIN_STATUS_GETTING_COMPANY_INFO;
341 
343  my_client->SendPacket(p);
345 }
346 
349 {
351  _network_join_status = NETWORK_JOIN_STATUS_AUTHORIZING;
353 
354  Packet *p = new Packet(PACKET_CLIENT_JOIN);
356  p->Send_uint32(_openttd_newgrf_version);
357  p->Send_string(_settings_client.network.client_name); // Client name
358  p->Send_uint8 (_network_join_as); // PlayAs
359  p->Send_uint8 (NETLANG_ANY); // Language
360  my_client->SendPacket(p);
362 }
363 
366 {
368  my_client->SendPacket(p);
370 }
371 
377 {
379  p->Send_string(password);
380  my_client->SendPacket(p);
382 }
383 
389 {
391  p->Send_string(GenerateCompanyPasswordHash(password, _password_server_id, _password_game_seed));
392  my_client->SendPacket(p);
394 }
395 
398 {
400 
402  my_client->SendPacket(p);
404 }
405 
408 {
410 
412  my_client->SendPacket(p);
414 }
415 
418 {
419  Packet *p = new Packet(PACKET_CLIENT_ACK);
420 
422  p->Send_uint8 (my_client->token);
423  my_client->SendPacket(p);
425 }
426 
432 {
434  my_client->NetworkGameSocketHandler::SendCommand(p, cp);
435 
436  my_client->SendPacket(p);
438 }
439 
441 NetworkRecvStatus ClientNetworkGameSocketHandler::SendChat(NetworkAction action, DestType type, int dest, const char *msg, int64 data)
442 {
443  Packet *p = new Packet(PACKET_CLIENT_CHAT);
444 
445  p->Send_uint8 (action);
446  p->Send_uint8 (type);
447  p->Send_uint32(dest);
448  p->Send_string(msg);
449  p->Send_uint64(data);
450 
451  my_client->SendPacket(p);
453 }
454 
457 {
459 
460  p->Send_uint8(errorno);
461  my_client->SendPacket(p);
463 }
464 
470 {
472 
473  p->Send_string(GenerateCompanyPasswordHash(password, _password_server_id, _password_game_seed));
474  my_client->SendPacket(p);
476 }
477 
483 {
485 
486  p->Send_string(name);
487  my_client->SendPacket(p);
489 }
490 
495 {
496  Packet *p = new Packet(PACKET_CLIENT_QUIT);
497 
498  my_client->SendPacket(p);
500 }
501 
507 NetworkRecvStatus ClientNetworkGameSocketHandler::SendRCon(const char *pass, const char *command)
508 {
509  Packet *p = new Packet(PACKET_CLIENT_RCON);
510  p->Send_string(pass);
511  p->Send_string(command);
512  my_client->SendPacket(p);
514 }
515 
522 {
523  Packet *p = new Packet(PACKET_CLIENT_MOVE);
524  p->Send_uint8(company);
525  p->Send_string(GenerateCompanyPasswordHash(password, _password_server_id, _password_game_seed));
526  my_client->SendPacket(p);
528 }
529 
535 {
536  return my_client != nullptr && my_client->status == STATUS_ACTIVE;
537 }
538 
539 
540 /***********
541  * Receiving functions
542  * DEF_CLIENT_RECEIVE_COMMAND has parameter: Packet *p
543  ************/
544 
545 extern bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = nullptr);
546 
548 {
549  /* We try to join a server which is full */
550  ShowErrorMessage(STR_NETWORK_ERROR_SERVER_FULL, INVALID_STRING_ID, WL_CRITICAL);
552 
554 }
555 
557 {
558  /* We try to join a server where we are banned */
559  ShowErrorMessage(STR_NETWORK_ERROR_SERVER_BANNED, INVALID_STRING_ID, WL_CRITICAL);
561 
563 }
564 
566 {
568 
569  byte company_info_version = p->Recv_uint8();
570 
571  if (!this->HasClientQuit() && company_info_version == NETWORK_COMPANY_INFO_VERSION) {
572  /* We have received all data... (there are no more packets coming) */
573  if (!p->Recv_bool()) return NETWORK_RECV_STATUS_CLOSE_QUERY;
574 
575  CompanyID current = (Owner)p->Recv_uint8();
576  if (current >= MAX_COMPANIES) return NETWORK_RECV_STATUS_CLOSE_QUERY;
577 
578  NetworkCompanyInfo *company_info = GetLobbyCompanyInfo(current);
579  if (company_info == nullptr) return NETWORK_RECV_STATUS_CLOSE_QUERY;
580 
581  p->Recv_string(company_info->company_name, sizeof(company_info->company_name));
582  company_info->inaugurated_year = p->Recv_uint32();
583  company_info->company_value = p->Recv_uint64();
584  company_info->money = p->Recv_uint64();
585  company_info->income = p->Recv_uint64();
586  company_info->performance = p->Recv_uint16();
587  company_info->use_password = p->Recv_bool();
588  for (uint i = 0; i < NETWORK_VEH_END; i++) {
589  company_info->num_vehicle[i] = p->Recv_uint16();
590  }
591  for (uint i = 0; i < NETWORK_VEH_END; i++) {
592  company_info->num_station[i] = p->Recv_uint16();
593  }
594  company_info->ai = p->Recv_bool();
595 
596  p->Recv_string(company_info->clients, sizeof(company_info->clients));
597 
599 
601  }
602 
604 }
605 
606 /* This packet contains info about the client (playas and name)
607  * as client we save this in NetworkClientInfo, linked via 'client_id'
608  * which is always an unique number on a server. */
610 {
611  NetworkClientInfo *ci;
613  CompanyID playas = (CompanyID)p->Recv_uint8();
614  char name[NETWORK_NAME_LENGTH];
615 
616  p->Recv_string(name, sizeof(name));
617 
619  if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;
620 
621  ci = NetworkClientInfo::GetByClientID(client_id);
622  if (ci != nullptr) {
623  if (playas == ci->client_playas && strcmp(name, ci->client_name) != 0) {
624  /* Client name changed, display the change */
625  NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, name);
626  } else if (playas != ci->client_playas) {
627  /* The client changed from client-player..
628  * Do not display that for now */
629  }
630 
631  /* Make sure we're in the company the server tells us to be in,
632  * for the rare case that we get moved while joining. */
633  if (client_id == _network_own_client_id) SetLocalCompany(!Company::IsValidID(playas) ? COMPANY_SPECTATOR : playas);
634 
635  ci->client_playas = playas;
636  strecpy(ci->client_name, name, lastof(ci->client_name));
637 
639 
641  }
642 
643  /* There are at most as many ClientInfo as ClientSocket objects in a
644  * server. Having more info than a server can have means something
645  * has gone wrong somewhere, i.e. the server has more info than it
646  * has actual clients. That means the server is feeding us an invalid
647  * state. So, bail out! This server is broken. */
649 
650  /* We don't have this client_id yet, find an empty client_id, and put the data there */
651  ci = new NetworkClientInfo(client_id);
652  ci->client_playas = playas;
653  if (client_id == _network_own_client_id) this->SetInfo(ci);
654 
655  strecpy(ci->client_name, name, lastof(ci->client_name));
656 
658 
660 }
661 
663 {
664  static const StringID network_error_strings[] = {
665  STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_GENERAL
666  STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_DESYNC
667  STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_SAVEGAME_FAILED
668  STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_CONNECTION_LOST
669  STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_ILLEGAL_PACKET
670  STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_NEWGRF_MISMATCH
671  STR_NETWORK_ERROR_SERVER_ERROR, // NETWORK_ERROR_NOT_AUTHORIZED
672  STR_NETWORK_ERROR_SERVER_ERROR, // NETWORK_ERROR_NOT_EXPECTED
673  STR_NETWORK_ERROR_WRONG_REVISION, // NETWORK_ERROR_WRONG_REVISION
674  STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_NAME_IN_USE
675  STR_NETWORK_ERROR_WRONG_PASSWORD, // NETWORK_ERROR_WRONG_PASSWORD
676  STR_NETWORK_ERROR_SERVER_ERROR, // NETWORK_ERROR_COMPANY_MISMATCH
677  STR_NETWORK_ERROR_KICKED, // NETWORK_ERROR_KICKED
678  STR_NETWORK_ERROR_CHEATER, // NETWORK_ERROR_CHEATER
679  STR_NETWORK_ERROR_SERVER_FULL, // NETWORK_ERROR_FULL
680  STR_NETWORK_ERROR_TOO_MANY_COMMANDS, // NETWORK_ERROR_TOO_MANY_COMMANDS
681  STR_NETWORK_ERROR_TIMEOUT_PASSWORD, // NETWORK_ERROR_TIMEOUT_PASSWORD
682  STR_NETWORK_ERROR_TIMEOUT_COMPUTER, // NETWORK_ERROR_TIMEOUT_COMPUTER
683  STR_NETWORK_ERROR_TIMEOUT_MAP, // NETWORK_ERROR_TIMEOUT_MAP
684  STR_NETWORK_ERROR_TIMEOUT_JOIN, // NETWORK_ERROR_TIMEOUT_JOIN
685  };
686  assert_compile(lengthof(network_error_strings) == NETWORK_ERROR_END);
687 
689 
690  StringID err = STR_NETWORK_ERROR_LOSTCONNECTION;
691  if (error < (ptrdiff_t)lengthof(network_error_strings)) err = network_error_strings[error];
692 
694 
695  /* Perform an emergency save if we had already entered the game */
697 
699 
701 }
702 
704 {
706 
707  uint grf_count = p->Recv_uint8();
709 
710  /* Check all GRFs */
711  for (; grf_count > 0; grf_count--) {
712  GRFIdentifier c;
713  this->ReceiveGRFIdentifier(p, &c);
714 
715  /* Check whether we know this GRF */
716  const GRFConfig *f = FindGRFConfig(c.grfid, FGCM_EXACT, c.md5sum);
717  if (f == nullptr) {
718  /* We do not know this GRF, bail out of initialization */
719  char buf[sizeof(c.md5sum) * 2 + 1];
720  md5sumToString(buf, lastof(buf), c.md5sum);
721  DEBUG(grf, 0, "NewGRF %08X not found; checksum %s", BSWAP32(c.grfid), buf);
723  }
724  }
725 
726  if (ret == NETWORK_RECV_STATUS_OKAY) {
727  /* Start receiving the map */
728  return SendNewGRFsOk();
729  }
730 
731  /* NewGRF mismatch, bail out */
732  ShowErrorMessage(STR_NETWORK_ERROR_NEWGRF_MISMATCH, INVALID_STRING_ID, WL_CRITICAL);
733  return ret;
734 }
735 
737 {
738  if (this->status < STATUS_JOIN || this->status >= STATUS_AUTH_GAME) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
739  this->status = STATUS_AUTH_GAME;
740 
741  const char *password = _network_join_server_password;
742  if (!StrEmpty(password)) {
743  return SendGamePassword(password);
744  }
745 
746  ShowNetworkNeedPassword(NETWORK_GAME_PASSWORD);
747 
749 }
750 
752 {
753  if (this->status < STATUS_JOIN || this->status >= STATUS_AUTH_COMPANY) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
754  this->status = STATUS_AUTH_COMPANY;
755 
756  _password_game_seed = p->Recv_uint32();
757  p->Recv_string(_password_server_id, sizeof(_password_server_id));
759 
760  const char *password = _network_join_company_password;
761  if (!StrEmpty(password)) {
762  return SendCompanyPassword(password);
763  }
764 
765  ShowNetworkNeedPassword(NETWORK_COMPANY_PASSWORD);
766 
768 }
769 
771 {
772  if (this->status < STATUS_JOIN || this->status >= STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
773  this->status = STATUS_AUTHORIZED;
774 
776 
777  /* Initialize the password hash salting variables, even if they were previously. */
778  _password_game_seed = p->Recv_uint32();
779  p->Recv_string(_password_server_id, sizeof(_password_server_id));
780 
781  /* Start receiving the map */
782  return SendGetMap();
783 }
784 
786 {
787  /* We set the internal wait state when requesting the map. */
789 
790  /* But... only now we set the join status to waiting, instead of requesting. */
791  _network_join_status = NETWORK_JOIN_STATUS_WAITING;
794 
796 }
797 
799 {
800  if (this->status < STATUS_AUTHORIZED || this->status >= STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
801  this->status = STATUS_MAP;
802 
803  if (this->savegame != nullptr) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
804 
805  this->savegame = new PacketReader();
806 
808 
811 
812  _network_join_status = NETWORK_JOIN_STATUS_DOWNLOADING;
814 
816 }
817 
819 {
821  if (this->savegame == nullptr) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
822 
825 
827 }
828 
830 {
832  if (this->savegame == nullptr) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
833 
834  /* We are still receiving data, put it to the file */
835  this->savegame->AddPacket(p);
836 
837  _network_join_bytes = (uint32)this->savegame->written_bytes;
839 
841 }
842 
844 {
846  if (this->savegame == nullptr) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
847 
848  _network_join_status = NETWORK_JOIN_STATUS_PROCESSING;
850 
851  /*
852  * Make sure everything is set for reading.
853  *
854  * We need the local copy and reset this->savegame because when
855  * loading fails the network gets reset upon loading the intro
856  * game, which would cause us to free this->savegame twice.
857  */
858  LoadFilter *lf = this->savegame;
859  this->savegame = nullptr;
860  lf->Reset();
861 
862  /* The map is done downloading, load it */
864  bool load_success = SafeLoad(nullptr, SLO_LOAD, DFT_GAME_FILE, GM_NORMAL, NO_DIRECTORY, lf);
865 
866  /* Long savegame loads shouldn't affect the lag calculation! */
867  this->last_packet = _realtime_tick;
868 
869  if (!load_success) {
871  ShowErrorMessage(STR_NETWORK_ERROR_SAVEGAMEERROR, INVALID_STRING_ID, WL_CRITICAL);
873  }
874  /* If the savegame has successfully loaded, ALL windows have been removed,
875  * only toolbar/statusbar and gamefield are visible */
876 
877  /* Say we received the map and loaded it correctly! */
878  SendMapOk();
879 
880  /* New company/spectator (invalid company) or company we want to join is not active
881  * Switch local company to spectator and await the server's judgement */
882  if (_network_join_as == COMPANY_NEW_COMPANY || !Company::IsValidID(_network_join_as)) {
884 
885  if (_network_join_as != COMPANY_SPECTATOR) {
886  /* We have arrived and ready to start playing; send a command to make a new company;
887  * the server will give us a client-id and let us in */
888  _network_join_status = NETWORK_JOIN_STATUS_REGISTERING;
889  ShowJoinStatusWindow();
890  NetworkSendCommand(0, CCA_NEW, 0, CMD_COMPANY_CTRL, nullptr, nullptr, _local_company);
891  }
892  } else {
893  /* take control over an existing company */
894  SetLocalCompany(_network_join_as);
895  }
896 
898 }
899 
901 {
903 
906 #ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME
907  /* Test if the server supports this option
908  * and if we are at the frame the server is */
909  if (p->pos + 1 < p->size) {
911  _sync_seed_1 = p->Recv_uint32();
912 #ifdef NETWORK_SEND_DOUBLE_SEED
913  _sync_seed_2 = p->Recv_uint32();
914 #endif
915  }
916 #endif
917  /* Receive the token. */
918  if (p->pos != p->size) this->token = p->Recv_uint8();
919 
920  DEBUG(net, 5, "Received FRAME %d", _frame_counter_server);
921 
922  /* Let the server know that we received this frame correctly
923  * We do this only once per day, to save some bandwidth ;) */
924  if (!_network_first_time && last_ack_frame < _frame_counter) {
925  last_ack_frame = _frame_counter + DAY_TICKS;
926  DEBUG(net, 4, "Sent ACK at %d", _frame_counter);
927  SendAck();
928  }
929 
931 }
932 
934 {
936 
937  _sync_frame = p->Recv_uint32();
938  _sync_seed_1 = p->Recv_uint32();
939 #ifdef NETWORK_SEND_DOUBLE_SEED
940  _sync_seed_2 = p->Recv_uint32();
941 #endif
942 
944 }
945 
947 {
949 
950  CommandPacket cp;
951  const char *err = this->ReceiveCommand(p, &cp);
952  cp.frame = p->Recv_uint32();
953  cp.my_cmd = p->Recv_bool();
954 
955  if (err != nullptr) {
956  IConsolePrintF(CC_ERROR, "WARNING: %s from server, dropping...", err);
958  }
959 
960  this->incoming_queue.Append(&cp);
961 
963 }
964 
966 {
968 
969  char name[NETWORK_NAME_LENGTH], msg[NETWORK_CHAT_LENGTH];
970  const NetworkClientInfo *ci = nullptr, *ci_to;
971 
972  NetworkAction action = (NetworkAction)p->Recv_uint8();
974  bool self_send = p->Recv_bool();
976  int64 data = p->Recv_uint64();
977 
978  ci_to = NetworkClientInfo::GetByClientID(client_id);
979  if (ci_to == nullptr) return NETWORK_RECV_STATUS_OKAY;
980 
981  /* Did we initiate the action locally? */
982  if (self_send) {
983  switch (action) {
984  case NETWORK_ACTION_CHAT_CLIENT:
985  /* For speaking to client we need the client-name */
986  seprintf(name, lastof(name), "%s", ci_to->client_name);
988  break;
989 
990  /* For speaking to company or giving money, we need the company-name */
991  case NETWORK_ACTION_GIVE_MONEY:
992  if (!Company::IsValidID(ci_to->client_playas)) return NETWORK_RECV_STATUS_OKAY;
993  FALLTHROUGH;
994 
995  case NETWORK_ACTION_CHAT_COMPANY: {
996  StringID str = Company::IsValidID(ci_to->client_playas) ? STR_COMPANY_NAME : STR_NETWORK_SPECTATORS;
997  SetDParam(0, ci_to->client_playas);
998 
999  GetString(name, str, lastof(name));
1001  break;
1002  }
1003 
1004  default: return NETWORK_RECV_STATUS_MALFORMED_PACKET;
1005  }
1006  } else {
1007  /* Display message from somebody else */
1008  seprintf(name, lastof(name), "%s", ci_to->client_name);
1009  ci = ci_to;
1010  }
1011 
1012  if (ci != nullptr) {
1013  NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), self_send, name, msg, data);
1014  }
1015  return NETWORK_RECV_STATUS_OKAY;
1016 }
1017 
1019 {
1021 
1023 
1025  if (ci != nullptr) {
1026  NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, nullptr, GetNetworkErrorMsg((NetworkErrorCode)p->Recv_uint8()));
1027  delete ci;
1028  }
1029 
1031 
1032  return NETWORK_RECV_STATUS_OKAY;
1033 }
1034 
1036 {
1038 
1040 
1042  if (ci != nullptr) {
1043  NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, nullptr, STR_NETWORK_MESSAGE_CLIENT_LEAVING);
1044  delete ci;
1045  } else {
1046  DEBUG(net, 0, "Unknown client (%d) is leaving the game", client_id);
1047  }
1048 
1050 
1051  /* If we come here it means we could not locate the client.. strange :s */
1052  return NETWORK_RECV_STATUS_OKAY;
1053 }
1054 
1056 {
1058 
1060 
1062  if (ci != nullptr) {
1063  NetworkTextMessage(NETWORK_ACTION_JOIN, CC_DEFAULT, false, ci->client_name);
1064  }
1065 
1067 
1068  return NETWORK_RECV_STATUS_OKAY;
1069 }
1070 
1072 {
1073  /* Only when we're trying to join we really
1074  * care about the server shutting down. */
1075  if (this->status >= STATUS_JOIN) {
1076  ShowErrorMessage(STR_NETWORK_MESSAGE_SERVER_SHUTDOWN, INVALID_STRING_ID, WL_CRITICAL);
1077  }
1078 
1080 
1082 }
1083 
1085 {
1086  /* Only when we're trying to join we really
1087  * care about the server shutting down. */
1088  if (this->status >= STATUS_JOIN) {
1089  /* To throttle the reconnects a bit, every clients waits its
1090  * Client ID modulo 16. This way reconnects should be spread
1091  * out a bit. */
1093  ShowErrorMessage(STR_NETWORK_MESSAGE_SERVER_REBOOT, INVALID_STRING_ID, WL_CRITICAL);
1094  }
1095 
1097 
1099 }
1100 
1102 {
1104 
1105  TextColour colour_code = (TextColour)p->Recv_uint16();
1107 
1108  char rcon_out[NETWORK_RCONCOMMAND_LENGTH];
1109  p->Recv_string(rcon_out, sizeof(rcon_out));
1110 
1111  IConsolePrint(colour_code, rcon_out);
1112 
1113  return NETWORK_RECV_STATUS_OKAY;
1114 }
1115 
1117 {
1119 
1120  /* Nothing more in this packet... */
1122  CompanyID company_id = (CompanyID)p->Recv_uint8();
1123 
1124  if (client_id == 0) {
1125  /* definitely an invalid client id, debug message and do nothing. */
1126  DEBUG(net, 0, "[move] received invalid client index = 0");
1128  }
1129 
1130  const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
1131  /* Just make sure we do not try to use a client_index that does not exist */
1132  if (ci == nullptr) return NETWORK_RECV_STATUS_OKAY;
1133 
1134  /* if not valid player, force spectator, else check player exists */
1135  if (!Company::IsValidID(company_id)) company_id = COMPANY_SPECTATOR;
1136 
1137  if (client_id == _network_own_client_id) {
1138  SetLocalCompany(company_id);
1139  }
1140 
1141  return NETWORK_RECV_STATUS_OKAY;
1142 }
1143 
1145 {
1147 
1148  _network_server_max_companies = p->Recv_uint8();
1149  _network_server_max_spectators = p->Recv_uint8();
1150 
1151  return NETWORK_RECV_STATUS_OKAY;
1152 }
1153 
1155 {
1157 
1160 
1161  return NETWORK_RECV_STATUS_OKAY;
1162 }
1163 
1168 {
1169  /* Only once we're authorized we can expect a steady stream of packets. */
1170  if (this->status < STATUS_AUTHORIZED) return;
1171 
1172  /* It might... sometimes occur that the realtime ticker overflows. */
1173  if (_realtime_tick < this->last_packet) this->last_packet = _realtime_tick;
1174 
1175  /* Lag is in milliseconds; 5 seconds are roughly twice the
1176  * server's "you're slow" threshold (1 game day). */
1177  uint lag = (_realtime_tick - this->last_packet) / 1000;
1178  if (lag < 5) return;
1179 
1180  /* 20 seconds are (way) more than 4 game days after which
1181  * the server will forcefully disconnect you. */
1182  if (lag > 20) {
1184  return;
1185  }
1186 
1187  /* Prevent showing the lag message every tick; just update it when needed. */
1188  static uint last_lag = 0;
1189  if (last_lag == lag) return;
1190 
1191  last_lag = lag;
1192  SetDParam(0, lag);
1193  ShowErrorMessage(STR_NETWORK_ERROR_CLIENT_GUI_LOST_CONNECTION_CAPTION, STR_NETWORK_ERROR_CLIENT_GUI_LOST_CONNECTION, WL_INFO);
1194 }
1195 
1196 
1199 {
1200  /* Set the frame-counter to 0 so nothing happens till we are ready */
1201  _frame_counter = 0;
1203  last_ack_frame = 0;
1204  /* Request the game-info */
1206 }
1207 
1213 void NetworkClientSendRcon(const char *password, const char *command)
1214 {
1215  MyClient::SendRCon(password, command);
1216 }
1217 
1224 void NetworkClientRequestMove(CompanyID company_id, const char *pass)
1225 {
1226  MyClient::SendMove(company_id, pass);
1227 }
1228 
1234 {
1235  Backup<CompanyID> cur_company(_current_company, FILE_LINE);
1236  /* If our company is changing owner, go to spectators */
1238 
1239  NetworkClientInfo *ci;
1240  FOR_ALL_CLIENT_INFOS(ci) {
1241  if (ci->client_playas != cid) continue;
1242  NetworkTextMessage(NETWORK_ACTION_COMPANY_SPECTATOR, CC_DEFAULT, false, ci->client_name);
1244  }
1245 
1246  cur_company.Restore();
1247 }
1248 
1253 {
1255 
1256  if (ci == nullptr) return;
1257 
1258  /* Don't change the name if it is the same as the old name */
1259  if (strcmp(ci->client_name, _settings_client.network.client_name) != 0) {
1260  if (!_network_server) {
1262  } else {
1264  NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, _settings_client.network.client_name);
1267  }
1268  }
1269  }
1270 }
1271 
1280 void NetworkClientSendChat(NetworkAction action, DestType type, int dest, const char *msg, int64 data)
1281 {
1282  MyClient::SendChat(action, type, dest, msg, data);
1283 }
1284 
1289 void NetworkClientSetCompanyPassword(const char *password)
1290 {
1291  MyClient::SendSetPassword(password);
1292 }
1293 
1300 {
1301  /* Only companies actually playing can speak to team. Eg spectators cannot */
1303 
1304  const NetworkClientInfo *ci;
1305  FOR_ALL_CLIENT_INFOS(ci) {
1306  if (ci->client_playas == cio->client_playas && ci != cio) return true;
1307  }
1308 
1309  return false;
1310 }
1311 
1317 {
1319 }
1320 
1326 {
1328 }
Everything is okay.
Definition: core.h:25
Client acknowledges that it has all required NewGRFs.
Definition: tcp_game.h:58
Owner
Enum for all companies/owners.
Definition: company_type.h:20
We are trying to get company information.
NetworkRecvStatus Receive_SERVER_COMPANY_INFO(Packet *p) override
Sends information about the companies (one packet per company): uint8 Version of the structure of thi...
NetworkRecvStatus CloseConnection(bool error=true) override
Functions to help ReceivePacket/SendPacket a bit A socket can make errors.
Definition: tcp_game.cpp:42
used in multiplayer to create a new companies etc.
Definition: command_type.h:280
bool _networking
are we in networking mode?
Definition: network.cpp:54
NetworkRecvStatus Receive_SERVER_FULL(Packet *p) override
Notification that the server is full.
void NetworkSendCommand(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback, const char *text, CompanyID company)
Prepare a DoCommand to be send over the network.
char clients[NETWORK_CLIENTS_LENGTH]
The clients that control this company (Name1, name2, ..)
Definition: network_gui.h:38
bool HasClientQuit() const
Whether the current client connected to the socket has quit.
Definition: core.h:69
Container for all information known about a client.
Definition: network_base.h:25
SOCKET sock
The socket currently connected to.
Definition: tcp.h:34
uint32 _sync_seed_1
Seed to compare during sync checks.
Definition: network.cpp:73
struct PacketReader * savegame
Packet reader for reading the savegame.
uint32 _realtime_tick
The real time in the game.
Definition: debug.cpp:50
Internal entity of a packet.
Definition: packet.h:42
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3199
TextColour GetDrawStringCompanyColour(CompanyID company)
Get the colour for DrawString-subroutines which matches the colour of the company.
A client changes its name.
Definition: tcp_game.h:110
static NetworkRecvStatus SendJoin()
Tell the server we would like to join.
size_t written_bytes
The total number of bytes we&#39;ve written.
static bool Receive()
Check whether we received/can send some data from/to the server and when that&#39;s the case handle it ap...
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition: fileio_type.h:110
uint32 Recv_uint32()
Read a 32 bits integer from the packet.
Definition: packet.cpp:248
The client is authorized at the server.
NetworkRecvStatus Receive_SERVER_JOIN(Packet *p) override
A client joined (PACKET_CLIENT_MAP_OK), what usually directly follows is a PACKET_SERVER_CLIENT_INFO:...
NetworkRecvStatus ReceivePackets()
Do the actual receiving of packets.
Definition: tcp_game.cpp:134
Client list; Window numbers:
Definition: window_type.h:474
PacketSize pos
The current read/write position in the packet.
Definition: packet.h:52
NetworkRecvStatus Receive_SERVER_NEWGAME(Packet *p) override
Let the clients know that the server is loading a new map.
const char * _network_join_server_password
Login password from -p argument.
static NetworkRecvStatus SendGamePassword(const char *password)
Set the game password as requested.
Switch to game intro menu.
Definition: openttd.h:32
const char * _network_join_company_password
Company password from -P argument.
bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf=nullptr)
Load the specified savegame but on error do different things.
Definition: openttd.cpp:1003
bool ai
Is this company an AI.
Definition: network_type.h:62
static uint8 _network_server_max_spectators
Maximum number of spectators of the currently joined server.
GUIs related to networking.
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:409
void Send_string(const char *data)
Sends a string over the network.
Definition: packet.cpp:150
void ClientError(NetworkRecvStatus res)
Handle an error coming from the client side.
static NetworkRecvStatus SendMapOk()
Tell the server we received the complete map.
Something went wrong (down)loading the savegame.
Definition: core.h:28
byte ** block
The block we&#39;re reading from/writing to.
void ClientNetworkEmergencySave()
Create an emergency savegame when the network connection is lost.
NetworkErrorCode
The error codes we send around in the protocols.
Definition: network_type.h:102
NetworkRecvStatus CloseConnection(NetworkRecvStatus status) override
Close the network connection due to the given status.
char company_name[NETWORK_COMPANY_NAME_LENGTH]
Company name.
Definition: network_gui.h:31
Clients sends the (hashed) game password.
Definition: tcp_game.h:62
NetworkJoinStatus _network_join_status
The status of joining.
NetworkRecvStatus Receive_SERVER_COMMAND(Packet *p) override
Sends a DoCommand to the client: uint8 ID of the company (0..MAX_COMPANIES-1).
The client wants a new company.
Definition: company_type.h:36
void Send_uint8(uint8 data)
Package a 8 bits integer in the packet.
Definition: packet.cpp:98
char * md5sumToString(char *buf, const char *last, const uint8 md5sum[16])
Convert the md5sum to a hexadecimal string representation.
Definition: string.cpp:427
Client part of the network protocol.
void NetworkUpdateClientInfo(ClientID client_id)
Send updated client info of a particular client.
static uint8 _network_server_max_companies
Maximum number of companies of the currently joined server.
NetworkRecvStatus Receive_SERVER_CONFIG_UPDATE(Packet *p) override
Update the clients knowledge of the max settings: uint8 Maximum number of companies allowed...
void NetworkClientRequestMove(CompanyID company_id, const char *pass)
Notify the server of this client wanting to be moved to another company.
void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel wl, int x=0, int y=0, const GRFFile *textref_stack_grffile=nullptr, uint textref_stack_size=0, const uint32 *textref_stack=nullptr)
Display an error message in a window.
Definition: error_gui.cpp:382
NetworkRecvStatus Receive_SERVER_SHUTDOWN(Packet *p) override
Let the clients know that the server is closing.
static NetworkRecvStatus SendNewGRFsOk()
Tell the server we got all the NewGRFs.
static const int DAY_TICKS
1 day is 74 ticks; _date_fract used to be uint16 and incremented by 885.
Definition: date_type.h:30
void CSleep(int milliseconds)
Sleep on the current thread for a defined time.
Definition: thread.h:27
void Send_uint32(uint32 data)
Package a 32 bits integer in the packet.
Definition: packet.cpp:119
void NetworkClientSendChat(NetworkAction action, DestType type, int dest, const char *msg, int64 data)
Send a chat message.
NetworkRecvStatus Receive_SERVER_WELCOME(Packet *p) override
The client is joined and ready to receive his map: uint32 Own client ID.
#define lastof(x)
Get the last element of an fixed size array.
Definition: depend.cpp:50
NetworkRecvStatus Receive_SERVER_COMPANY_UPDATE(Packet *p) override
Update the clients knowledge of which company is password protected: uint16 Bitwise representation of...
static const TextColour CC_DEFAULT
Default colour of the console.
Definition: console_type.h:25
Money company_value
The company value.
Definition: network_gui.h:33
bool IsValidConsoleColour(TextColour c)
Check whether the given TextColour is valid for console usage.
Base core network types and some helper functions to access them.
bool NetworkMaxSpectatorsReached()
Check if max_spectatos has been reached on the server (local check only).
ClientNetworkGameSocketHandler(SOCKET s)
Create a new socket for the client side of the game connection.
static NetworkRecvStatus SendSetPassword(const char *password)
Tell the server that we like to change the password of the company.
NetworkRecvStatus Receive_SERVER_SYNC(Packet *p) override
Sends a sync-check to the client: uint32 Frame counter.
const char * GetNetworkRevisionString()
Get the network version string used by this build.
Definition: network.cpp:1111
void Append(CommandPacket *p)
Append a CommandPacket at the end of the queue.
const GRFConfig * FindGRFConfig(uint32 grfid, FindGRFConfigMode mode, const uint8 *md5sum, uint32 desired_version)
Find a NewGRF in the scanned list.
void AddPacket(const Packet *p)
Add a packet to this buffer.
Class for handling the client side of the game connection.
ClientID
&#39;Unique&#39; identifier to be given to clients
Definition: network_type.h:41
uint32 _sync_frame
The frame to perform the sync check.
Definition: network.cpp:77
The server told us we made an error.
Definition: core.h:31
The client tells the server which frame it has executed.
Definition: tcp_game.h:89
Basic data to distinguish a GRF.
Definition: newgrf_config.h:84
SendPacketsState SendPackets(bool closing_down=false)
Sends all the buffered packets out for this client.
Definition: tcp.cpp:97
File is being saved.
Definition: fileio_type.h:52
StringID GetNetworkErrorMsg(NetworkErrorCode err)
Retrieve the string id of an internal error number.
Definition: network.cpp:308
Client asks the server to execute some command.
Definition: tcp_game.h:101
Network lobby window.
Definition: window_type.h:30
The password of the company.
Definition: network_type.h:76
CommandQueue incoming_queue
The command-queue awaiting handling.
Definition: tcp_game.h:522
Class to backup a specific variable and restore it later.
Definition: backup_type.hpp:23
size_t Read(byte *rbuf, size_t size) override
Read a given number of bytes from the savegame.
static const size_t CHUNK
32 KiB chunks of memory.
uint16 num_vehicle[NETWORK_VEH_END]
How many vehicles are there of this type?
Definition: network_type.h:60
Save game or scenario file.
Definition: fileio_type.h:33
Done querying the server.
Definition: core.h:34
Interface for filtering a savegame till it is loaded.
A desync did occur.
Definition: core.h:26
Year inaugurated_year
What year the company started in.
Definition: network_gui.h:32
~ClientNetworkGameSocketHandler()
Clear whatever we assigned.
Critical errors, the MessageBox is shown in all cases.
Definition: error.h:26
void StateGameLoop()
State controlling game loop.
Definition: openttd.cpp:1335
static bool IsConnected()
Check whether the client is actually connected (and in the game).
NetworkRecvStatus Receive_SERVER_MAP_DATA(Packet *p) override
Sends the data of the map to the client: Contains a part of the map (until max size of packet)...
bool prefer_teamchat
choose the chat message target with <ENTER>, true=all clients, false=your team
static NetworkRecvStatus SendAck()
Send an acknowledgement from the server&#39;s ticks.
NetworkSettings network
settings related to the network
CompanyID client_playas
As which company is this client playing (CompanyID)
Definition: network_base.h:29
static const uint NETWORK_RCONCOMMAND_LENGTH
The maximum length of a rconsole command, in bytes including &#39;\0&#39;.
Definition: config.h:50
void Send_uint64(uint64 data)
Package a 64 bits integer in the packet.
Definition: packet.cpp:132
A client would like to be moved to another company.
Definition: tcp_game.h:105
static NetworkRecvStatus SendCompanyPassword(const char *password)
Set the company password as requested.
DateFract _date_fract
Fractional part of the day.
Definition: date.cpp:29
byte * buffer
The buffer of this packet, of basically variable length up to SEND_MTU.
Definition: packet.h:54
The client is spectating.
Definition: company_type.h:37
Information about GRF, used in the game and (part of it) in savegames.
friend void NetworkExecuteLocalCommandQueue()
Execute all commands on the local command queue that ought to be executed this frame.
char client_name[NETWORK_CLIENT_NAME_LENGTH]
Name of the client.
Definition: network_base.h:27
GameMode
Mode which defines the state of the game.
Definition: openttd.h:18
Client sends the (hashed) company password.
Definition: tcp_game.h:64
uint8 max_spectators
maximum amount of spectators
Company information stored at the client side.
Definition: network_gui.h:30
void IConsolePrint(TextColour colour_code, const char *string)
Handle the printing of text entered into the console or redirected there by any other means...
Definition: console.cpp:86
Read some packets, and when do use that data as initial load filter.
size_t read_bytes
The total number of read bytes.
void CheckConnection()
Check the connection&#39;s state, i.e.
ClientID _network_own_client_id
Our client identifier.
Definition: network.cpp:61
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:80
static NetworkRecvStatus SendError(NetworkErrorCode errorno)
Send an error-packet over the network.
void CDECL IConsolePrintF(TextColour colour_code, const char *format,...)
Handle the printing of text entered into the console or redirected there by any other means...
Definition: console.cpp:126
A path without any base directory.
Definition: fileio_type.h:127
The client is waiting as someone else is downloading the map.
void NetworkClientsToSpectators(CompanyID cid)
Move the clients of a company to the spectators.
NetworkRecvStatus Receive_SERVER_FRAME(Packet *p) override
Sends the current frame counter to the client: uint32 Frame counter uint32 Frame counter max (how far...
void SetLocalCompany(CompanyID new_company)
Sets the local company and updates the settings that are set on a per-company basis to reflect the co...
NetworkRecvStatus Receive_SERVER_CHAT(Packet *p) override
Sends a chat-packet to the client: uint8 ID of the action (see NetworkAction).
TextColour
Colour of the strings, see _string_colourmap in table/string_colours.h or docs/ottd-colourtext-palett...
Definition: gfx_type.h:247
virtual void Reset()
Reset this filter to read from the beginning of the file.
void NetworkUpdateClientName()
Send the server our name.
static const uint MILLISECONDS_PER_TICK
The number of milliseconds per game tick.
Definition: gfx_type.h:306
uint8 _network_reconnect
Reconnect timeout.
Definition: network.cpp:64
static ClientNetworkGameSocketHandler * my_client
This is us!
Subdirectory of save for autosaves.
Definition: fileio_type.h:113
NetworkRecvStatus Receive_SERVER_NEED_GAME_PASSWORD(Packet *p) override
Indication to the client that the server needs a game password.
NetworkRecvStatus
Status of a network client; reasons why a client has quit.
Definition: core.h:24
A client (re)sets its company&#39;s password.
Definition: tcp_game.h:109
void Reset() override
Reset this filter to read from the beginning of the file.
assert_compile(NETWORK_SERVER_ID_LENGTH==16 *2+1)
Make sure the server ID length is the same as a md5 hash.
#define FOR_ALL_CLIENT_INFOS(var)
Iterate over all the clients.
Definition: network_base.h:53
NetworkRecvStatus Receive_SERVER_MAP_DONE(Packet *p) override
Sends that all data of the map are sent to the client:
byte * buf
Buffer we&#39;re going to write to/read from.
std::vector< byte * > blocks
Buffer with blocks of allocated memory.
static const uint NETWORK_CHAT_LENGTH
The maximum length of a chat message, in bytes including &#39;\0&#39;.
Definition: config.h:52
We did not have the required NewGRFs.
Definition: core.h:27
Basic functions/variables used all over the place.
PacketSize size
The size of the whole packet for received packets.
Definition: packet.h:50
SaveOrLoadResult SaveOrLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, Subdirectory sb, bool threaded)
Main Save or Load function where the high-level saveload functions are handled.
Definition: saveload.cpp:2719
#define lengthof(x)
Return the length of an fixed size array.
Definition: depend.cpp:42
uint last_packet
Time we received the last frame.
Definition: tcp_game.h:523
File is being loaded.
Definition: fileio_type.h:51
static T min(const T a, const T b)
Returns the minimum of two values.
Definition: math_func.hpp:42
NetworkClientInfo * GetInfo() const
Gets the client info of this socket handler.
Definition: tcp_game.h:548
uint32 frame
the frame in which this packet is executed
ServerStatus status
Status of the connection with the server.
static NetworkRecvStatus SendRCon(const char *password, const char *command)
Send a console command.
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:18
static NetworkRecvStatus SendMove(CompanyID company, const char *password)
Ask the server to move us.
A client reports an error to the server.
Definition: tcp_game.h:121
bool Recv_bool()
Read a boolean from the packet.
Definition: packet.cpp:210
uint32 _network_join_bytes
The number of bytes we already downloaded.
SaveLoadOperation
Operation performed on the file.
Definition: fileio_type.h:49
void NetworkClient_Connected()
Is called after a client is connected to the server.
uint16 performance
What was his performance last month?
Definition: network_gui.h:36
uint8 max_companies
maximum amount of companies
bool NetworkClientPreferTeamChat(const NetworkClientInfo *cio)
Tell whether the client has team members where he/she can chat to.
The connection is &#39;just&#39; lost.
Definition: core.h:29
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:37
Network status window; Window numbers:
Definition: window_type.h:487
ClientID client_id
Client identifier.
Definition: tcp_game.h:519
NetworkRecvStatus Receive_SERVER_CLIENT_INFO(Packet *p) override
Send information about a client: uint32 ID of the client (always unique on a server.
void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
Delete a window by its class and window number (if it is open).
Definition: window.cpp:1146
The server is full.
Definition: core.h:32
static NetworkRecvStatus SendCompanyInformationQuery()
Query the server for company information.
The password of the game.
Definition: network_type.h:75
NetworkRecvStatus Receive_SERVER_RCON(Packet *p) override
Send the result of an issues RCon command back to the client: uint16 Colour code. ...
Network join status.
Definition: window_type.h:34
bool NetworkFindName(char *new_name, const char *last)
Check whether a name is unique, and otherwise try to make it unique.
uint8 Recv_uint8()
Read a 8 bits integer from the packet.
Definition: packet.cpp:219
bool use_password
Is there a password.
Definition: network_gui.h:37
char client_name[NETWORK_CLIENT_NAME_LENGTH]
name of the player (as client)
GUISettings gui
settings related to the GUI
Client requests the actual map.
Definition: tcp_game.h:71
void SetInfo(NetworkClientInfo *info)
Sets the client info for this socket handler.
Definition: tcp_game.h:538
uint32 _frame_counter
The current frame.
Definition: network.cpp:70
The server has banned us.
Definition: core.h:33
uint64 Recv_uint64()
Read a 64 bits integer from the packet.
Definition: packet.cpp:265
void ClearErrorMessages()
Clear all errors from the queue.
Definition: error_gui.cpp:340
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
Definition: string_func.h:59
Randomizer _random
Random used in the game state calculations.
Definition: random_func.cpp:27
static size_t GetNumItems()
Returns number of valid items in the pool.
Definition: pool_type.hpp:276
PacketReader()
Initialise everything.
CompanyID _network_join_as
Who would we like to join as.
CompanyMask _network_company_passworded
Bitmask of the password status of all companies.
Definition: network.cpp:82
void NetworkClientSetCompanyPassword(const char *password)
Set/Reset company password on the client side.
NetworkRecvStatus Receive_SERVER_CHECK_NEWGRFS(Packet *p) override
Sends information about all used GRFs to the client: uint8 Amount of GRFs (the following data is repe...
NetworkRecvStatus Receive_SERVER_NEED_COMPANY_PASSWORD(Packet *p) override
Indication to the client that the server needs a company password: uint32 Generation seed...
Client executed a command and sends it to the server.
Definition: tcp_game.h:93
virtual NetworkRecvStatus CloseConnection(bool error=true)
Close the current connection; for TCP this will be mostly equivalent to Close(), but for UDP it just ...
Definition: core.h:61
void NetworkClientSendRcon(const char *password, const char *command)
Send a remote console command.
void CDECL error(const char *s,...)
Error handling for fatal non-user errors.
Definition: openttd.cpp:114
The client telling the server it wants to join.
Definition: tcp_game.h:39
NetworkRecvStatus Receive_SERVER_ERROR_QUIT(Packet *p) override
Inform all clients that one client made an error and thus has quit/been disconnected: uint32 ID of th...
uint32 _frame_counter_server
The frame_counter of the server, if in network-mode.
Definition: network.cpp:68
uint16 num_station[NETWORK_VEH_END]
How many stations are there of this type?
Definition: network_type.h:61
static const uint NETWORK_SERVER_ID_LENGTH
The maximum length of the network id of the servers, in bytes including &#39;\0&#39;.
Definition: config.h:45
Network window; Window numbers:
Definition: window_type.h:468
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
Definition: depend.cpp:68
Maximum number of companies.
Definition: company_type.h:25
The client is active within in the game.
byte * bufe
End of the buffer we write to/read from.
SwitchMode _switch_mode
The next mainloop command.
Definition: gfx.cpp:48
const char * GenerateCompanyPasswordHash(const char *password, const char *password_server_id, uint32 password_game_seed)
Hash the given password using server ID and game seed.
Definition: network.cpp:192
const char * ReceiveCommand(Packet *p, CommandPacket *cp)
Receives a command from the network.
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function() ...
Definition: pool_type.hpp:216
static uint32 _password_game_seed
One bit of &#39;entropy&#39; used to generate a salt for the company passwords.
A client tells the server it is going to quit.
Definition: tcp_game.h:119
bool NetworkMaxCompaniesReached()
Check if max_companies has been reached on the server (local check only).
NetworkRecvStatus Receive_SERVER_BANNED(Packet *p) override
Notification that the client trying to join is banned.
bool _network_server
network-server is active
Definition: network.cpp:55
static NetworkRecvStatus SendQuit()
Tell the server we would like to quit.
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:47
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
Definition: pool_type.hpp:235
static const TextColour CC_ERROR
Colour for error lines.
Definition: console_type.h:26
We are trying to join a server.
Everything we need to know about a command to be able to execute it.
static void Send()
Send the packets of this socket handler.
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
Definition: strings_type.h:19
static NetworkRecvStatus SendSetName(const char *name)
Tell the server that we like to change the name of the client.
uint32 grfid
GRF ID (defined by Action 0x08)
Definition: newgrf_config.h:85
We apparently send a malformed packet.
Definition: core.h:30
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: depend.cpp:131
uint32 _network_join_bytes_total
The total number of bytes to download.
NetworkRecvStatus Receive_SERVER_QUIT(Packet *p) override
Notification that a client left the game: uint32 ID of the client.
The client is downloading the map.
Client said something that should be distributed.
Definition: tcp_game.h:97
static const uint NETWORK_NAME_LENGTH
The maximum length of the server name and map name, in bytes including &#39;\0&#39;.
Definition: config.h:42
Used for DoCommand-like (and some non-fatal AI GUI) errors/information.
Definition: error.h:23
virtual void SendPacket(Packet *packet)
This function puts the packet in the send-queue and it is send as soon as possible.
Definition: tcp.cpp:63
static NetworkRecvStatus SendGetMap()
Request the map from the server.
Create a new company.
Definition: company_type.h:67
void Restore()
Restore the variable.
static NetworkRecvStatus SendCommand(const CommandPacket *cp)
Send a command to the server.
Servers always have this ID.
Definition: network_type.h:43
Money money
The amount of money the company has.
Definition: network_gui.h:34
void ReceiveGRFIdentifier(Packet *p, GRFIdentifier *grf)
Deserializes the GRFIdentifier (GRF ID and MD5 checksum) from the packet.
Definition: core.cpp:73
Last action was requesting game (server) password.
uint16 Recv_uint16()
Read a 16 bits integer from the packet.
Definition: packet.cpp:233
bool CanSendReceive()
Check whether this socket can send or receive something.
Definition: tcp.cpp:227
Base socket handler for all TCP sockets.
Definition: tcp_game.h:150
static uint32 BSWAP32(uint32 x)
Perform a 32 bits endianness bitswap on x.
Last action was requesting company password.
uint8 md5sum[16]
MD5 checksum of file to distinguish files with the same GRF ID (eg. newer version of GRF) ...
Definition: newgrf_config.h:86
static NetworkClientInfo * GetByClientID(ClientID client_id)
Return the CI given it&#39;s client-identifier.
Definition: network.cpp:124
static uint32 last_ack_frame
Last frame we performed an ack.
Only find Grfs matching md5sum.
uint32 state[2]
The state of the randomizer.
Definition: random_func.hpp:25
static const byte NETWORK_COMPANY_INFO_VERSION
What version of company info is this?
Definition: config.h:39
uint8 _network_join_waiting
The number of clients waiting in front of us.
static NetworkRecvStatus SendChat(NetworkAction action, DestType type, int dest, const char *msg, int64 data)
Send a chat-packet over the network.
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Definition: window.cpp:3227
bool my_cmd
did the command originate from "me"
NetworkRecvStatus Receive_SERVER_MAP_BEGIN(Packet *p) override
Sends that the server will begin with sending the map to the client: uint32 Current frame...
Date _date
Current date in days (day counter)
Definition: date.cpp:28
NetworkRecvStatus Receive_SERVER_MOVE(Packet *p) override
Move a client from one company into another: uint32 ID of the client.
Company view; Window numbers:
Definition: window_type.h:364
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition: company_cmd.cpp:46
DetailedFileType
Kinds of files in each AbstractFileType.
Definition: fileio_type.h:30
uint32 _frame_counter_max
To where we may go with our clients.
Definition: network.cpp:69
NetworkRecvStatus Receive_SERVER_ERROR(Packet *p) override
The client made an error: uint8 Error code caused (see NetworkErrorCode).
static bool GameLoop()
Actual game loop for the client.
bool _network_first_time
Whether we have finished joining or not.
Definition: network.cpp:78
byte token
The token we need to send back to the server to prove we&#39;re the right client.
DestType
Destination of our chat messages.
Definition: network_type.h:80
Money income
How much did the company earned last year.
Definition: network_gui.h:35
static char _password_server_id[NETWORK_SERVER_ID_LENGTH]
The other bit of &#39;entropy&#39; used to generate a salt for the company passwords.
NetworkAction
Actions that can be used for NetworkTextMessage.
Definition: network_type.h:87
NetworkRecvStatus Receive_SERVER_MAP_SIZE(Packet *p) override
Sends the size of the map to the client.
NetworkRecvStatus Receive_SERVER_WAIT(Packet *p) override
Notification that another client is currently receiving the map: uint8 Number of clients waiting in f...
void Recv_string(char *buffer, size_t size, StringValidationSettings settings=SVS_REPLACE_WITH_QUESTION_MARK)
Reads a string till it finds a &#39;\0&#39; in the stream.
Definition: packet.cpp:288
Request information about all companies.
Definition: tcp_game.h:43
bool autosave_on_network_disconnect
save an autosave when you get disconnected from a network game with an error?
NetworkCompanyInfo * GetLobbyCompanyInfo(CompanyID company)
Get the company information of a given company to fill for the lobby.
Client tells the server that it received the whole map.
Definition: tcp_game.h:77
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
Definition: strings_func.h:201