1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
|
// Copyright Epic Games, Inc. All Rights Reserved.
#include "ui_cmd.h"
#include <zencore/except_fmt.h>
#include <zencore/fmtutils.h>
#include <zencore/logging.h>
#include <zencore/process.h>
#include <zenutil/consoletui.h>
#include <zenutil/zenserverprocess.h>
#if ZEN_PLATFORM_WINDOWS
# include <zencore/windows.h>
# include <shellapi.h>
#endif
namespace zen {
namespace {
struct RunningServerInfo
{
uint16_t Port;
uint32_t Pid;
std::string SessionId;
std::string CmdLine;
};
static std::vector<RunningServerInfo> CollectRunningServers()
{
std::vector<RunningServerInfo> Servers;
ZenServerState State;
if (!State.InitializeReadOnly())
return Servers;
State.Snapshot([&](const ZenServerState::ZenServerEntry& Entry) {
StringBuilder<25> SessionSB;
Entry.GetSessionId().ToString(SessionSB);
std::error_code CmdLineEc;
std::string CmdLine = GetProcessCommandLine(static_cast<int>(Entry.Pid.load()), CmdLineEc);
Servers.push_back({Entry.EffectiveListenPort.load(), Entry.Pid.load(), std::string(SessionSB.c_str()), std::move(CmdLine)});
});
return Servers;
}
} // namespace
UiCommand::UiCommand()
{
m_Options.add_options()("h,help", "Print help");
m_Options.add_options()("a,all", "Open dashboard for all running instances", cxxopts::value(m_All)->default_value("false"));
m_Options.add_option("", "u", "hosturl", kHostUrlHelp, cxxopts::value(m_HostName)->default_value(""), "<hosturl>");
m_Options.add_option("",
"p",
"path",
"Dashboard path (default: /dashboard/)",
cxxopts::value(m_DashboardPath)->default_value("/dashboard/"),
"<path>");
m_Options.parse_positional("path");
}
UiCommand::~UiCommand()
{
}
void
UiCommand::OpenBrowser(std::string_view HostName)
{
// Allow shortcuts for specifying dashboard path, and ensure it is in a format we expect
// (leading slash, trailing slash if no file extension)
if (!m_DashboardPath.empty())
{
if (m_DashboardPath[0] != '/')
{
m_DashboardPath = "/dashboard/" + m_DashboardPath;
}
if (m_DashboardPath.find_last_of('.') == std::string::npos && m_DashboardPath.back() != '/')
{
m_DashboardPath += '/';
}
}
bool Success = false;
ExtendableStringBuilder<256> FullUrl;
FullUrl << HostName << m_DashboardPath;
#if ZEN_PLATFORM_WINDOWS
HINSTANCE Result = ShellExecuteA(nullptr, "open", FullUrl.c_str(), nullptr, nullptr, SW_SHOWNORMAL);
Success = reinterpret_cast<intptr_t>(Result) > 32;
#else
// Validate URL doesn't contain shell metacharacters that could lead to command injection
std::string_view FullUrlView = FullUrl;
constexpr std::string_view DangerousChars = ";|&$`\\\"'<>(){}[]!#*?~\n\r";
if (FullUrlView.find_first_of(DangerousChars) != std::string_view::npos)
{
throw OptionParseException(fmt::format("URL contains invalid characters: '{}'", FullUrl), m_Options.help());
}
# if ZEN_PLATFORM_MAC
std::string Command = fmt::format("open \"{}\"", FullUrl);
# elif ZEN_PLATFORM_LINUX
std::string Command = fmt::format("xdg-open \"{}\"", FullUrl);
# else
ZEN_NOT_IMPLEMENTED("Browser launching not implemented on this platform");
# endif
Success = system(Command.c_str()) == 0;
#endif
if (!Success)
{
throw zen::runtime_error("Failed to launch browser for '{}'", FullUrl);
}
ZEN_CONSOLE("Web browser launched for '{}' successfully", FullUrl);
}
void
UiCommand::Run(const ZenCliOptions& GlobalOptions, int argc, char** argv)
{
using namespace std::literals;
ZEN_UNUSED(GlobalOptions);
if (!ParseOptions(argc, argv))
{
return;
}
// Resolve target server
uint16_t ServerPort = 0;
if (m_HostName.empty())
{
// Auto-discover running instances.
std::vector<RunningServerInfo> Servers = CollectRunningServers();
if (m_All)
{
if (Servers.empty())
{
throw OptionParseException("No running Zen server instances found", m_Options.help());
}
for (const auto& Server : Servers)
{
OpenBrowser(fmt::format("http://localhost:{}", Server.Port));
}
return;
}
// If multiple are found and we have an interactive terminal, present a picker
// instead of silently using the first one.
if (Servers.size() > 1 && IsTuiAvailable())
{
std::vector<std::string> Labels;
Labels.reserve(Servers.size() + 1);
Labels.push_back(fmt::format("(all {} instances)", Servers.size()));
const int32_t Cols = static_cast<int32_t>(TuiConsoleColumns());
constexpr int32_t kIndicator = 3; // " > " or " " prefix
constexpr int32_t kSeparator = 2; // " " before cmdline
constexpr int32_t kEllipsis = 3; // "..."
for (const auto& Server : Servers)
{
std::string Label = fmt::format("port {:<5} pid {:<7} session {}", Server.Port, Server.Pid, Server.SessionId);
if (!Server.CmdLine.empty())
{
int32_t Available = Cols - kIndicator - kSeparator - static_cast<int32_t>(Label.size());
if (Available > kEllipsis)
{
Label += " ";
if (static_cast<int32_t>(Server.CmdLine.size()) <= Available)
{
Label += Server.CmdLine;
}
else
{
Label.append(Server.CmdLine, 0, static_cast<size_t>(Available - kEllipsis));
Label += "...";
}
}
}
Labels.push_back(std::move(Label));
}
int SelectedIdx = TuiPickOne("Multiple Zen server instances found. Select one to open:", Labels);
if (SelectedIdx < 0)
return; // User cancelled
if (SelectedIdx == 0)
{
// "All" selected
for (const auto& Server : Servers)
{
OpenBrowser(fmt::format("http://localhost:{}", Server.Port));
}
return;
}
ServerPort = Servers[SelectedIdx - 1].Port;
m_HostName = fmt::format("http://localhost:{}", ServerPort);
}
if (m_HostName.empty())
{
// Single or zero instances, or not an interactive terminal:
// fall back to default resolution (picks first instance or returns empty)
m_HostName = ResolveTargetHostSpec("", ServerPort);
}
}
else
{
if (m_All)
{
throw OptionParseException("--all cannot be used together with --hosturl", m_Options.help());
}
m_HostName = ResolveTargetHostSpec(m_HostName, ServerPort);
}
if (m_HostName.empty())
{
throw OptionParseException("Unable to resolve server specification", m_Options.help());
}
if (IsUnixSocketSpec(m_HostName))
{
throw std::runtime_error("Cannot open browser for a Unix domain socket connection");
}
OpenBrowser(m_HostName);
}
} // namespace zen
|