1#include "local_server.h"
2
3#include <base/fs.h>
4#include <base/mem.h>
5#include <base/net.h>
6#include <base/process.h>
7#include <base/secure.h>
8#include <base/str.h>
9#include <base/time.h>
10
11#include <engine/serverbrowser.h>
12#include <engine/storage.h>
13
14#include <game/client/gameclient.h>
15#include <game/localization.h>
16
17#include <cstdlib>
18
19#if defined(CONF_PLATFORM_ANDROID)
20#include <android/android_main.h>
21#endif
22
23// File that the server writes its port to, unique per client process
24static const char *PortFile(char *pBuf, unsigned BufSize)
25{
26 str_format(buffer: pBuf, buffer_size: BufSize, format: "local_server_port.%d.txt", process_id());
27 return pBuf;
28}
29
30void CLocalServer::Reset()
31{
32 mem_zero(block: m_aRconPassword, size: sizeof(m_aRconPassword));
33 m_Port = 0;
34 m_WaitingForPort = false;
35 m_ConnectRequested = false;
36
37 char aPortFile[IO_MAX_PATH_LENGTH];
38 Storage()->RemoveFile(pFilename: PortFile(pBuf: aPortFile, BufSize: sizeof(aPortFile)), Type: IStorage::TYPE_SAVE);
39}
40
41void CLocalServer::WaitForPort()
42{
43 m_WaitingForPort = true;
44 m_StartTime = time_get_nanoseconds();
45 m_NextPortCheck = m_StartTime;
46}
47
48void CLocalServer::OnServerStarted()
49{
50 WaitForPort();
51 GameClient()->m_Menus.ForceRefreshLanPage();
52}
53
54bool CLocalServer::RunServer(const std::vector<const char *> &vpArguments)
55{
56 Reset();
57
58 char aPortFile[IO_MAX_PATH_LENGTH];
59 char aPortFileCommand[IO_MAX_PATH_LENGTH + 16];
60 str_format(buffer: aPortFileCommand, buffer_size: sizeof(aPortFileCommand), format: "sv_port_file %s", PortFile(pBuf: aPortFile, BufSize: sizeof(aPortFile)));
61
62 secure_random_password(buffer: m_aRconPassword, length: sizeof(m_aRconPassword), pw_length: 16);
63 char aAuthCommand[64 + sizeof(m_aRconPassword)];
64 str_format(buffer: aAuthCommand, buffer_size: sizeof(aAuthCommand), format: "auth_add %s admin %s", DEFAULT_SAVED_RCON_USER, m_aRconPassword);
65
66 std::vector<const char *> vpArgumentsWithAuth = vpArguments;
67 vpArgumentsWithAuth.push_back(x: aPortFileCommand);
68 vpArgumentsWithAuth.push_back(x: aAuthCommand);
69
70#if defined(CONF_PLATFORM_ANDROID)
71 if(StartAndroidServer(vpArgumentsWithAuth.data(), vpArgumentsWithAuth.size()))
72 {
73 OnServerStarted();
74 return true;
75 }
76 else
77 {
78 Client()->AddWarning(SWarning(Localize("Server could not be started. Make sure to grant the notification permission in the app settings so the server can run in the background.")));
79 Reset();
80 return false;
81 }
82#else
83 char aBuf[IO_MAX_PATH_LENGTH];
84 Storage()->GetBinaryPath(PLAT_SERVER_EXEC, pBuffer: aBuf, BufferSize: sizeof(aBuf));
85#if defined(CONF_PLATFORM_MACOS)
86 if(!fs_is_file(aBuf) && fs_parent_dir(aBuf) == 0)
87 {
88 str_append(aBuf, "/../../../DDNet-Server.app/Contents/MacOS/");
89 str_append(aBuf, PLAT_SERVER_EXEC);
90 }
91#endif
92 // No / in binary path means to search in $PATH, so it is expected that the file can't be opened. Just try executing anyway.
93 if(str_find(haystack: aBuf, needle: "/") == nullptr || fs_is_file(path: aBuf))
94 {
95 m_Process = process_execute(file: aBuf, window_state: EShellExecuteWindowState::BACKGROUND, arguments: vpArgumentsWithAuth.data(), num_arguments: vpArgumentsWithAuth.size());
96 if(m_Process != INVALID_PROCESS)
97 {
98 OnServerStarted();
99 return true;
100 }
101 else
102 {
103 Client()->AddWarning(Warning: SWarning(Localize(pStr: "Server could not be started")));
104 Reset();
105 return false;
106 }
107 }
108 else
109 {
110 Client()->AddWarning(Warning: SWarning(Localize(pStr: "Server executable not found, can't run server")));
111 Reset();
112 return false;
113 }
114#endif
115}
116
117void CLocalServer::KillServer()
118{
119#if defined(CONF_PLATFORM_ANDROID)
120 ExecuteAndroidServerCommand("shutdown");
121 GameClient()->m_Menus.ForceRefreshLanPage();
122#else
123 if(m_Process != INVALID_PROCESS && process_kill(process: m_Process))
124 {
125 m_Process = INVALID_PROCESS;
126 GameClient()->m_Menus.ForceRefreshLanPage();
127 }
128#endif
129 Reset();
130}
131
132bool CLocalServer::IsServerRunning()
133{
134#if defined(CONF_PLATFORM_ANDROID)
135 return IsAndroidServerRunning();
136#else
137 if(m_Process != INVALID_PROCESS && !process_is_alive(process: m_Process))
138 {
139 if(m_ConnectRequested)
140 {
141 Client()->AddWarning(Warning: SWarning(Localize(pStr: "Server could not be started")));
142 }
143 KillServer();
144 }
145 return m_Process != INVALID_PROCESS;
146#endif
147}
148
149void CLocalServer::RconAuthIfPossible()
150{
151 if(!IsServerRunning() ||
152 m_aRconPassword[0] == '\0' ||
153 !net_addr_is_local(addr: &Client()->ServerAddress()))
154 {
155 return;
156 }
157 Client()->RconAuth(pUsername: DEFAULT_SAVED_RCON_USER, pPassword: m_aRconPassword, Dummy: g_Config.m_ClDummy);
158}
159
160void CLocalServer::Connect()
161{
162 // The server reports its port asynchronously, so connect as soon as it is known
163 m_ConnectRequested = true;
164 if(m_Port == 0 && !m_WaitingForPort)
165 {
166 WaitForPort();
167 }
168}
169
170void CLocalServer::CancelConnect()
171{
172 m_ConnectRequested = false;
173}
174
175void CLocalServer::Update()
176{
177 if(m_WaitingForPort && time_get_nanoseconds() >= m_NextPortCheck)
178 {
179 m_NextPortCheck = time_get_nanoseconds() + std::chrono::milliseconds(100);
180 char aPortFile[IO_MAX_PATH_LENGTH];
181 char *pPort = Storage()->ReadFileStr(pFilename: PortFile(pBuf: aPortFile, BufSize: sizeof(aPortFile)), Type: IStorage::TYPE_SAVE);
182 if(pPort != nullptr)
183 {
184 const int Port = str_toint(str: pPort);
185 free(ptr: pPort);
186 Storage()->RemoveFile(pFilename: aPortFile, Type: IStorage::TYPE_SAVE);
187 // Ignore a file without a valid port, the fallback below decides then
188 if(Port > 0 && Port <= 65535)
189 {
190 m_Port = Port;
191 m_WaitingForPort = false;
192 }
193 }
194
195 if(m_WaitingForPort)
196 {
197 const std::chrono::nanoseconds Waiting = time_get_nanoseconds() - m_StartTime;
198 if(Waiting > std::chrono::seconds(5) && !IsServerRunning())
199 {
200 // The Android server service only starts running asynchronously, so give
201 // the server time to start before considering it failed
202 m_WaitingForPort = false;
203 if(m_ConnectRequested)
204 {
205 m_ConnectRequested = false;
206 Client()->AddWarning(Warning: SWarning(Localize(pStr: "Server could not be started")));
207 }
208 }
209 else if(Waiting > std::chrono::seconds(5))
210 {
211 // The server is running but never reported its port, could lack
212 // permissions to write port file.
213 m_Port = IServerBrowser::LAN_PORT_BEGIN;
214 m_WaitingForPort = false;
215 mem_zero(block: m_aRconPassword, size: sizeof(m_aRconPassword));
216 }
217 }
218 }
219
220 if(m_ConnectRequested)
221 {
222 const IClient::EClientState State = Client()->State();
223 if(State != IClient::STATE_OFFLINE && State != IClient::STATE_ONLINE)
224 {
225 // A connection that the user started in the meantime supersedes the request
226 m_ConnectRequested = false;
227 }
228 else if(m_Port != 0)
229 {
230 m_ConnectRequested = false;
231 char aAddress[32];
232 str_format(buffer: aAddress, buffer_size: sizeof(aAddress), format: "localhost:%d", m_Port);
233 GameClient()->m_Menus.Connect(pAddress: aAddress);
234 }
235 }
236}
237