OpenTTD
network_client.cpp
Go to the documentation of this file.
1 /* $Id: network_client.cpp 27893 2017-08-13 18:38:42Z frosch $ */
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 #ifdef ENABLE_NETWORK
13 
14 #include "../stdafx.h"
15 #include "network_gui.h"
16 #include "../saveload/saveload.h"
17 #include "../saveload/saveload_filter.h"
18 #include "../command_func.h"
19 #include "../console_func.h"
20 #include "../strings_func.h"
21 #include "../window_func.h"
22 #include "../company_func.h"
23 #include "../company_base.h"
24 #include "../company_gui.h"
25 #include "../core/random_func.hpp"
26 #include "../date_func.h"
27 #include "../gfx_func.h"
28 #include "../error.h"
29 #include "../rev.h"
30 #include "network.h"
31 #include "network_base.h"
32 #include "network_client.h"
33 #include "../core/backup_type.hpp"
34 
35 #include "table/strings.h"
36 
37 #include "../safeguards.h"
38 
39 /* This file handles all the client-commands */
40 
41 
44  static const size_t CHUNK = 32 * 1024;
45 
47  byte *buf;
48  byte *bufe;
49  byte **block;
50  size_t written_bytes;
51  size_t read_bytes;
52 
54  PacketReader() : LoadFilter(NULL), buf(NULL), bufe(NULL), block(NULL), written_bytes(0), read_bytes(0)
55  {
56  }
57 
62  void AddPacket(const Packet *p)
63  {
64  assert(this->read_bytes == 0);
65 
66  size_t in_packet = p->size - p->pos;
67  size_t to_write = min((size_t)(this->bufe - this->buf), in_packet);
68  const byte *pbuf = p->buffer + p->pos;
69 
70  this->written_bytes += in_packet;
71  if (to_write != 0) {
72  memcpy(this->buf, pbuf, to_write);
73  this->buf += to_write;
74  }
75 
76  /* Did everything fit in the current chunk, then we're done. */
77  if (to_write == in_packet) return;
78 
79  /* Allocate a new chunk and add the remaining data. */
80  pbuf += to_write;
81  to_write = in_packet - to_write;
82  this->buf = *this->blocks.Append() = CallocT<byte>(CHUNK);
83  this->bufe = this->buf + CHUNK;
84 
85  memcpy(this->buf, pbuf, to_write);
86  this->buf += to_write;
87  }
88 
89  /* virtual */ size_t Read(byte *rbuf, size_t size)
90  {
91  /* Limit the amount to read to whatever we still have. */
92  size_t ret_size = size = min(this->written_bytes - this->read_bytes, size);
93  this->read_bytes += ret_size;
94  const byte *rbufe = rbuf + ret_size;
95 
96  while (rbuf != rbufe) {
97  if (this->buf == this->bufe) {
98  this->buf = *this->block++;
99  this->bufe = this->buf + CHUNK;
100  }
101 
102  size_t to_write = min(this->bufe - this->buf, rbufe - rbuf);
103  memcpy(rbuf, this->buf, to_write);
104  rbuf += to_write;
105  this->buf += to_write;
106  }
107 
108  return ret_size;
109  }
110 
111  /* virtual */ void Reset()
112  {
113  this->read_bytes = 0;
114 
115  this->block = this->blocks.Begin();
116  this->buf = *this->block++;
117  this->bufe = this->buf + CHUNK;
118  }
119 };
120 
121 
127 {
130 }
131 
134 {
137 
138  delete this->savegame;
139 }
140 
142 {
143  assert(status != NETWORK_RECV_STATUS_OKAY);
144  /*
145  * Sending a message just before leaving the game calls cs->SendPackets.
146  * This might invoke this function, which means that when we close the
147  * connection after cs->SendPackets we will close an already closed
148  * connection. This handles that case gracefully without having to make
149  * that code any more complex or more aware of the validity of the socket.
150  */
151  if (this->sock == INVALID_SOCKET) return status;
152 
153  DEBUG(net, 1, "Closed client connection %d", this->client_id);
154 
155  this->SendPackets(true);
156 
157  /* Wait a number of ticks so our leave message can reach the server.
158  * This is especially needed for Windows servers as they seem to get
159  * the "socket is closed" message before receiving our leave message,
160  * which would trigger the server to close the connection as well. */
161  CSleep(3 * MILLISECONDS_PER_TICK);
162 
163  delete this->GetInfo();
164  delete this;
165 
166  return status;
167 }
168 
174 {
175  /* First, send a CLIENT_ERROR to the server, so he knows we are
176  * disconnection (and why!) */
177  NetworkErrorCode errorno;
178 
179  /* We just want to close the connection.. */
180  if (res == NETWORK_RECV_STATUS_CLOSE_QUERY) {
182  this->CloseConnection(res);
183  _networking = false;
184 
186  return;
187  }
188 
189  switch (res) {
190  case NETWORK_RECV_STATUS_DESYNC: errorno = NETWORK_ERROR_DESYNC; break;
191  case NETWORK_RECV_STATUS_SAVEGAME: errorno = NETWORK_ERROR_SAVEGAME_FAILED; break;
192  case NETWORK_RECV_STATUS_NEWGRF_MISMATCH: errorno = NETWORK_ERROR_NEWGRF_MISMATCH; break;
193  default: errorno = NETWORK_ERROR_GENERAL; break;
194  }
195 
196  /* This means we fucked up and the server closed the connection */
199  SendError(errorno);
200  }
201 
203  this->CloseConnection(res);
204  _networking = false;
205 }
206 
207 
214 {
215  if (my_client->CanSendReceive()) {
217  if (res != NETWORK_RECV_STATUS_OKAY) {
218  /* The client made an error of which we can not recover.
219  * Close the connection and drop back to the main menu. */
220  my_client->ClientError(res);
221  return false;
222  }
223  }
224  return _networking;
225 }
226 
229 {
232 }
233 
239 {
240  _frame_counter++;
241 
243 
244  extern void StateGameLoop();
245  StateGameLoop();
246 
247  /* Check if we are in sync! */
248  if (_sync_frame != 0) {
249  if (_sync_frame == _frame_counter) {
250 #ifdef NETWORK_SEND_DOUBLE_SEED
251  if (_sync_seed_1 != _random.state[0] || _sync_seed_2 != _random.state[1]) {
252 #else
253  if (_sync_seed_1 != _random.state[0]) {
254 #endif
255  NetworkError(STR_NETWORK_ERROR_DESYNC);
256  DEBUG(desync, 1, "sync_err: %08x; %02x", _date, _date_fract);
257  DEBUG(net, 0, "Sync error detected!");
259  return false;
260  }
261 
262  /* If this is the first time we have a sync-frame, we
263  * need to let the server know that we are ready and at the same
264  * frame as he is.. so we can start playing! */
265  if (_network_first_time) {
266  _network_first_time = false;
267  SendAck();
268  }
269 
270  _sync_frame = 0;
271  } else if (_sync_frame < _frame_counter) {
272  DEBUG(net, 1, "Missed frame for sync-test (%d / %d)", _sync_frame, _frame_counter);
273  _sync_frame = 0;
274  }
275  }
276 
277  return true;
278 }
279 
280 
283 
285 static uint32 last_ack_frame;
286 
288 static uint32 _password_game_seed;
291 
296 
299 
301 const char *_network_join_server_password = NULL;
304 
307 
308 /***********
309  * Sending functions
310  * DEF_CLIENT_SEND_COMMAND has no parameters
311  ************/
312 
315 {
317  _network_join_status = NETWORK_JOIN_STATUS_GETTING_COMPANY_INFO;
319 
321  my_client->SendPacket(p);
323 }
324 
327 {
329  _network_join_status = NETWORK_JOIN_STATUS_AUTHORIZING;
331 
332  Packet *p = new Packet(PACKET_CLIENT_JOIN);
333  p->Send_string(_openttd_revision);
334  p->Send_uint32(_openttd_newgrf_version);
335  p->Send_string(_settings_client.network.client_name); // Client name
336  p->Send_uint8 (_network_join_as); // PlayAs
337  p->Send_uint8 (NETLANG_ANY); // Language
338  my_client->SendPacket(p);
340 }
341 
344 {
346  my_client->SendPacket(p);
348 }
349 
355 {
357  p->Send_string(password);
358  my_client->SendPacket(p);
360 }
361 
367 {
369  p->Send_string(GenerateCompanyPasswordHash(password, _password_server_id, _password_game_seed));
370  my_client->SendPacket(p);
372 }
373 
376 {
378 
380  my_client->SendPacket(p);
382 }
383 
386 {
388 
390  my_client->SendPacket(p);
392 }
393 
396 {
397  Packet *p = new Packet(PACKET_CLIENT_ACK);
398 
400  p->Send_uint8 (my_client->token);
401  my_client->SendPacket(p);
403 }
404 
410 {
412  my_client->NetworkGameSocketHandler::SendCommand(p, cp);
413 
414  my_client->SendPacket(p);
416 }
417 
419 NetworkRecvStatus ClientNetworkGameSocketHandler::SendChat(NetworkAction action, DestType type, int dest, const char *msg, int64 data)
420 {
421  Packet *p = new Packet(PACKET_CLIENT_CHAT);
422 
423  p->Send_uint8 (action);
424  p->Send_uint8 (type);
425  p->Send_uint32(dest);
426  p->Send_string(msg);
427  p->Send_uint64(data);
428 
429  my_client->SendPacket(p);
431 }
432 
435 {
437 
438  p->Send_uint8(errorno);
439  my_client->SendPacket(p);
441 }
442 
448 {
450 
451  p->Send_string(GenerateCompanyPasswordHash(password, _password_server_id, _password_game_seed));
452  my_client->SendPacket(p);
454 }
455 
461 {
463 
464  p->Send_string(name);
465  my_client->SendPacket(p);
467 }
468 
473 {
474  Packet *p = new Packet(PACKET_CLIENT_QUIT);
475 
476  my_client->SendPacket(p);
478 }
479 
485 NetworkRecvStatus ClientNetworkGameSocketHandler::SendRCon(const char *pass, const char *command)
486 {
487  Packet *p = new Packet(PACKET_CLIENT_RCON);
488  p->Send_string(pass);
489  p->Send_string(command);
490  my_client->SendPacket(p);
492 }
493 
500 {
501  Packet *p = new Packet(PACKET_CLIENT_MOVE);
502  p->Send_uint8(company);
503  p->Send_string(GenerateCompanyPasswordHash(password, _password_server_id, _password_game_seed));
504  my_client->SendPacket(p);
506 }
507 
513 {
514  return my_client != NULL && my_client->status == STATUS_ACTIVE;
515 }
516 
517 
518 /***********
519  * Receiving functions
520  * DEF_CLIENT_RECEIVE_COMMAND has parameter: Packet *p
521  ************/
522 
523 extern bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = NULL);
524 
526 {
527  /* We try to join a server which is full */
528  ShowErrorMessage(STR_NETWORK_ERROR_SERVER_FULL, INVALID_STRING_ID, WL_CRITICAL);
530 
532 }
533 
535 {
536  /* We try to join a server where we are banned */
537  ShowErrorMessage(STR_NETWORK_ERROR_SERVER_BANNED, INVALID_STRING_ID, WL_CRITICAL);
539 
541 }
542 
544 {
546 
547  byte company_info_version = p->Recv_uint8();
548 
549  if (!this->HasClientQuit() && company_info_version == NETWORK_COMPANY_INFO_VERSION) {
550  /* We have received all data... (there are no more packets coming) */
551  if (!p->Recv_bool()) return NETWORK_RECV_STATUS_CLOSE_QUERY;
552 
553  CompanyID current = (Owner)p->Recv_uint8();
554  if (current >= MAX_COMPANIES) return NETWORK_RECV_STATUS_CLOSE_QUERY;
555 
556  NetworkCompanyInfo *company_info = GetLobbyCompanyInfo(current);
557  if (company_info == NULL) return NETWORK_RECV_STATUS_CLOSE_QUERY;
558 
559  p->Recv_string(company_info->company_name, sizeof(company_info->company_name));
560  company_info->inaugurated_year = p->Recv_uint32();
561  company_info->company_value = p->Recv_uint64();
562  company_info->money = p->Recv_uint64();
563  company_info->income = p->Recv_uint64();
564  company_info->performance = p->Recv_uint16();
565  company_info->use_password = p->Recv_bool();
566  for (uint i = 0; i < NETWORK_VEH_END; i++) {
567  company_info->num_vehicle[i] = p->Recv_uint16();
568  }
569  for (uint i = 0; i < NETWORK_VEH_END; i++) {
570  company_info->num_station[i] = p->Recv_uint16();
571  }
572  company_info->ai = p->Recv_bool();
573 
574  p->Recv_string(company_info->clients, sizeof(company_info->clients));
575 
577 
579  }
580 
582 }
583 
584 /* This packet contains info about the client (playas and name)
585  * as client we save this in NetworkClientInfo, linked via 'client_id'
586  * which is always an unique number on a server. */
588 {
589  NetworkClientInfo *ci;
591  CompanyID playas = (CompanyID)p->Recv_uint8();
592  char name[NETWORK_NAME_LENGTH];
593 
594  p->Recv_string(name, sizeof(name));
595 
597  if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;
598 
599  ci = NetworkClientInfo::GetByClientID(client_id);
600  if (ci != NULL) {
601  if (playas == ci->client_playas && strcmp(name, ci->client_name) != 0) {
602  /* Client name changed, display the change */
603  NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, name);
604  } else if (playas != ci->client_playas) {
605  /* The client changed from client-player..
606  * Do not display that for now */
607  }
608 
609  /* Make sure we're in the company the server tells us to be in,
610  * for the rare case that we get moved while joining. */
611  if (client_id == _network_own_client_id) SetLocalCompany(!Company::IsValidID(playas) ? COMPANY_SPECTATOR : playas);
612 
613  ci->client_playas = playas;
614  strecpy(ci->client_name, name, lastof(ci->client_name));
615 
617 
619  }
620 
621  /* There are at most as many ClientInfo as ClientSocket objects in a
622  * server. Having more info than a server can have means something
623  * has gone wrong somewhere, i.e. the server has more info than it
624  * has actual clients. That means the server is feeding us an invalid
625  * state. So, bail out! This server is broken. */
627 
628  /* We don't have this client_id yet, find an empty client_id, and put the data there */
629  ci = new NetworkClientInfo(client_id);
630  ci->client_playas = playas;
631  if (client_id == _network_own_client_id) this->SetInfo(ci);
632 
633  strecpy(ci->client_name, name, lastof(ci->client_name));
634 
636 
638 }
639 
641 {
642  static const StringID network_error_strings[] = {
643  STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_GENERAL
644  STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_DESYNC
645  STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_SAVEGAME_FAILED
646  STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_CONNECTION_LOST
647  STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_ILLEGAL_PACKET
648  STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_NEWGRF_MISMATCH
649  STR_NETWORK_ERROR_SERVER_ERROR, // NETWORK_ERROR_NOT_AUTHORIZED
650  STR_NETWORK_ERROR_SERVER_ERROR, // NETWORK_ERROR_NOT_EXPECTED
651  STR_NETWORK_ERROR_WRONG_REVISION, // NETWORK_ERROR_WRONG_REVISION
652  STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_NAME_IN_USE
653  STR_NETWORK_ERROR_WRONG_PASSWORD, // NETWORK_ERROR_WRONG_PASSWORD
654  STR_NETWORK_ERROR_SERVER_ERROR, // NETWORK_ERROR_COMPANY_MISMATCH
655  STR_NETWORK_ERROR_KICKED, // NETWORK_ERROR_KICKED
656  STR_NETWORK_ERROR_CHEATER, // NETWORK_ERROR_CHEATER
657  STR_NETWORK_ERROR_SERVER_FULL, // NETWORK_ERROR_FULL
658  STR_NETWORK_ERROR_TOO_MANY_COMMANDS, // NETWORK_ERROR_TOO_MANY_COMMANDS
659  STR_NETWORK_ERROR_TIMEOUT_PASSWORD, // NETWORK_ERROR_TIMEOUT_PASSWORD
660  STR_NETWORK_ERROR_TIMEOUT_COMPUTER, // NETWORK_ERROR_TIMEOUT_COMPUTER
661  STR_NETWORK_ERROR_TIMEOUT_MAP, // NETWORK_ERROR_TIMEOUT_MAP
662  STR_NETWORK_ERROR_TIMEOUT_JOIN, // NETWORK_ERROR_TIMEOUT_JOIN
663  };
664  assert_compile(lengthof(network_error_strings) == NETWORK_ERROR_END);
665 
667 
668  StringID err = STR_NETWORK_ERROR_LOSTCONNECTION;
669  if (error < (ptrdiff_t)lengthof(network_error_strings)) err = network_error_strings[error];
670 
672 
674 
676 }
677 
679 {
681 
682  uint grf_count = p->Recv_uint8();
684 
685  /* Check all GRFs */
686  for (; grf_count > 0; grf_count--) {
687  GRFIdentifier c;
688  this->ReceiveGRFIdentifier(p, &c);
689 
690  /* Check whether we know this GRF */
691  const GRFConfig *f = FindGRFConfig(c.grfid, FGCM_EXACT, c.md5sum);
692  if (f == NULL) {
693  /* We do not know this GRF, bail out of initialization */
694  char buf[sizeof(c.md5sum) * 2 + 1];
695  md5sumToString(buf, lastof(buf), c.md5sum);
696  DEBUG(grf, 0, "NewGRF %08X not found; checksum %s", BSWAP32(c.grfid), buf);
698  }
699  }
700 
701  if (ret == NETWORK_RECV_STATUS_OKAY) {
702  /* Start receiving the map */
703  return SendNewGRFsOk();
704  }
705 
706  /* NewGRF mismatch, bail out */
707  ShowErrorMessage(STR_NETWORK_ERROR_NEWGRF_MISMATCH, INVALID_STRING_ID, WL_CRITICAL);
708  return ret;
709 }
710 
712 {
713  if (this->status < STATUS_JOIN || this->status >= STATUS_AUTH_GAME) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
714  this->status = STATUS_AUTH_GAME;
715 
716  const char *password = _network_join_server_password;
717  if (!StrEmpty(password)) {
718  return SendGamePassword(password);
719  }
720 
721  ShowNetworkNeedPassword(NETWORK_GAME_PASSWORD);
722 
724 }
725 
727 {
728  if (this->status < STATUS_JOIN || this->status >= STATUS_AUTH_COMPANY) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
729  this->status = STATUS_AUTH_COMPANY;
730 
731  _password_game_seed = p->Recv_uint32();
732  p->Recv_string(_password_server_id, sizeof(_password_server_id));
734 
735  const char *password = _network_join_company_password;
736  if (!StrEmpty(password)) {
737  return SendCompanyPassword(password);
738  }
739 
740  ShowNetworkNeedPassword(NETWORK_COMPANY_PASSWORD);
741 
743 }
744 
746 {
747  if (this->status < STATUS_JOIN || this->status >= STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
748  this->status = STATUS_AUTHORIZED;
749 
751 
752  /* Initialize the password hash salting variables, even if they were previously. */
753  _password_game_seed = p->Recv_uint32();
754  p->Recv_string(_password_server_id, sizeof(_password_server_id));
755 
756  /* Start receiving the map */
757  return SendGetMap();
758 }
759 
761 {
762  /* We set the internal wait state when requesting the map. */
764 
765  /* But... only now we set the join status to waiting, instead of requesting. */
766  _network_join_status = NETWORK_JOIN_STATUS_WAITING;
769 
771 }
772 
774 {
775  if (this->status < STATUS_AUTHORIZED || this->status >= STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
776  this->status = STATUS_MAP;
777 
778  if (this->savegame != NULL) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
779 
780  this->savegame = new PacketReader();
781 
783 
786 
787  _network_join_status = NETWORK_JOIN_STATUS_DOWNLOADING;
789 
791 }
792 
794 {
796  if (this->savegame == NULL) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
797 
800 
802 }
803 
805 {
807  if (this->savegame == NULL) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
808 
809  /* We are still receiving data, put it to the file */
810  this->savegame->AddPacket(p);
811 
812  _network_join_bytes = (uint32)this->savegame->written_bytes;
814 
816 }
817 
819 {
821  if (this->savegame == NULL) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
822 
823  _network_join_status = NETWORK_JOIN_STATUS_PROCESSING;
825 
826  /*
827  * Make sure everything is set for reading.
828  *
829  * We need the local copy and reset this->savegame because when
830  * loading fails the network gets reset upon loading the intro
831  * game, which would cause us to free this->savegame twice.
832  */
833  LoadFilter *lf = this->savegame;
834  this->savegame = NULL;
835  lf->Reset();
836 
837  /* The map is done downloading, load it */
839  bool load_success = SafeLoad(NULL, SLO_LOAD, DFT_GAME_FILE, GM_NORMAL, NO_DIRECTORY, lf);
840 
841  /* Long savegame loads shouldn't affect the lag calculation! */
842  this->last_packet = _realtime_tick;
843 
844  if (!load_success) {
846  ShowErrorMessage(STR_NETWORK_ERROR_SAVEGAMEERROR, INVALID_STRING_ID, WL_CRITICAL);
848  }
849  /* If the savegame has successfully loaded, ALL windows have been removed,
850  * only toolbar/statusbar and gamefield are visible */
851 
852  /* Say we received the map and loaded it correctly! */
853  SendMapOk();
854 
855  /* New company/spectator (invalid company) or company we want to join is not active
856  * Switch local company to spectator and await the server's judgement */
857  if (_network_join_as == COMPANY_NEW_COMPANY || !Company::IsValidID(_network_join_as)) {
859 
860  if (_network_join_as != COMPANY_SPECTATOR) {
861  /* We have arrived and ready to start playing; send a command to make a new company;
862  * the server will give us a client-id and let us in */
863  _network_join_status = NETWORK_JOIN_STATUS_REGISTERING;
864  ShowJoinStatusWindow();
865  NetworkSendCommand(0, 0, 0, CMD_COMPANY_CTRL, NULL, NULL, _local_company);
866  }
867  } else {
868  /* take control over an existing company */
869  SetLocalCompany(_network_join_as);
870  }
871 
873 }
874 
876 {
878 
881 #ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME
882  /* Test if the server supports this option
883  * and if we are at the frame the server is */
884  if (p->pos + 1 < p->size) {
886  _sync_seed_1 = p->Recv_uint32();
887 #ifdef NETWORK_SEND_DOUBLE_SEED
888  _sync_seed_2 = p->Recv_uint32();
889 #endif
890  }
891 #endif
892  /* Receive the token. */
893  if (p->pos != p->size) this->token = p->Recv_uint8();
894 
895  DEBUG(net, 5, "Received FRAME %d", _frame_counter_server);
896 
897  /* Let the server know that we received this frame correctly
898  * We do this only once per day, to save some bandwidth ;) */
899  if (!_network_first_time && last_ack_frame < _frame_counter) {
900  last_ack_frame = _frame_counter + DAY_TICKS;
901  DEBUG(net, 4, "Sent ACK at %d", _frame_counter);
902  SendAck();
903  }
904 
906 }
907 
909 {
911 
912  _sync_frame = p->Recv_uint32();
913  _sync_seed_1 = p->Recv_uint32();
914 #ifdef NETWORK_SEND_DOUBLE_SEED
915  _sync_seed_2 = p->Recv_uint32();
916 #endif
917 
919 }
920 
922 {
924 
925  CommandPacket cp;
926  const char *err = this->ReceiveCommand(p, &cp);
927  cp.frame = p->Recv_uint32();
928  cp.my_cmd = p->Recv_bool();
929 
930  if (err != NULL) {
931  IConsolePrintF(CC_ERROR, "WARNING: %s from server, dropping...", err);
933  }
934 
935  this->incoming_queue.Append(&cp);
936 
938 }
939 
941 {
943 
944  char name[NETWORK_NAME_LENGTH], msg[NETWORK_CHAT_LENGTH];
945  const NetworkClientInfo *ci = NULL, *ci_to;
946 
947  NetworkAction action = (NetworkAction)p->Recv_uint8();
949  bool self_send = p->Recv_bool();
951  int64 data = p->Recv_uint64();
952 
953  ci_to = NetworkClientInfo::GetByClientID(client_id);
954  if (ci_to == NULL) return NETWORK_RECV_STATUS_OKAY;
955 
956  /* Did we initiate the action locally? */
957  if (self_send) {
958  switch (action) {
959  case NETWORK_ACTION_CHAT_CLIENT:
960  /* For speaking to client we need the client-name */
961  seprintf(name, lastof(name), "%s", ci_to->client_name);
963  break;
964 
965  /* For speaking to company or giving money, we need the company-name */
966  case NETWORK_ACTION_GIVE_MONEY:
967  if (!Company::IsValidID(ci_to->client_playas)) return NETWORK_RECV_STATUS_OKAY;
968  FALLTHROUGH;
969 
970  case NETWORK_ACTION_CHAT_COMPANY: {
971  StringID str = Company::IsValidID(ci_to->client_playas) ? STR_COMPANY_NAME : STR_NETWORK_SPECTATORS;
972  SetDParam(0, ci_to->client_playas);
973 
974  GetString(name, str, lastof(name));
976  break;
977  }
978 
979  default: return NETWORK_RECV_STATUS_MALFORMED_PACKET;
980  }
981  } else {
982  /* Display message from somebody else */
983  seprintf(name, lastof(name), "%s", ci_to->client_name);
984  ci = ci_to;
985  }
986 
987  if (ci != NULL) {
988  NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), self_send, name, msg, data);
989  }
991 }
992 
994 {
996 
998 
1000  if (ci != NULL) {
1001  NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, NULL, GetNetworkErrorMsg((NetworkErrorCode)p->Recv_uint8()));
1002  delete ci;
1003  }
1004 
1006 
1007  return NETWORK_RECV_STATUS_OKAY;
1008 }
1009 
1011 {
1013 
1015 
1017  if (ci != NULL) {
1018  NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, NULL, STR_NETWORK_MESSAGE_CLIENT_LEAVING);
1019  delete ci;
1020  } else {
1021  DEBUG(net, 0, "Unknown client (%d) is leaving the game", client_id);
1022  }
1023 
1025 
1026  /* If we come here it means we could not locate the client.. strange :s */
1027  return NETWORK_RECV_STATUS_OKAY;
1028 }
1029 
1031 {
1033 
1035 
1037  if (ci != NULL) {
1038  NetworkTextMessage(NETWORK_ACTION_JOIN, CC_DEFAULT, false, ci->client_name);
1039  }
1040 
1042 
1043  return NETWORK_RECV_STATUS_OKAY;
1044 }
1045 
1047 {
1048  /* Only when we're trying to join we really
1049  * care about the server shutting down. */
1050  if (this->status >= STATUS_JOIN) {
1051  ShowErrorMessage(STR_NETWORK_MESSAGE_SERVER_SHUTDOWN, INVALID_STRING_ID, WL_CRITICAL);
1052  }
1053 
1055 }
1056 
1058 {
1059  /* Only when we're trying to join we really
1060  * care about the server shutting down. */
1061  if (this->status >= STATUS_JOIN) {
1062  /* To throttle the reconnects a bit, every clients waits its
1063  * Client ID modulo 16. This way reconnects should be spread
1064  * out a bit. */
1066  ShowErrorMessage(STR_NETWORK_MESSAGE_SERVER_REBOOT, INVALID_STRING_ID, WL_CRITICAL);
1067  }
1068 
1070 }
1071 
1073 {
1075 
1076  TextColour colour_code = (TextColour)p->Recv_uint16();
1078 
1079  char rcon_out[NETWORK_RCONCOMMAND_LENGTH];
1080  p->Recv_string(rcon_out, sizeof(rcon_out));
1081 
1082  IConsolePrint(colour_code, rcon_out);
1083 
1084  return NETWORK_RECV_STATUS_OKAY;
1085 }
1086 
1088 {
1090 
1091  /* Nothing more in this packet... */
1093  CompanyID company_id = (CompanyID)p->Recv_uint8();
1094 
1095  if (client_id == 0) {
1096  /* definitely an invalid client id, debug message and do nothing. */
1097  DEBUG(net, 0, "[move] received invalid client index = 0");
1099  }
1100 
1101  const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
1102  /* Just make sure we do not try to use a client_index that does not exist */
1103  if (ci == NULL) return NETWORK_RECV_STATUS_OKAY;
1104 
1105  /* if not valid player, force spectator, else check player exists */
1106  if (!Company::IsValidID(company_id)) company_id = COMPANY_SPECTATOR;
1107 
1108  if (client_id == _network_own_client_id) {
1109  SetLocalCompany(company_id);
1110  }
1111 
1112  return NETWORK_RECV_STATUS_OKAY;
1113 }
1114 
1116 {
1118 
1119  _network_server_max_companies = p->Recv_uint8();
1120  _network_server_max_spectators = p->Recv_uint8();
1121 
1122  return NETWORK_RECV_STATUS_OKAY;
1123 }
1124 
1126 {
1128 
1131 
1132  return NETWORK_RECV_STATUS_OKAY;
1133 }
1134 
1139 {
1140  /* Only once we're authorized we can expect a steady stream of packets. */
1141  if (this->status < STATUS_AUTHORIZED) return;
1142 
1143  /* It might... sometimes occur that the realtime ticker overflows. */
1144  if (_realtime_tick < this->last_packet) this->last_packet = _realtime_tick;
1145 
1146  /* Lag is in milliseconds; 5 seconds are roughly twice the
1147  * server's "you're slow" threshold (1 game day). */
1148  uint lag = (_realtime_tick - this->last_packet) / 1000;
1149  if (lag < 5) return;
1150 
1151  /* 20 seconds are (way) more than 4 game days after which
1152  * the server will forcefully disconnect you. */
1153  if (lag > 20) {
1155  ShowErrorMessage(STR_NETWORK_ERROR_LOSTCONNECTION, INVALID_STRING_ID, WL_CRITICAL);
1156  return;
1157  }
1158 
1159  /* Prevent showing the lag message every tick; just update it when needed. */
1160  static uint last_lag = 0;
1161  if (last_lag == lag) return;
1162 
1163  last_lag = lag;
1164  SetDParam(0, lag);
1165  ShowErrorMessage(STR_NETWORK_ERROR_CLIENT_GUI_LOST_CONNECTION_CAPTION, STR_NETWORK_ERROR_CLIENT_GUI_LOST_CONNECTION, WL_INFO);
1166 }
1167 
1168 
1171 {
1172  /* Set the frame-counter to 0 so nothing happens till we are ready */
1173  _frame_counter = 0;
1175  last_ack_frame = 0;
1176  /* Request the game-info */
1178 }
1179 
1185 void NetworkClientSendRcon(const char *password, const char *command)
1186 {
1187  MyClient::SendRCon(password, command);
1188 }
1189 
1196 void NetworkClientRequestMove(CompanyID company_id, const char *pass)
1197 {
1198  MyClient::SendMove(company_id, pass);
1199 }
1200 
1206 {
1207  Backup<CompanyByte> cur_company(_current_company, FILE_LINE);
1208  /* If our company is changing owner, go to spectators */
1210 
1211  NetworkClientInfo *ci;
1212  FOR_ALL_CLIENT_INFOS(ci) {
1213  if (ci->client_playas != cid) continue;
1214  NetworkTextMessage(NETWORK_ACTION_COMPANY_SPECTATOR, CC_DEFAULT, false, ci->client_name);
1216  }
1217 
1218  cur_company.Restore();
1219 }
1220 
1225 {
1227 
1228  if (ci == NULL) return;
1229 
1230  /* Don't change the name if it is the same as the old name */
1231  if (strcmp(ci->client_name, _settings_client.network.client_name) != 0) {
1232  if (!_network_server) {
1234  } else {
1236  NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, _settings_client.network.client_name);
1239  }
1240  }
1241  }
1242 }
1243 
1252 void NetworkClientSendChat(NetworkAction action, DestType type, int dest, const char *msg, int64 data)
1253 {
1254  MyClient::SendChat(action, type, dest, msg, data);
1255 }
1256 
1261 void NetworkClientSetCompanyPassword(const char *password)
1262 {
1263  MyClient::SendSetPassword(password);
1264 }
1265 
1272 {
1273  /* Only companies actually playing can speak to team. Eg spectators cannot */
1275 
1276  const NetworkClientInfo *ci;
1277  FOR_ALL_CLIENT_INFOS(ci) {
1278  if (ci->client_playas == cio->client_playas && ci != cio) return true;
1279  }
1280 
1281  return false;
1282 }
1283 
1289 {
1291 }
1292 
1298 {
1300 }
1301 
1302 #endif /* ENABLE_NETWORK */
Everything is okay.
Definition: core.h:27
Client acknowledges that it has all required NewGRFs.
Definition: tcp_game.h:60
We are trying to get company information.
used in multiplayer to create a new companies etc.
Definition: command_type.h:279
bool _networking
are we in networking mode?
Definition: network.cpp:56
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:40
bool HasClientQuit() const
Whether the current client connected to the socket has quit.
Definition: core.h:71
Container for all information known about a client.
Definition: network_base.h:27
SOCKET sock
The socket currently connected to.
Definition: tcp.h:36
virtual NetworkRecvStatus Receive_SERVER_WAIT(Packet *p)
Notification that another client is currently receiving the map: uint8 Number of clients waiting in f...
uint32 _sync_seed_1
Seed to compare during sync checks.
Definition: network.cpp:75
struct PacketReader * savegame
Packet reader for reading the savegame.
uint32 _realtime_tick
The real time in the game.
Definition: debug.cpp:48
Internal entity of a packet.
Definition: packet.h:44
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3120
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:112
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:250
The client is authorized at the server.
virtual NetworkRecvStatus Receive_SERVER_JOIN(Packet *p)
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:54
const char * _network_join_server_password
Login password from -p argument.
virtual NetworkRecvStatus Receive_SERVER_SHUTDOWN(Packet *p)
Let the clients know that the server is closing.
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.
virtual NetworkRecvStatus Receive_SERVER_CHAT(Packet *p)
Sends a chat-packet to the client: uint8 ID of the action (see NetworkAction).
bool ai
Is this company an AI.
Definition: network_type.h:64
virtual NetworkRecvStatus Receive_SERVER_NEWGAME(Packet *p)
Let the clients know that the server is loading a new map.
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:398
void Send_string(const char *data)
Sends a string over the network.
Definition: packet.cpp:152
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:30
byte ** block
The block we&#39;re reading from/writing to.
NetworkErrorCode
The error codes we send around in the protocols.
Definition: network_type.h:104
char company_name[NETWORK_COMPANY_NAME_LENGTH]
Company name.
Definition: network_gui.h:33
Clients sends the (hashed) game password.
Definition: tcp_game.h:64
NetworkJoinStatus _network_join_status
The status of joining.
void Send_uint8(uint8 data)
Package a 8 bits integer in the packet.
Definition: packet.cpp:100
char * md5sumToString(char *buf, const char *last, const uint8 md5sum[16])
Convert the md5sum to a hexadecimal string representation.
Definition: string.cpp:416
virtual NetworkRecvStatus Receive_SERVER_FULL(Packet *p)
Notification that the server is full.
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.
const T * Begin() const
Get the pointer to the first item (const)
void NetworkClientRequestMove(CompanyID company_id, const char *pass)
Notify the server of this client wanting to be moved to another company.
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
virtual NetworkRecvStatus Receive_SERVER_CLIENT_INFO(Packet *p)
Send information about a client: uint32 ID of the client (always unique on a server.
void Send_uint32(uint32 data)
Package a 32 bits integer in the packet.
Definition: packet.cpp:121
void NetworkClientSendChat(NetworkAction action, DestType type, int dest, const char *msg, int64 data)
Send a chat message.
#define lastof(x)
Get the last element of an fixed size array.
Definition: depend.cpp:50
The client is spectating.
Definition: company_type.h:37
The client wants a new company.
Definition: company_type.h:36
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:35
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.
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.
virtual NetworkRecvStatus Receive_SERVER_QUIT(Packet *p)
Notification that a client left the game: uint32 ID of the client.
Class for handling the client side of the game connection.
virtual NetworkRecvStatus Receive_SERVER_CHECK_NEWGRFS(Packet *p)
Sends information about all used GRFs to the client: uint8 Amount of GRFs (the following data is repe...
uint32 _sync_frame
The frame to perform the sync check.
Definition: network.cpp:79
The server told us we made an error.
Definition: core.h:33
The client tells the server which frame it has executed.
Definition: tcp_game.h:91
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:99
virtual NetworkRecvStatus Receive_SERVER_WELCOME(Packet *p)
The client is joined and ready to receive his map: uint32 Own client ID.
StringID GetNetworkErrorMsg(NetworkErrorCode err)
Retrieve the string id of an internal error number.
Definition: network.cpp:310
Servers always have this ID.
Definition: network_type.h:45
Client asks the server to execute some command.
Definition: tcp_game.h:103
Network lobby window.
Definition: window_type.h:30
The password of the company.
Definition: network_type.h:78
T * Append(uint to_add=1)
Append an item and return it.
CommandQueue incoming_queue
The command-queue awaiting handling.
Definition: tcp_game.h:524
Class to backup a specific variable and restore it later.
Definition: backup_type.hpp:23
CompanyByte _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition: company_cmd.cpp:46
virtual NetworkRecvStatus Receive_SERVER_ERROR(Packet *p)
The client made an error: uint8 Error code caused (see NetworkErrorCode).
virtual NetworkRecvStatus Receive_SERVER_COMMAND(Packet *p)
Sends a DoCommand to the client: uint8 ID of the company (0..MAX_COMPANIES-1).
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:62
Save game or scenario file.
Definition: fileio_type.h:33
Done querying the server.
Definition: core.h:36
Interface for filtering a savegame till it is loaded.
A desync did occur.
Definition: core.h:28
Year inaugurated_year
What year the company started in.
Definition: network_gui.h:34
~ClientNetworkGameSocketHandler()
Clear whatever we assigned.
Critical errors, the MessageBox is shown in all cases.
Definition: error.h:26
void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel wl, int x=0, int y=0, const GRFFile *textref_stack_grffile=NULL, uint textref_stack_size=0, const uint32 *textref_stack=NULL)
Display an error message in a window.
Definition: error_gui.cpp:378
void StateGameLoop()
State controlling game loop.
Definition: openttd.cpp:1341
static bool IsConnected()
Check whether the client is actually connected (and in the game).
bool prefer_teamchat
choose the chat message target with <ENTER>, true=all clients, false=your team
Definition: settings_type.h:93
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:31
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:134
A client would like to be moved to another company.
Definition: tcp_game.h:107
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:56
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:29
GameMode
Mode which defines the state of the game.
Definition: openttd.h:18
NetworkRecvStatus CloseConnection(bool error=true)
Functions to help ReceivePacket/SendPacket a bit A socket can make errors.
Definition: tcp_game.cpp:44
Client sends the (hashed) company password.
Definition: tcp_game.h:66
uint8 max_spectators
maximum amount of spectators
Company information stored at the client side.
Definition: network_gui.h:32
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:88
Read some packets, and when do use that data as initial load filter.
AutoFreeSmallVector< byte *, 16 > blocks
Buffer with blocks of allocated memory.
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:63
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:76
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:132
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.
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...
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:66
static ClientNetworkGameSocketHandler * my_client
This is us!
NetworkRecvStatus
Status of a network client; reasons why a client has quit.
Definition: core.h:26
A client (re)sets its company&#39;s password.
Definition: tcp_game.h:111
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:55
byte * buf
Buffer we&#39;re going to write to/read from.
static const uint NETWORK_CHAT_LENGTH
The maximum length of a chat message, in bytes including &#39;\0&#39;.
Definition: config.h:52
virtual NetworkRecvStatus Receive_SERVER_COMPANY_INFO(Packet *p)
Sends information about the companies (one packet per company): uint8 Version of the structure of thi...
We did not have the required NewGRFs.
Definition: core.h:29
Basic functions/variables used all over the place.
virtual NetworkRecvStatus Receive_SERVER_COMPANY_UPDATE(Packet *p)
Update the clients knowledge of which company is password protected: uint16 Bitwise representation of...
PacketSize size
The size of the whole packet for received packets.
Definition: packet.h:52
#define lengthof(x)
Return the length of an fixed size array.
Definition: depend.cpp:42
virtual NetworkRecvStatus Receive_SERVER_MAP_DATA(Packet *p)
Sends the data of the map to the client: Contains a part of the map (until max size of packet)...
uint last_packet
Time we received the last frame.
Definition: tcp_game.h:525
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:550
uint32 frame
the frame in which this packet is executed
ServerStatus status
Status of the connection with the server.
NetworkRecvStatus CloseConnection(NetworkRecvStatus status)
Close the network connection due to the given status.
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:123
bool Recv_bool()
Read a boolean from the packet.
Definition: packet.cpp:212
uint32 _network_join_bytes
The number of bytes we already downloaded.
SaveLoadOperation
Operation performed on the file.
Definition: fileio_type.h:49
Maximum number of companies.
Definition: company_type.h:25
void Reset()
Reset this filter to read from the beginning of the file.
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:38
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.
virtual NetworkRecvStatus Receive_SERVER_NEED_COMPANY_PASSWORD(Packet *p)
Indication to the client that the server needs a company password: uint32 Generation seed...
The connection is &#39;just&#39; lost.
Definition: core.h:31
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:39
virtual NetworkRecvStatus Receive_SERVER_BANNED(Packet *p)
Notification that the client trying to join is banned.
Network status window; Window numbers:
Definition: window_type.h:487
ClientID client_id
Client identifier.
Definition: tcp_game.h:521
virtual NetworkRecvStatus Receive_SERVER_MOVE(Packet *p)
Move a client from one company into another: uint32 ID of the client.
void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
Delete a window by its class and window number (if it is open).
Definition: window.cpp:1137
The server is full.
Definition: core.h:34
static NetworkRecvStatus SendCompanyInformationQuery()
Query the server for company information.
The password of the game.
Definition: network_type.h:77
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.
virtual NetworkRecvStatus Receive_SERVER_SYNC(Packet *p)
Sends a sync-check to the client: uint32 Frame counter.
uint8 Recv_uint8()
Read a 8 bits integer from the packet.
Definition: packet.cpp:221
bool use_password
Is there a password.
Definition: network_gui.h:39
char client_name[NETWORK_CLIENT_NAME_LENGTH]
name of the player (as client)
virtual NetworkRecvStatus Receive_SERVER_ERROR_QUIT(Packet *p)
Inform all clients that one client made an error and thus has quit/been disconnected: uint32 ID of th...
GUISettings gui
settings related to the GUI
Client requests the actual map.
Definition: tcp_game.h:73
void SetInfo(NetworkClientInfo *info)
Sets the client info for this socket handler.
Definition: tcp_game.h:540
uint32 _frame_counter
The current frame.
Definition: network.cpp:72
The server has banned us.
Definition: core.h:35
uint64 Recv_uint64()
Read a 64 bits integer from the packet.
Definition: packet.cpp:267
void ClearErrorMessages()
Clear all errors from the queue.
Definition: error_gui.cpp:336
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
Definition: string_func.h:59
CompanyByte _current_company
Company currently doing an action.
Definition: company_cmd.cpp:47
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.
virtual NetworkRecvStatus Receive_SERVER_NEED_GAME_PASSWORD(Packet *p)
Indication to the client that the server needs a game password.
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:84
void NetworkClientSetCompanyPassword(const char *password)
Set/Reset company password on the client side.
Client executed a command and sends it to the server.
Definition: tcp_game.h:95
ClientID
&#39;Unique&#39; identifier to be given to clients
Definition: network_type.h:43
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:63
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:110
The client telling the server it wants to join.
Definition: tcp_game.h:41
virtual NetworkRecvStatus Receive_SERVER_MAP_BEGIN(Packet *p)
Sends that the server will begin with sending the map to the client: uint32 Current frame...
uint32 _frame_counter_server
The frame_counter of the server, if in network-mode.
Definition: network.cpp:70
uint16 num_station[NETWORK_VEH_END]
How many stations are there of this type?
Definition: network_type.h:63
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
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:47
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:194
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
virtual NetworkRecvStatus Receive_SERVER_RCON(Packet *p)
Send the result of an issues RCon command back to the client: uint16 Colour code. ...
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:121
bool NetworkMaxCompaniesReached()
Check if max_companies has been reached on the server (local check only).
bool _network_server
network-server is active
Definition: network.cpp:57
static NetworkRecvStatus SendQuit()
Tell the server we would like to quit.
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-NULL) 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.
virtual NetworkRecvStatus Receive_SERVER_MAP_DONE(Packet *p)
Sends that all data of the map are sent to the client:
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:32
uint32 _network_join_bytes_total
The total number of bytes to download.
The client is downloading the map.
Client said something that should be distributed.
Definition: tcp_game.h:99
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:65
static NetworkRecvStatus SendGetMap()
Request the map from the server.
void Restore()
Restore the variable.
static NetworkRecvStatus SendCommand(const CommandPacket *cp)
Send a command to the server.
Money money
The amount of money the company has.
Definition: network_gui.h:36
void ReceiveGRFIdentifier(Packet *p, GRFIdentifier *grf)
Deserializes the GRFIdentifier (GRF ID and MD5 checksum) from the packet.
Definition: core.cpp:122
Last action was requesting game (server) password.
uint16 Recv_uint16()
Read a 16 bits integer from the packet.
Definition: packet.cpp:235
bool CanSendReceive()
Check whether this socket can send or receive something.
Definition: tcp.cpp:229
Base socket handler for all TCP sockets.
Definition: tcp_game.h:152
static uint32 BSWAP32(uint32 x)
Perform a 32 bits endianness bitswap on x.
Owner
Enum for all companies/owners.
Definition: company_type.h:20
virtual NetworkRecvStatus Receive_SERVER_FRAME(Packet *p)
Sends the current frame counter to the client: uint32 Frame counter uint32 Frame counter max (how far...
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:126
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:3148
bool my_cmd
did the command originate from "me"
size_t Read(byte *rbuf, size_t size)
Read a given number of bytes from the savegame.
Date _date
Current date in days (day counter)
Definition: date.cpp:28
Company view; Window numbers:
Definition: window_type.h:364
DetailedFileType
Kinds of files in each AbstractFileType.
Definition: fileio_type.h:30
virtual NetworkRecvStatus Receive_SERVER_MAP_SIZE(Packet *p)
Sends the size of the map to the client.
uint32 _frame_counter_max
To where we may go with our clients.
Definition: network.cpp:71
static bool GameLoop()
Actual game loop for the client.
bool _network_first_time
Whether we have finished joining or not.
Definition: network.cpp:80
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:82
Money income
How much did the company earned last year.
Definition: network_gui.h:37
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:89
bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf=NULL)
Load the specified savegame but on error do different things.
Definition: openttd.cpp:1000
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:290
virtual NetworkRecvStatus Receive_SERVER_CONFIG_UPDATE(Packet *p)
Update the clients knowledge of the max settings: uint8 Maximum number of companies allowed...
Request information about all companies.
Definition: tcp_game.h:45
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:79
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