id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
10,529
|
webserver.h
|
tindy2013_subconverter/src/server/webserver.h
|
#ifndef WEBSERVER_H_INCLUDED
#define WEBSERVER_H_INCLUDED
#include <string>
#include <map>
#include <atomic>
#include <curl/curlver.h>
#include "utils/map_extra.h"
#include "utils/string.h"
#include "version.h"
struct Request
{
std::string method;
std::string url;
string_multimap argument;
string_icase_map headers;
std::string postdata;
};
struct Response
{
int status_code = 200;
std::string content_type;
string_icase_map headers;
};
using response_callback = std::string (*)(Request&, Response&); //process arguments and POST data and return served-content
#define RESPONSE_CALLBACK_ARGS Request &request, Response &response
struct listener_args
{
std::string listen_address;
int port;
int max_conn;
int max_workers;
void (*looper_callback)() = nullptr;
uint32_t looper_interval = 200;
};
struct responseRoute
{
std::string method;
std::string path;
std::string content_type;
response_callback rc {};
};
class WebServer
{
public:
std::string user_agent_str = "subconverter/" VERSION " cURL/" LIBCURL_VERSION;
std::atomic_bool SERVER_EXIT_FLAG{false};
// file server
bool serve_file = false;
std::string serve_file_root;
// basic authentication
bool require_auth = false;
std::string auth_user, auth_password, auth_realm = "Please enter username and password:";
void stop_web_server();
void append_response(const std::string &method, const std::string &uri, const std::string &content_type, response_callback response)
{
responseRoute rr;
rr.method = method;
rr.path = uri;
rr.content_type = content_type;
rr.rc = response;
responses.emplace_back(std::move(rr));
}
void append_redirect(const std::string &uri, const std::string &target)
{
redirect_map[uri] = target;
}
void reset_redirect()
{
std::map<std::string, std::string>().swap(redirect_map);
}
int start_web_server(listener_args *args);
int start_web_server_multi(listener_args *args);
std::vector<responseRoute> responses;
string_map redirect_map;
};
#endif // WEBSERVER_H_INCLUDED
| 2,187
|
C++
|
.h
| 76
| 24.592105
| 136
| 0.692785
|
tindy2013/subconverter
| 12,883
| 2,744
| 197
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,530
|
socket.h
|
tindy2013_subconverter/src/server/socket.h
|
#ifndef SOCKET_H_INCLUDED
#define SOCKET_H_INCLUDED
#ifdef _WIN32
#ifndef WINVER
#define WINVER 0x0501
#endif // WINVER
#include <ws2tcpip.h>
#include <winsock2.h>
#else
//translate windows functions to linux functions
#define SOCKET int
#define INVALID_SOCKET (SOCKET)(~0)
#define SOCKET_ERROR (-1)
#define closesocket close
#define SOCKADDR_IN sockaddr_in
#define ZeroMemory(d,l) memset((d), 0, (l))
#define ioctlsocket ioctl
#ifndef SA_INTERRUPT
#define SA_INTERRUPT 0 //ignore this setting
#endif
#define SD_BOTH SHUT_RDWR
#ifndef __hpux
#include <sys/select.h>
#endif /* __hpux */
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <netdb.h>
#include <signal.h>
#include <unistd.h>
typedef sockaddr *LPSOCKADDR;
#endif // _WIN32
#endif // SOCKET_H_INCLUDED
| 858
|
C++
|
.h
| 36
| 22.777778
| 48
| 0.768293
|
tindy2013/subconverter
| 12,883
| 2,744
| 197
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,531
|
proxygroup.h
|
tindy2013_subconverter/src/config/proxygroup.h
|
#ifndef PROXYGROUP_H_INCLUDED
#define PROXYGROUP_H_INCLUDED
#include "def.h"
enum class ProxyGroupType
{
Select,
URLTest,
Fallback,
LoadBalance,
Relay,
SSID,
Smart
};
enum class BalanceStrategy
{
ConsistentHashing,
RoundRobin
};
struct ProxyGroupConfig
{
String Name;
ProxyGroupType Type;
StrArray Proxies;
StrArray UsingProvider;
String Url;
Integer Interval = 0;
Integer Timeout = 0;
Integer Tolerance = 0;
BalanceStrategy Strategy = BalanceStrategy::ConsistentHashing;
Boolean Lazy;
Boolean DisableUdp;
Boolean Persistent;
Boolean EvaluateBeforeUse;
String TypeStr() const
{
switch(Type)
{
case ProxyGroupType::Select: return "select";
case ProxyGroupType::URLTest: return "url-test";
case ProxyGroupType::LoadBalance: return "load-balance";
case ProxyGroupType::Fallback: return "fallback";
case ProxyGroupType::Relay: return "relay";
case ProxyGroupType::SSID: return "ssid";
case ProxyGroupType::Smart: return "smart";
}
return "";
}
String StrategyStr() const
{
switch(Strategy)
{
case BalanceStrategy::ConsistentHashing: return "consistent-hashing";
case BalanceStrategy::RoundRobin: return "round-robin";
}
return "";
}
};
using ProxyGroupConfigs = std::vector<ProxyGroupConfig>;
#endif // PROXYGROUP_H_INCLUDED
| 1,513
|
C++
|
.h
| 59
| 19.694915
| 81
| 0.663209
|
tindy2013/subconverter
| 12,883
| 2,744
| 197
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,532
|
crontask.h
|
tindy2013_subconverter/src/config/crontask.h
|
#ifndef CRONTASK_H_INCLUDED
#define CRONTASK_H_INCLUDED
#include "def.h"
struct CronTaskConfig
{
String Name;
String CronExp;
String Path;
Integer Timeout = 0;
};
using CronTaskConfigs = std::vector<CronTaskConfig>;
#endif // CRONTASK_H_INCLUDED
| 266
|
C++
|
.h
| 12
| 19.5
| 52
| 0.76
|
tindy2013/subconverter
| 12,883
| 2,744
| 197
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,533
|
regmatch.h
|
tindy2013_subconverter/src/config/regmatch.h
|
#ifndef REGMATCH_H_INCLUDED
#define REGMATCH_H_INCLUDED
#include "def.h"
struct RegexMatchConfig
{
String Match;
String Replace;
String Script;
};
using RegexMatchConfigs = std::vector<RegexMatchConfig>;
#endif // REGMATCH_H_INCLUDED
| 250
|
C++
|
.h
| 11
| 20.272727
| 56
| 0.782979
|
tindy2013/subconverter
| 12,883
| 2,744
| 197
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,534
|
binding.h
|
tindy2013_subconverter/src/config/binding.h
|
#ifndef BINDING_H_INCLUDED
#define BINDING_H_INCLUDED
#include <toml.hpp>
#include "handler/settings.h"
#include "crontask.h"
#include "proxygroup.h"
#include "regmatch.h"
#include "ruleset.h"
namespace toml
{
template<>
struct from<ProxyGroupConfig>
{
static ProxyGroupConfig from_toml(const value& v)
{
ProxyGroupConfig conf;
conf.Name = toml::find<String>(v, "name");
String type = toml::find<String>(v, "type");
String strategy = toml::find_or<String>(v, "strategy", "");
switch(hash_(type))
{
case "select"_hash:
conf.Type = ProxyGroupType::Select;
break;
case "url-test"_hash:
conf.Type = ProxyGroupType::URLTest;
conf.Url = toml::find<String>(v, "url");
conf.Interval = toml::find<Integer>(v, "interval");
conf.Tolerance = toml::find_or<Integer>(v, "tolerance", 0);
if(v.contains("lazy"))
conf.Lazy = toml::find_or<bool>(v, "lazy", false);
if(v.contains("evaluate-before-use"))
conf.EvaluateBeforeUse = toml::find_or(v, "evaluate-before-use", conf.EvaluateBeforeUse.get());
break;
case "load-balance"_hash:
conf.Type = ProxyGroupType::LoadBalance;
conf.Url = toml::find<String>(v, "url");
conf.Interval = toml::find<Integer>(v, "interval");
switch(hash_(strategy))
{
case "consistent-hashing"_hash:
conf.Strategy = BalanceStrategy::ConsistentHashing;
break;
case "round-robin"_hash:
conf.Strategy = BalanceStrategy::RoundRobin;
break;
}
if(v.contains("persistent"))
conf.Persistent = toml::find_or(v, "persistent", conf.Persistent.get());
break;
case "fallback"_hash:
conf.Type = ProxyGroupType::Fallback;
conf.Url = toml::find<String>(v, "url");
conf.Interval = toml::find<Integer>(v, "interval");
if(v.contains("evaluate-before-use"))
conf.EvaluateBeforeUse = toml::find_or(v, "evaluate-before-use", conf.EvaluateBeforeUse.get());
break;
case "relay"_hash:
conf.Type = ProxyGroupType::Relay;
break;
case "ssid"_hash:
conf.Type = ProxyGroupType::SSID;
break;
case "smart"_hash:
conf.Type = ProxyGroupType::Smart;
conf.Url = toml::find<String>(v, "url");
conf.Interval = toml::find<Integer>(v, "interval");
conf.Tolerance = toml::find_or<Integer>(v, "tolerance", 0);
if(v.contains("lazy"))
conf.Lazy = toml::find_or<bool>(v, "lazy", false);
if(v.contains("evaluate-before-use"))
conf.EvaluateBeforeUse = toml::find_or(v, "evaluate-before-use", conf.EvaluateBeforeUse.get());
break;
default:
throw toml::syntax_error("Proxy Group has incorrect type, should be one of following:\n select, url-test, load-balance, fallback, relay, ssid", v.at("type").location());
}
conf.Timeout = toml::find_or(v, "timeout", 5);
conf.Proxies = toml::find_or<StrArray>(v, "rule", {});
conf.UsingProvider = toml::find_or<StrArray>(v, "use", {});
if(conf.Proxies.empty() && conf.UsingProvider.empty())
throw toml::syntax_error("Proxy Group must contains at least one of proxy match rule or provider", v.location());
if(v.contains("disable-udp"))
conf.DisableUdp = toml::find_or(v, "disable-udp", conf.DisableUdp.get());
return conf;
}
};
template<>
struct from<RulesetConfig>
{
static RulesetConfig from_toml(const value& v)
{
RulesetConfig conf;
conf.Group = toml::find<String>(v, "group");
String type = toml::find_or<String>(v, "type", "surge-ruleset");
switch(hash_(type))
{
/*
case "surge-ruleset"_hash:
conf.Type = RulesetType::SurgeRuleset;
conf.Url = "surge:";
break;
case "quantumultx"_hash:
conf.Type = RulesetType::QuantumultX;
conf.Url = "quanx:";
break;
case "clash-domain"_hash:
conf.Type = RulesetType::ClashDomain;
conf.Url = type;
break;
case "clash-ipcidr"_hash:
conf.Type = RulesetType::ClashIpCidr;
conf.Url = type;
break;
case "clash-classic"_hash:
conf.Type = RulesetType::ClashClassic;
conf.Url = type;
break;
*/
case "surge-ruleset"_hash:
conf.Url = "surge:";
break;
case "quantumultx"_hash:
conf.Url = "quanx:";
break;
case "clash-domain"_hash:
case "clash-ipcidr"_hash:
case "clash-classic"_hash:
conf.Url = type + ":";
break;
default:
throw toml::syntax_error("Ruleset has incorrect type, should be one of following:\n surge-ruleset, quantumultx, clash-domain, clash-ipcidr, clash-classic", v.at("type").location());
}
conf.Url += toml::find<String>(v, "ruleset");
conf.Interval = toml::find_or<Integer>(v, "interval", 86400);
return conf;
}
};
template<>
struct from<RegexMatchConfig>
{
static RegexMatchConfig from_toml(const value& v)
{
RegexMatchConfig conf;
if(v.contains("script"))
{
conf.Script = toml::find<String>(v, "script");
return conf;
}
conf.Match = toml::find<String>(v, "match");
if(v.contains("emoji"))
conf.Replace = toml::find<String>(v, "emoji");
else
conf.Replace = toml::find<String>(v, "replace");
return conf;
}
};
template<>
struct from<CronTaskConfig>
{
static CronTaskConfig from_toml(const value& v)
{
CronTaskConfig conf;
conf.Name = toml::find<String>(v, "name");
conf.CronExp = toml::find<String>(v, "cronexp");
conf.Path = toml::find<String>(v, "path");
conf.Timeout = toml::find_or<Integer>(v, "timeout", 0);
return conf;
}
};
template<>
struct from<tribool>
{
static tribool from_toml(const value& v)
{
tribool t;
t.set(v.as_boolean());
return t;
}
};
}
namespace INIBinding
{
template<class T> struct from
{};
template<>
struct from<ProxyGroupConfig>
{
static ProxyGroupConfigs from_ini(const StrArray &arr)
{
ProxyGroupConfigs confs;
for(const String &x : arr)
{
unsigned int rules_upper_bound = 0;
ProxyGroupConfig conf;
StrArray vArray = split(x, "`");
if(vArray.size() < 3)
continue;
conf.Name = vArray[0];
String type = vArray[1];
rules_upper_bound = vArray.size();
switch(hash_(type))
{
case "select"_hash:
conf.Type = ProxyGroupType::Select;
break;
case "relay"_hash:
conf.Type = ProxyGroupType::Relay;
break;
case "url-test"_hash:
conf.Type = ProxyGroupType::URLTest;
break;
case "fallback"_hash:
conf.Type = ProxyGroupType::Fallback;
break;
case "load-balance"_hash:
conf.Type = ProxyGroupType::LoadBalance;
break;
case "ssid"_hash:
conf.Type = ProxyGroupType::SSID;
break;
case "smart"_hash:
conf.Type = ProxyGroupType::Smart;
break;
default:
continue;
}
if(conf.Type == ProxyGroupType::URLTest || conf.Type == ProxyGroupType::LoadBalance || conf.Type == ProxyGroupType::Fallback)
{
if(rules_upper_bound < 5)
continue;
rules_upper_bound -= 2;
conf.Url = vArray[rules_upper_bound];
parseGroupTimes(vArray[rules_upper_bound + 1], &conf.Interval, &conf.Timeout, &conf.Tolerance);
}
for(unsigned int i = 2; i < rules_upper_bound; i++)
{
if(startsWith(vArray[i], "!!PROVIDER="))
{
string_array list = split(vArray[i].substr(11), ",");
conf.UsingProvider.reserve(conf.UsingProvider.size() + list.size());
std::move(list.begin(), list.end(), std::back_inserter(conf.UsingProvider));
}
else
conf.Proxies.emplace_back(std::move(vArray[i]));
}
confs.emplace_back(std::move(conf));
}
return confs;
}
};
template<>
struct from<RulesetConfig>
{
static RulesetConfigs from_ini(const StrArray &arr)
{
/*
static const std::map<std::string, RulesetType> RulesetTypes = {
{"clash-domain:", RulesetType::ClashDomain},
{"clash-ipcidr:", RulesetType::ClashIpCidr},
{"clash-classic:", RulesetType::ClashClassic},
{"quanx:", RulesetType::QuantumultX},
{"surge:", RulesetType::SurgeRuleset}
};
*/
RulesetConfigs confs;
for(const String &x : arr)
{
RulesetConfig conf;
String::size_type pos = x.find(",");
if(pos == String::npos)
continue;
conf.Group = x.substr(0, pos);
if(x.substr(pos + 1, 2) == "[]")
{
conf.Url = x.substr(pos + 1);
//conf.Type = RulesetType::SurgeRuleset;
confs.emplace_back(std::move(conf));
continue;
}
String::size_type epos = x.rfind(",");
if(pos != epos)
{
conf.Interval = to_int(x.substr(epos + 1), 0);
conf.Url = x.substr(pos + 1, epos - pos - 1);
}
else
conf.Url = x.substr(pos + 1);
confs.emplace_back(std::move(conf));
}
return confs;
}
};
template<>
struct from<CronTaskConfig>
{
static CronTaskConfigs from_ini(const StrArray &arr)
{
CronTaskConfigs confs;
for(const String &x : arr)
{
CronTaskConfig conf;
StrArray vArray = split(x, "`");
if(vArray.size() < 3)
continue;
conf.Name = vArray[0];
conf.CronExp = vArray[1];
conf.Path = vArray[2];
if(vArray.size() > 3)
conf.Timeout = to_int(vArray[3], 0);
confs.emplace_back(std::move(conf));
}
return confs;
}
};
template<>
struct from<RegexMatchConfig>
{
static RegexMatchConfigs from_ini(const StrArray &arr, const std::string &delimiter)
{
RegexMatchConfigs confs;
for(const String &x : arr)
{
RegexMatchConfig conf;
if(startsWith(x, "script:"))
{
conf.Script = x.substr(7);
confs.emplace_back(std::move(conf));
continue;
}
String::size_type pos = x.rfind(delimiter);
conf.Match = x.substr(0, pos);
if(pos != String::npos && pos < x.size() - 1)
conf.Replace = x.substr(pos + 1);
confs.emplace_back(std::move(conf));
}
return confs;
}
};
}
#endif // BINDING_H_INCLUDED
| 13,029
|
C++
|
.h
| 340
| 24.255882
| 198
| 0.479836
|
tindy2013/subconverter
| 12,883
| 2,744
| 197
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,535
|
ruleset.h
|
tindy2013_subconverter/src/config/ruleset.h
|
#ifndef RULESET_H_INCLUDED
#define RULESET_H_INCLUDED
#include "def.h"
enum class RulesetType
{
SurgeRuleset,
QuantumultX,
ClashDomain,
ClashIpCidr,
ClashClassic
};
struct RulesetConfig
{
String Group;
//RulesetType Type = RulesetType::SurgeRuleset;
String Url;
Integer Interval = 86400;
bool operator==(const RulesetConfig &r) const
{
return Group == r.Group && Url == r.Url && Interval == r.Interval;
}
};
using RulesetConfigs = std::vector<RulesetConfig>;
#endif // RULESET_H_INCLUDED
| 549
|
C++
|
.h
| 24
| 19.333333
| 74
| 0.707692
|
tindy2013/subconverter
| 12,883
| 2,744
| 197
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,536
|
def.h
|
tindy2013_subconverter/src/config/def.h
|
#ifndef DEF_H_INCLUDED
#define DEF_H_INCLUDED
#include <string>
#include <vector>
#include <tuple>
#include <cstdint>
#include "utils/string.h"
#include "utils/tribool.h"
using String = std::string;
using Integer = int32_t;
using StrArray = string_array;
using Boolean = tribool;
#endif // DEF_H_INCLUDED
| 309
|
C++
|
.h
| 13
| 22.461538
| 30
| 0.770548
|
tindy2013/subconverter
| 12,883
| 2,744
| 197
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,537
|
pty_compat.cc
|
mobile-shell_mosh/src/util/pty_compat.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include "src/include/config.h"
#if !defined( HAVE_FORKPTY ) || !defined( HAVE_CFMAKERAW )
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/stropts.h>
#include <termios.h>
#include <unistd.h>
#include "src/util/pty_compat.h"
#ifndef HAVE_FORKPTY
pid_t my_forkpty( int* amaster, char* name, const struct termios* termp, const struct winsize* winp )
{
/* For Solaris and AIX */
int master, slave;
char* slave_name;
pid_t pid;
#ifdef _AIX
#define PTY_DEVICE "/dev/ptc"
#else
#define PTY_DEVICE "/dev/ptmx"
#endif
master = open( PTY_DEVICE, O_RDWR | O_NOCTTY );
if ( master < 0 ) {
perror( "open(" PTY_DEVICE ")" );
return -1;
}
if ( grantpt( master ) < 0 ) {
perror( "grantpt" );
close( master );
return -1;
}
if ( unlockpt( master ) < 0 ) {
perror( "unlockpt" );
close( master );
return -1;
}
slave_name = ptsname( master );
if ( slave_name == NULL ) {
perror( "ptsname" );
close( master );
return -1;
}
slave = open( slave_name, O_RDWR | O_NOCTTY );
if ( slave < 0 ) {
perror( "open(slave)" );
close( master );
return -1;
}
#ifndef _AIX
if ( ioctl( slave, I_PUSH, "ptem" ) < 0 || ioctl( slave, I_PUSH, "ldterm" ) < 0 ) {
perror( "ioctl(I_PUSH)" );
close( slave );
close( master );
return -1;
}
#endif
if ( amaster != NULL )
*amaster = master;
if ( name != NULL )
strcpy( name, slave_name );
if ( termp != NULL ) {
if ( tcsetattr( slave, TCSAFLUSH, termp ) < 0 ) {
perror( "tcsetattr" );
exit( 1 );
}
}
// we need to set initial window size, or TIOCGWINSZ fails
struct winsize w;
w.ws_row = 25;
w.ws_col = 80;
w.ws_xpixel = 0;
w.ws_ypixel = 0;
if ( ioctl( slave, TIOCSWINSZ, &w ) < 0 ) {
perror( "ioctl TIOCSWINSZ" );
exit( 1 );
}
if ( winp != NULL ) {
if ( ioctl( slave, TIOCGWINSZ, winp ) < 0 ) {
perror( "ioctl TIOCGWINSZ" );
exit( 1 );
}
}
pid = fork();
switch ( pid ) {
case -1: /* Error */
perror( "fork()" );
return -1;
case 0: /* Child */
if ( setsid() < 0 )
perror( "setsid" );
#ifdef TIOCSCTTY
if ( ioctl( slave, TIOCSCTTY, NULL ) < 0 ) {
perror( "ioctl" );
return -1;
}
#else
{
int dummy_fd;
dummy_fd = open( slave_name, O_RDWR );
if ( dummy_fd < 0 ) {
perror( "open(slave_name)" );
return -1;
}
close( dummy_fd );
}
#endif /* TIOCSCTTY */
close( master );
dup2( slave, STDIN_FILENO );
dup2( slave, STDOUT_FILENO );
dup2( slave, STDERR_FILENO );
return 0;
default: /* Parent */
close( slave );
return pid;
}
}
#endif
#ifndef HAVE_CFMAKERAW
void my_cfmakeraw( struct termios* termios_p )
{
termios_p->c_iflag &= ~( IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON );
termios_p->c_oflag &= ~OPOST;
termios_p->c_lflag &= ~( ECHO | ECHONL | ICANON | ISIG | IEXTEN );
termios_p->c_cflag &= ~( CSIZE | PARENB );
termios_p->c_cflag |= CS8;
termios_p->c_cc[VMIN] = 1; // read() is satisfied after 1 char
termios_p->c_cc[VTIME] = 0; // No timer
}
#endif
#endif
| 4,723
|
C++
|
.cc
| 158
| 25.639241
| 101
| 0.631359
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,539
|
timestamp.cc
|
mobile-shell_mosh/src/util/timestamp.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include "src/include/config.h"
#include "src/util/timestamp.h"
#include <cerrno>
#if HAVE_CLOCK_GETTIME
#include <ctime>
#endif
#if HAVE_MACH_ABSOLUTE_TIME
#include <mach/error.h>
#include <mach/mach_time.h>
#endif
#if HAVE_GETTIMEOFDAY
#include <cstdio>
#include <sys/time.h>
#endif
// On Apple systems CLOCK_MONOTONIC is unfortunately able to go
// backwards in time. This breaks mosh when system is returning from
// suspend as described in ticket #1014. To avoid this issue prefer
// CLOCK_MONOTONIC_RAW on Apple systems when available.
#if defined( __APPLE__ ) && defined( CLOCK_MONOTONIC_RAW )
#define CLOCKTYPE CLOCK_MONOTONIC_RAW
#else
#define CLOCKTYPE CLOCK_MONOTONIC
#endif
static uint64_t millis_cache = -1;
uint64_t frozen_timestamp( void )
{
if ( millis_cache == uint64_t( -1 ) ) {
freeze_timestamp();
}
return millis_cache;
}
void freeze_timestamp( void )
{
// Try all our clock sources till we get something. This could
// break if a source only sometimes works in a given process.
#if HAVE_CLOCK_GETTIME
// Preferred clock source-- portable, monotonic, (should be)
// adjusted after system sleep
struct timespec tp;
if (
#if defined( __APPLE__ ) && defined( __MACH__ )
// Check for presence, for OS X SDK >= 10.12 and runtime < 10.12
&clock_gettime != NULL &&
#endif
clock_gettime( CLOCKTYPE, &tp ) == 0 ) {
uint64_t millis = tp.tv_nsec / 1000000;
millis += uint64_t( tp.tv_sec ) * 1000;
millis_cache = millis;
return;
}
#endif
#if HAVE_MACH_ABSOLUTE_TIME
// Monotonic, not adjusted after system sleep. OS X 10.12 has
// mach_continuous_time(), but also has clock_gettime().
static mach_timebase_info_data_t s_timebase_info;
static double absolute_to_millis = 0.0;
if ( absolute_to_millis == 0.0 ) {
if ( ERR_SUCCESS == mach_timebase_info( &s_timebase_info ) ) {
absolute_to_millis = 1e-6 * s_timebase_info.numer / s_timebase_info.denom;
} else
absolute_to_millis = -1.0;
}
// NB: mach_absolute_time() returns "absolute time units"
// We need to apply a conversion to get milliseconds.
if ( absolute_to_millis > 0.0 ) {
millis_cache = mach_absolute_time() * absolute_to_millis;
return;
}
#endif
#if HAVE_GETTIMEOFDAY
// Not monotonic.
// NOTE: If time steps backwards, timeouts may be confused.
struct timeval tv;
if ( gettimeofday( &tv, NULL ) ) {
perror( "gettimeofday" );
} else {
uint64_t millis = tv.tv_usec / 1000;
millis += uint64_t( tv.tv_sec ) * 1000;
millis_cache = millis;
return;
}
#else
#error "gettimeofday() unavailable-- required as timer of last resort"
#endif
}
| 4,115
|
C++
|
.cc
| 111
| 33.846847
| 80
| 0.721205
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,541
|
locale_utils.cc
|
mobile-shell_mosh/src/util/locale_utils.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include "src/include/config.h"
#include <cerrno>
#include <clocale>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#if HAVE_LANGINFO_H
#include <langinfo.h>
#endif
#include "src/util/locale_utils.h"
const std::string LocaleVar::str( void ) const
{
if ( name.empty() ) {
return std::string( "[no charset variables]" );
}
return name + "=" + value;
}
const LocaleVar get_ctype( void )
{
/* Reimplement the search logic, just for diagnostics */
if ( const char* all = getenv( "LC_ALL" ) ) {
return LocaleVar( "LC_ALL", all );
} else if ( const char* ctype = getenv( "LC_CTYPE" ) ) {
return LocaleVar( "LC_CTYPE", ctype );
} else if ( const char* lang = getenv( "LANG" ) ) {
return LocaleVar( "LANG", lang );
}
return LocaleVar( "", "" );
}
const char* locale_charset( void )
{
static const char ASCII_name[] = "US-ASCII";
/* Produce more pleasant name of US-ASCII */
const char* ret = nl_langinfo( CODESET );
if ( strcmp( ret, "ANSI_X3.4-1968" ) == 0 ) {
ret = ASCII_name;
}
return ret;
}
bool is_utf8_locale( void )
{
/* Verify locale calls for UTF-8 */
if ( strcmp( locale_charset(), "UTF-8" ) != 0 && strcmp( locale_charset(), "utf-8" ) != 0 ) {
return false;
}
return true;
}
void set_native_locale( void )
{
/* Adopt native locale */
if ( NULL == setlocale( LC_ALL, "" ) ) {
int saved_errno = errno;
if ( saved_errno == ENOENT ) {
LocaleVar ctype( get_ctype() );
fprintf( stderr, "The locale requested by %s isn't available here.\n", ctype.str().c_str() );
if ( !ctype.name.empty() ) {
fprintf( stderr, "Running `locale-gen %s' may be necessary.\n\n", ctype.value.c_str() );
}
} else {
errno = saved_errno;
perror( "setlocale" );
}
}
}
void clear_locale_variables( void )
{
unsetenv( "LANG" );
unsetenv( "LANGUAGE" );
unsetenv( "LC_CTYPE" );
unsetenv( "LC_NUMERIC" );
unsetenv( "LC_TIME" );
unsetenv( "LC_COLLATE" );
unsetenv( "LC_MONETARY" );
unsetenv( "LC_MESSAGES" );
unsetenv( "LC_PAPER" );
unsetenv( "LC_NAME" );
unsetenv( "LC_ADDRESS" );
unsetenv( "LC_TELEPHONE" );
unsetenv( "LC_MEASUREMENT" );
unsetenv( "LC_IDENTIFICATION" );
unsetenv( "LC_ALL" );
}
| 3,729
|
C++
|
.cc
| 109
| 30.715596
| 99
| 0.67879
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,542
|
terminal_parser_fuzzer.cc
|
mobile-shell_mosh/src/fuzz/terminal_parser_fuzzer.cc
|
#include <cstddef>
#include <cstdint>
#include "src/terminal/parser.h"
extern "C" int LLVMFuzzerTestOneInput( const uint8_t* data, size_t size )
{
Parser::UTF8Parser parser;
Parser::Actions result;
for ( size_t i = 0; i < size; i++ ) {
parser.input( data[i], result );
}
return 0;
}
| 301
|
C++
|
.cc
| 12
| 22.583333
| 73
| 0.684211
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,543
|
terminal_fuzzer.cc
|
mobile-shell_mosh/src/fuzz/terminal_fuzzer.cc
|
#include <cstddef>
#include <cstdint>
#include "src/statesync/completeterminal.h"
#include "src/terminal/parser.h"
extern "C" int LLVMFuzzerTestOneInput( const uint8_t* data, size_t size )
{
Terminal::Display display( false );
Terminal::Complete complete( 80, 24 );
Terminal::Framebuffer state( 80, 24 );
for ( size_t i = 0; i < size; i++ ) {
complete.act( Parser::UserByte( data[i] ) );
}
display.new_frame( true, state, complete.get_fb() );
return 0;
}
| 476
|
C++
|
.cc
| 15
| 29.333333
| 73
| 0.694323
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,544
|
crypto.cc
|
mobile-shell_mosh/src/crypto/crypto.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include <cassert>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <sys/resource.h>
#include "src/crypto/base64.h"
#include "src/crypto/byteorder.h"
#include "src/crypto/crypto.h"
#include "src/crypto/prng.h"
#include "src/util/fatal_assert.h"
using namespace Crypto;
long int myatoi( const char* str )
{
char* end;
errno = 0;
long int ret = strtol( str, &end, 10 );
if ( ( errno != 0 ) || ( end != str + strlen( str ) ) ) {
throw CryptoException( "Bad integer." );
}
return ret;
}
uint64_t Crypto::unique( void )
{
static uint64_t counter = 0;
uint64_t rv = counter++;
if ( counter == 0 ) {
throw CryptoException( "Counter wrapped", true );
}
return rv;
}
AlignedBuffer::AlignedBuffer( size_t len, const char* data ) : m_len( len ), m_allocated( NULL ), m_data( NULL )
{
size_t alloc_len = len ? len : 1;
#if defined( HAVE_POSIX_MEMALIGN )
if ( ( 0 != posix_memalign( &m_allocated, 16, alloc_len ) ) || ( m_allocated == NULL ) ) {
throw std::bad_alloc();
}
m_data = (char*)m_allocated;
#else
/* malloc() a region 15 bytes larger than we need, and find
the aligned offset within. */
m_allocated = malloc( 15 + alloc_len );
if ( m_allocated == NULL ) {
throw std::bad_alloc();
}
uintptr_t iptr = (uintptr_t)m_allocated;
if ( iptr & 0xF ) {
iptr += 16 - ( iptr & 0xF );
}
assert( !( iptr & 0xF ) );
assert( iptr >= (uintptr_t)m_allocated );
assert( iptr <= ( 15 + (uintptr_t)m_allocated ) );
m_data = (char*)iptr;
#endif /* !defined(HAVE_POSIX_MEMALIGN) */
if ( data ) {
memcpy( m_data, data, len );
}
}
Base64Key::Base64Key( std::string printable_key )
{
if ( printable_key.length() != 22 ) {
throw CryptoException( "Key must be 22 letters long." );
}
std::string base64 = printable_key + "==";
size_t len = 16;
if ( !base64_decode( base64.data(), 24, key, &len ) ) {
throw CryptoException( "Key must be well-formed base64." );
}
if ( len != 16 ) {
throw CryptoException( "Key must represent 16 octets." );
}
/* to catch changes after the first 128 bits */
if ( printable_key != this->printable_key() ) {
throw CryptoException( "Base64 key was not encoded 128-bit key." );
}
}
Base64Key::Base64Key()
{
PRNG().fill( key, sizeof( key ) );
}
Base64Key::Base64Key( PRNG& prng )
{
prng.fill( key, sizeof( key ) );
}
std::string Base64Key::printable_key( void ) const
{
char base64[24];
base64_encode( key, 16, base64, 24 );
if ( ( base64[23] != '=' ) || ( base64[22] != '=' ) ) {
throw CryptoException( std::string( "Unexpected output from base64_encode: " ) + std::string( base64, 24 ) );
}
base64[22] = 0;
return std::string( base64 );
}
Session::Session( Base64Key s_key )
: key( s_key ), ctx_buf( ae_ctx_sizeof() ), ctx( (ae_ctx*)ctx_buf.data() ), blocks_encrypted( 0 ),
plaintext_buffer( RECEIVE_MTU ), ciphertext_buffer( RECEIVE_MTU ), nonce_buffer( Nonce::NONCE_LEN )
{
if ( AE_SUCCESS != ae_init( ctx, key.data(), 16, 12, 16 ) ) {
throw CryptoException( "Could not initialize AES-OCB context." );
}
}
Session::~Session()
{
fatal_assert( ae_clear( ctx ) == AE_SUCCESS );
}
Nonce::Nonce( uint64_t val )
{
uint64_t val_net = htobe64( val );
memset( bytes, 0, 4 );
memcpy( bytes + 4, &val_net, 8 );
}
uint64_t Nonce::val( void ) const
{
uint64_t ret;
memcpy( &ret, bytes + 4, 8 );
return be64toh( ret );
}
Nonce::Nonce( const char* s_bytes, size_t len )
{
if ( len != 8 ) {
throw CryptoException( "Nonce representation must be 8 octets long." );
}
memset( bytes, 0, 4 );
memcpy( bytes + 4, s_bytes, 8 );
}
const std::string Session::encrypt( const Message& plaintext )
{
const size_t pt_len = plaintext.text.size();
const int ciphertext_len = pt_len + 16;
assert( (size_t)ciphertext_len <= ciphertext_buffer.len() );
assert( pt_len <= plaintext_buffer.len() );
memcpy( plaintext_buffer.data(), plaintext.text.data(), pt_len );
memcpy( nonce_buffer.data(), plaintext.nonce.data(), Nonce::NONCE_LEN );
if ( ciphertext_len
!= ae_encrypt( ctx, /* ctx */
nonce_buffer.data(), /* nonce */
plaintext_buffer.data(), /* pt */
pt_len, /* pt_len */
NULL, /* ad */
0, /* ad_len */
ciphertext_buffer.data(), /* ct */
NULL, /* tag */
AE_FINALIZE ) ) { /* final */
throw CryptoException( "ae_encrypt() returned error." );
}
blocks_encrypted += pt_len >> 4;
if ( pt_len & 0xF ) {
/* partial block */
blocks_encrypted++;
}
/* "Both the privacy and the authenticity properties of OCB degrade as
per s^2 / 2^128, where s is the total number of blocks that the
adversary acquires.... In order to ensure that s^2 / 2^128 remains
small, a given key should be used to encrypt at most 2^48 blocks (2^55
bits or 4 petabytes)"
-- http://tools.ietf.org/html/draft-krovetz-ocb-03
We deem it unlikely that a legitimate user will send 4 PB through a Mosh
session. If it happens, we simply kill the session. The server and
client use the same key, so we actually need to die after 2^47 blocks.
*/
if ( blocks_encrypted >> 47 ) {
throw CryptoException( "Encrypted 2^47 blocks.", true );
}
std::string text( ciphertext_buffer.data(), ciphertext_len );
return plaintext.nonce.cc_str() + text;
}
const Message Session::decrypt( const char* str, size_t len )
{
if ( len < 24 ) {
throw CryptoException( "Ciphertext must contain nonce and tag." );
}
int body_len = len - 8;
int pt_len = body_len - 16;
if ( pt_len < 0 ) { /* super-assertion that pt_len does not equal AE_INVALID */
fprintf( stderr, "BUG.\n" );
exit( 1 );
}
assert( (size_t)body_len <= ciphertext_buffer.len() );
assert( (size_t)pt_len <= plaintext_buffer.len() );
Nonce nonce( str, 8 );
memcpy( ciphertext_buffer.data(), str + 8, body_len );
memcpy( nonce_buffer.data(), nonce.data(), Nonce::NONCE_LEN );
if ( pt_len
!= ae_decrypt( ctx, /* ctx */
nonce_buffer.data(), /* nonce */
ciphertext_buffer.data(), /* ct */
body_len, /* ct_len */
NULL, /* ad */
0, /* ad_len */
plaintext_buffer.data(), /* pt */
NULL, /* tag */
AE_FINALIZE ) ) { /* final */
throw CryptoException( "Packet failed integrity check." );
}
const Message ret( nonce, std::string( plaintext_buffer.data(), pt_len ) );
return ret;
}
static rlim_t saved_core_rlimit;
/* Disable dumping core, as a precaution to avoid saving sensitive data
to disk. */
void Crypto::disable_dumping_core( void )
{
struct rlimit limit;
if ( 0 != getrlimit( RLIMIT_CORE, &limit ) ) {
/* We don't throw CryptoException because this is called very early
in main(), outside of 'try'. */
perror( "getrlimit(RLIMIT_CORE)" );
exit( 1 );
}
saved_core_rlimit = limit.rlim_cur;
limit.rlim_cur = 0;
if ( 0 != setrlimit( RLIMIT_CORE, &limit ) ) {
perror( "setrlimit(RLIMIT_CORE)" );
exit( 1 );
}
}
void Crypto::reenable_dumping_core( void )
{
/* Silent failure is safe. */
struct rlimit limit;
if ( 0 == getrlimit( RLIMIT_CORE, &limit ) ) {
limit.rlim_cur = saved_core_rlimit;
setrlimit( RLIMIT_CORE, &limit );
}
}
| 9,235
|
C++
|
.cc
| 254
| 31.795276
| 113
| 0.618877
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,546
|
ocb_internal.cc
|
mobile-shell_mosh/src/crypto/ocb_internal.cc
|
/*------------------------------------------------------------------------
/ OCB Version 3 Reference Code (Optimized C) Last modified 08-SEP-2012
/-------------------------------------------------------------------------
/ Copyright (c) 2012 Ted Krovetz.
/ Copyright 2022 Google LLC
/
/ Permission to use, copy, modify, and/or distribute this software for any
/ purpose with or without fee is hereby granted, provided that the above
/ copyright notice and this permission notice appear in all copies.
/
/ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
/ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
/ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
/ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
/ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
/ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
/ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
/
/ Phillip Rogaway holds patents relevant to OCB. See the following for
/ his patent grant: http://www.cs.ucdavis.edu/~rogaway/ocb/grant.htm
/
/ Special thanks to Keegan McAllister for suggesting several good improvements
/
/ Comments are welcome: Ted Krovetz <ted@krovetz.net> - Dedicated to Laurel K
/------------------------------------------------------------------------- */
// clang-format off
#include "src/include/config.h"
/* This module implements the ae.h interface for OpenSSL, Apple Common
/ Crypto, and Nettle. */
#if !defined(USE_OPENSSL_AES) && !defined(USE_APPLE_COMMON_CRYPTO_AES) && \
!defined(USE_NETTLE_AES)
#error ocb_internal.cc only works with OpenSSL, Apple Common Crypto, or Nettle
#endif
/* ----------------------------------------------------------------------- */
/* Usage notes */
/* ----------------------------------------------------------------------- */
/* - When AE_PENDING is passed as the 'final' parameter of any function,
/ the length parameters must be a multiple of (BPI*16).
/ - When available, SSE or AltiVec registers are used to manipulate data.
/ So, when on machines with these facilities, all pointers passed to
/ any function should be 16-byte aligned.
/ - Plaintext and ciphertext pointers may be equal (ie, plaintext gets
/ encrypted in-place), but no other pair of pointers may be equal.
/ - This code assumes all x86 processors have SSE2 and SSSE3 instructions
/ when compiling under MSVC. If untrue, alter the #define.
/ - This code is tested for C99 and recent versions of GCC and MSVC. */
/* ----------------------------------------------------------------------- */
/* User configuration options */
/* ----------------------------------------------------------------------- */
/* Set the AES key length to use and length of authentication tag to produce.
/ Setting either to 0 requires the value be set at runtime via ae_init().
/ Some optimizations occur for each when set to a fixed value. */
#define OCB_KEY_LEN 16 /* 0, 16, 24 or 32. 0 means set in ae_init */
#define OCB_TAG_LEN 16 /* 0 to 16. 0 means set in ae_init */
/* This implementation has built-in support for multiple AES APIs. Set any
/ one of the following to non-zero to specify which to use. */
#if 0
#define USE_APPLE_COMMON_CRYPTO_AES 0
#define USE_NETTLE_AES 0
#define USE_OPENSSL_AES 1 /* http://openssl.org */
#endif
/* During encryption and decryption, various "L values" are required.
/ The L values can be precomputed during initialization (requiring extra
/ space in ae_ctx), generated as needed (slightly slowing encryption and
/ decryption), or some combination of the two. L_TABLE_SZ specifies how many
/ L values to precompute. L_TABLE_SZ must be at least 3. L_TABLE_SZ*16 bytes
/ are used for L values in ae_ctx. Plaintext and ciphertexts shorter than
/ 2^L_TABLE_SZ blocks need no L values calculated dynamically. */
#define L_TABLE_SZ 16
/* Set L_TABLE_SZ_IS_ENOUGH non-zero iff you know that all plaintexts
/ will be shorter than 2^(L_TABLE_SZ+4) bytes in length. This results
/ in better performance. */
#define L_TABLE_SZ_IS_ENOUGH 1
/* ----------------------------------------------------------------------- */
/* Includes and compiler specific definitions */
/* ----------------------------------------------------------------------- */
#include "src/crypto/ae.h"
#include "src/crypto/crypto.h"
#include "src/util/fatal_assert.h"
#include <cstdlib>
#include <cstring>
#if defined(HAVE_STRINGS_H)
#include <strings.h>
#endif
#if defined(HAVE_ENDIAN_H)
#include <endian.h>
#elif defined(HAVE_SYS_ENDIAN_H)
#include <sys/types.h>
#include <sys/endian.h>
#endif
#include <new>
/* Define standard sized integers */
#if defined(_MSC_VER) && (_MSC_VER < 1600)
typedef unsigned __int8 uint8_t;
typedef unsigned __int32 uint32_t;
typedef unsigned __int64 uint64_t;
typedef __int64 int64_t;
#else
#include <stdint.h>
#endif
/* Compiler-specific intrinsics and fixes: bswap64, ntz */
#if _MSC_VER
#define inline __inline /* MSVC doesn't recognize "inline" in C */
#define restrict __restrict /* MSVC doesn't recognize "restrict" in C */
#define __SSE2__ (_M_IX86 || _M_AMD64 || _M_X64) /* Assume SSE2 */
#define __SSSE3__ (_M_IX86 || _M_AMD64 || _M_X64) /* Assume SSSE3 */
#include <intrin.h>
#pragma intrinsic(_byteswap_uint64, _BitScanForward, memcpy)
#elif __GNUC__
#ifndef inline
#define inline __inline__ /* No "inline" in GCC ansi C mode */
#endif
#ifndef restrict
#define restrict __restrict__ /* No "restrict" in GCC ansi C mode */
#endif
#endif
#if _MSC_VER
#define bswap64(x) _byteswap_uint64(x)
#elif HAVE_DECL_BSWAP64
/* nothing */
#elif HAVE_DECL___BUILTIN_BSWAP64
#define bswap64(x) __builtin_bswap64(x) /* GCC 4.3+ */
#else
#define bswap32(x) \
((((x) & 0xff000000u) >> 24) | (((x) & 0x00ff0000u) >> 8) | \
(((x) & 0x0000ff00u) << 8) | (((x) & 0x000000ffu) << 24))
static inline uint64_t bswap64(uint64_t x) {
union { uint64_t u64; uint32_t u32[2]; } in, out;
in.u64 = x;
out.u32[0] = bswap32(in.u32[1]);
out.u32[1] = bswap32(in.u32[0]);
return out.u64;
}
#endif
#if _MSC_VER
static inline unsigned ntz(unsigned x) {_BitScanForward(&x,x);return x;}
#elif HAVE_DECL___BUILTIN_CTZ
#define ntz(x) __builtin_ctz((unsigned)(x)) /* GCC 3.4+ */
#elif HAVE_DECL_FFS
#define ntz(x) (ffs(x) - 1)
#else
#if (L_TABLE_SZ <= 9) && (L_TABLE_SZ_IS_ENOUGH) /* < 2^13 byte texts */
static inline unsigned ntz(unsigned x) {
static const unsigned char tz_table[] = {0,
2,3,2,4,2,3,2,5,2,3,2,4,2,3,2,6,2,3,2,4,2,3,2,5,2,3,2,4,2,3,2,7,
2,3,2,4,2,3,2,5,2,3,2,4,2,3,2,6,2,3,2,4,2,3,2,5,2,3,2,4,2,3,2,8,
2,3,2,4,2,3,2,5,2,3,2,4,2,3,2,6,2,3,2,4,2,3,2,5,2,3,2,4,2,3,2,7,
2,3,2,4,2,3,2,5,2,3,2,4,2,3,2,6,2,3,2,4,2,3,2,5,2,3,2,4,2,3,2};
return tz_table[x/4];
}
#else /* From http://supertech.csail.mit.edu/papers/debruijn.pdf */
static inline unsigned ntz(unsigned x) {
static const unsigned char tz_table[32] =
{ 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9};
return tz_table[((uint32_t)((x & -x) * 0x077CB531u)) >> 27];
}
#endif
#endif
/* ----------------------------------------------------------------------- */
/* Define blocks and operations -- Patch if incorrect on your compiler. */
/* ----------------------------------------------------------------------- */
#if __SSE2__
#include <xmmintrin.h> /* SSE instructions and _mm_malloc */
#include <emmintrin.h> /* SSE2 instructions */
typedef __m128i block;
#define xor_block(x,y) _mm_xor_si128(x,y)
#define zero_block() _mm_setzero_si128()
#define unequal_blocks(x,y) \
(_mm_movemask_epi8(_mm_cmpeq_epi8(x,y)) != 0xffff)
#if __SSSE3__
#include <tmmintrin.h> /* SSSE3 instructions */
#define swap_if_le(b) \
_mm_shuffle_epi8(b,_mm_set_epi8(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15))
#else
static inline block swap_if_le(block b) {
block a = _mm_shuffle_epi32 (b, _MM_SHUFFLE(0,1,2,3));
a = _mm_shufflehi_epi16(a, _MM_SHUFFLE(2,3,0,1));
a = _mm_shufflelo_epi16(a, _MM_SHUFFLE(2,3,0,1));
return _mm_xor_si128(_mm_srli_epi16(a,8), _mm_slli_epi16(a,8));
}
#endif
static inline block gen_offset(uint64_t KtopStr[3], unsigned bot) {
block hi = _mm_load_si128((__m128i *)(KtopStr+0)); /* hi = B A */
block lo = _mm_loadu_si128((__m128i *)(KtopStr+1)); /* lo = C B */
__m128i lshift = _mm_cvtsi32_si128(bot);
__m128i rshift = _mm_cvtsi32_si128(64-bot);
lo = _mm_xor_si128(_mm_sll_epi64(hi,lshift),_mm_srl_epi64(lo,rshift));
#if __SSSE3__
return _mm_shuffle_epi8(lo,_mm_set_epi8(8,9,10,11,12,13,14,15,0,1,2,3,4,5,6,7));
#else
return swap_if_le(_mm_shuffle_epi32(lo, _MM_SHUFFLE(1,0,3,2)));
#endif
}
static inline block double_block(block bl) {
const __m128i mask = _mm_set_epi32(135,1,1,1);
__m128i tmp = _mm_srai_epi32(bl, 31);
tmp = _mm_and_si128(tmp, mask);
tmp = _mm_shuffle_epi32(tmp, _MM_SHUFFLE(2,1,0,3));
bl = _mm_slli_epi32(bl, 1);
return _mm_xor_si128(bl,tmp);
}
#elif __ALTIVEC__ && _CALL_ELF != 2
#include <altivec.h>
typedef vector unsigned block;
#define xor_block(x,y) vec_xor(x,y)
#define zero_block() vec_splat_u32(0)
#define unequal_blocks(x,y) vec_any_ne(x,y)
#define swap_if_le(b) (b)
#if __PPC64__
static block gen_offset(uint64_t KtopStr[3], unsigned bot) {
union {uint64_t u64[2]; block bl;} rval;
rval.u64[0] = (KtopStr[0] << bot) | (KtopStr[1] >> (64-bot));
rval.u64[1] = (KtopStr[1] << bot) | (KtopStr[2] >> (64-bot));
return rval.bl;
}
#else
/* Special handling: Shifts are mod 32, and no 64-bit types */
static block gen_offset(uint64_t KtopStr[3], unsigned bot) {
const vector unsigned k32 = {32,32,32,32};
vector unsigned hi = *(vector unsigned *)(KtopStr+0);
vector unsigned lo = *(vector unsigned *)(KtopStr+2);
vector unsigned bot_vec;
if (bot < 32) {
lo = vec_sld(hi,lo,4);
} else {
vector unsigned t = vec_sld(hi,lo,4);
lo = vec_sld(hi,lo,8);
hi = t;
bot = bot - 32;
}
if (bot == 0) return hi;
*(unsigned *)&bot_vec = bot;
vector unsigned lshift = vec_splat(bot_vec,0);
vector unsigned rshift = vec_sub(k32,lshift);
hi = vec_sl(hi,lshift);
lo = vec_sr(lo,rshift);
return vec_xor(hi,lo);
}
#endif
static inline block double_block(block b) {
const vector unsigned char mask = {135,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
const vector unsigned char perm = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0};
const vector unsigned char shift7 = vec_splat_u8(7);
const vector unsigned char shift1 = vec_splat_u8(1);
vector unsigned char c = (vector unsigned char)b;
vector unsigned char t = vec_sra(c,shift7);
t = vec_and(t,mask);
t = vec_perm(t,t,perm);
c = vec_sl(c,shift1);
return (block)vec_xor(c,t);
}
#elif __ARM_NEON__
#include <arm_neon.h>
typedef int8x16_t block; /* Yay! Endian-neutral reads! */
#define xor_block(x,y) veorq_s8(x,y)
#define zero_block() vdupq_n_s8(0)
static inline int unequal_blocks(block a, block b) {
int64x2_t t=veorq_s64((int64x2_t)a,(int64x2_t)b);
return (vgetq_lane_s64(t,0)|vgetq_lane_s64(t,1))!=0;
}
#define swap_if_le(b) (b) /* Using endian-neutral int8x16_t */
/* KtopStr is reg correct by 64 bits, return mem correct */
static block gen_offset(uint64_t KtopStr[3], unsigned bot) {
const union { unsigned x; unsigned char endian; } little = { 1 };
const int64x2_t k64 = {-64,-64};
uint64x2_t hi, lo;
memcpy(&hi, KtopStr, sizeof(hi));
memcpy(&lo, KtopStr+1, sizeof(lo));
int64x2_t ls = vdupq_n_s64(bot);
int64x2_t rs = vqaddq_s64(k64,ls);
block rval = (block)veorq_u64(vshlq_u64(hi,ls),vshlq_u64(lo,rs));
if (little.endian)
rval = vrev64q_s8(rval);
return rval;
}
static inline block double_block(block b)
{
const block mask = {-121,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
block tmp = vshrq_n_s8(b,7);
tmp = vandq_s8(tmp, mask);
tmp = vextq_s8(tmp, tmp, 1); /* Rotate high byte to end */
b = vshlq_n_s8(b,1);
return veorq_s8(tmp,b);
}
#else
typedef struct { uint64_t l,r; } block;
static inline block xor_block(block x, block y) {
x.l^=y.l; x.r^=y.r; return x;
}
static inline block zero_block(void) { const block t = {0,0}; return t; }
#define unequal_blocks(x, y) ((((x).l^(y).l)|((x).r^(y).r)) != 0)
static inline block swap_if_le(block b) {
const union { unsigned x; unsigned char endian; } little = { 1 };
if (little.endian) {
block r;
r.l = bswap64(b.l);
r.r = bswap64(b.r);
return r;
} else
return b;
}
/* KtopStr is reg correct by 64 bits, return mem correct */
static block gen_offset(uint64_t KtopStr[3], unsigned bot) {
block rval;
if (bot != 0) {
rval.l = (KtopStr[0] << bot) | (KtopStr[1] >> (64-bot));
rval.r = (KtopStr[1] << bot) | (KtopStr[2] >> (64-bot));
} else {
rval.l = KtopStr[0];
rval.r = KtopStr[1];
}
return swap_if_le(rval);
}
#if __GNUC__ && !__clang__ && __arm__
static inline block double_block(block b) {
__asm__ ("adds %1,%1,%1\n\t"
"adcs %H1,%H1,%H1\n\t"
"adcs %0,%0,%0\n\t"
"adcs %H0,%H0,%H0\n\t"
"it cs\n\t"
"eorcs %1,%1,#135"
: "+r"(b.l), "+r"(b.r) : : "cc");
return b;
}
#else
static inline block double_block(block b) {
uint64_t t = (uint64_t)((int64_t)b.l >> 63);
b.l = (b.l + b.l) ^ (b.r >> 63);
b.r = (b.r + b.r) ^ (t & 135);
return b;
}
#endif
#endif
/* ----------------------------------------------------------------------- */
/* AES */
/* ----------------------------------------------------------------------- */
/*---------------*/
#if USE_OPENSSL_AES
/*---------------*/
#include <openssl/evp.h> /* http://openssl.org/ */
namespace ocb_aes {
typedef EVP_CIPHER_CTX KEY;
enum { BLOCK_SIZE = 16 };
static KEY *KEY_new() {
KEY *key = EVP_CIPHER_CTX_new();
if (key == NULL) {
throw std::bad_alloc();
}
return key;
}
static void KEY_delete(KEY *key) { EVP_CIPHER_CTX_free(key); }
static void set_encrypt_key(const unsigned char *user_key, int bits, KEY *key) {
// Do not copy and paste this code! It is far too low-level to be
// general-purpose. If you're looking for an example of using AEAD
// through OpenSSL's EVP_CIPHER API, have a look at ocb_openssl.cc
// instead.
//
// This function and the others in this section replicate the behavior of
// OpenSSL's deprecated AES_* primitives. Those primitives implemented AES
// without any block cipher mode--that is, in ECB mode. Normally, using ECB
// mode anywhere would be questionable, but it's safe here because it's
// being used to implement a higher-level cryptographic mode (OCB mode),
// which is in turn used by Mosh.
fatal_assert(bits == 128);
if (EVP_EncryptInit_ex(key, EVP_aes_128_ecb(), /*impl=*/NULL, user_key, /*iv=*/NULL) != 1 ||
EVP_CIPHER_CTX_set_padding(key, false) != 1) {
throw Crypto::CryptoException("Could not initialize AES encryption context.");
}
}
static void set_decrypt_key(const unsigned char *user_key, int bits, KEY *key) {
// Do not copy and paste this code! See notes in set_encrypt_key.
fatal_assert(bits == 128);
if (EVP_DecryptInit_ex(key, EVP_aes_128_ecb(), /*impl=*/NULL, user_key, /*iv=*/NULL) != 1 ||
EVP_CIPHER_CTX_set_padding(key, false) != 1) {
throw Crypto::CryptoException("Could not initialize AES decryption context.");
}
}
static void encrypt(const unsigned char *in, unsigned char *out, KEY *key) {
// Even though the functions in this section use ECB mode (which is
// stateless), OpenSSL still requires calls to EncryptInit and
// EncryptFinal. Since ECB mode has no IV and they key is unchanged,
// every parameter to this function can be NULL (which OpenSSL
// interprets as "don't change this").
if (EVP_EncryptInit_ex(key, /*type=*/NULL, /*impl=*/NULL, /*key=*/NULL, /*iv=*/NULL) != 1) {
throw Crypto::CryptoException("Could not start AES encryption operation.");
}
int len;
if (EVP_EncryptUpdate(key, out, &len, in, BLOCK_SIZE) != 1) {
throw Crypto::CryptoException("Could not AES-encrypt block.");
}
int total_len = len;
if (EVP_EncryptFinal_ex(key, out + total_len, &len) != 1) {
throw Crypto::CryptoException("Could not finish AES encryption operation.");
}
total_len += len;
fatal_assert(total_len == BLOCK_SIZE);
}
static void decrypt(const unsigned char *in, unsigned char *out, KEY *key) {
// See notes in encrypt about EncryptInit and EncryptFinal; the same
// notes apply to DecryptInit and DecryptFinal here.
if (EVP_DecryptInit_ex(key, /*type=*/NULL, /*impl=*/NULL, /*key=*/NULL, /*iv=*/NULL) != 1) {
throw Crypto::CryptoException("Could not start AES decryption operation.");
}
int len;
if (EVP_DecryptUpdate(key, out, &len, in, BLOCK_SIZE) != 1) {
throw Crypto::CryptoException("Could not AES-decrypt block.");
}
int total_len = len;
if (EVP_DecryptFinal_ex(key, out + total_len, &len) != 1) {
throw Crypto::CryptoException("Could not finish AES decryption operation.");
}
total_len += len;
fatal_assert(total_len == BLOCK_SIZE);
}
/* How to ECB encrypt an array of blocks, in place */
static void ecb_encrypt_blks(block *blks, unsigned nblks, KEY *key) {
while (nblks) {
--nblks;
encrypt(reinterpret_cast<unsigned char *>(blks+nblks), reinterpret_cast<unsigned char *>(blks+nblks), key);
}
}
static void ecb_decrypt_blks(block *blks, unsigned nblks, KEY *key) {
while (nblks) {
--nblks;
decrypt(reinterpret_cast<unsigned char *>(blks+nblks), reinterpret_cast<unsigned char *>(blks+nblks), key);
}
}
} // namespace ocb_aes
#define BPI 4 /* Number of blocks in buffer per ECB call */
/*-------------------*/
#elif USE_APPLE_COMMON_CRYPTO_AES
/*-------------------*/
#include <CommonCrypto/CommonCryptor.h>
namespace ocb_aes {
typedef struct {
CCCryptorRef ref;
uint8_t b[4096];
} KEY;
static KEY *KEY_new() { return new KEY; }
static void KEY_delete(KEY *key) { delete key; }
static void set_encrypt_key(const unsigned char *handle, const int bits, KEY *key)
{
CCCryptorStatus rv = CCCryptorCreateFromData(
kCCEncrypt,
kCCAlgorithmAES128,
kCCOptionECBMode,
handle,
bits / 8,
NULL,
&(key->b),
sizeof (key->b),
&(key->ref),
NULL);
fatal_assert(rv == kCCSuccess);
}
static void set_decrypt_key(const unsigned char *handle, const int bits, KEY *key)
{
CCCryptorStatus rv = CCCryptorCreateFromData(
kCCDecrypt,
kCCAlgorithmAES128,
kCCOptionECBMode,
handle,
bits / 8,
NULL,
&(key->b),
sizeof (key->b),
&(key->ref),
NULL);
fatal_assert(rv == kCCSuccess);
}
static void encrypt(unsigned char *src, unsigned char *dst, KEY *key) {
size_t dataOutMoved;
CCCryptorStatus rv = CCCryptorUpdate(
key->ref,
(const void *)src,
kCCBlockSizeAES128,
(void *)dst,
kCCBlockSizeAES128,
&dataOutMoved);
fatal_assert(rv == kCCSuccess);
fatal_assert(dataOutMoved == kCCBlockSizeAES128);
}
#if 0
/* unused */
static void decrypt(unsigned char *src, unsigned char *dst, KEY *key) {
encrypt(src, dst, key);
}
#endif
static void ecb_encrypt_blks(block *blks, unsigned nblks, KEY *key) {
const size_t dataSize = kCCBlockSizeAES128 * nblks;
size_t dataOutMoved;
CCCryptorStatus rv = CCCryptorUpdate(
key->ref,
(const void *)blks,
dataSize,
(void *)blks,
dataSize,
&dataOutMoved);
fatal_assert(rv == kCCSuccess);
fatal_assert(dataOutMoved == dataSize);
}
static void ecb_decrypt_blks(block *blks, unsigned nblks, KEY *key) {
ecb_encrypt_blks(blks, nblks, key);
}
} // namespace ocb_aes
#define BPI 4 /* Number of blocks in buffer per ECB call */
/*-------------------*/
#elif USE_NETTLE_AES
/*-------------------*/
#include <nettle/aes.h>
namespace ocb_aes {
typedef struct aes128_ctx KEY;
static KEY *KEY_new() { return new KEY; }
static void KEY_delete(KEY *key) { delete key; }
static void set_encrypt_key(const unsigned char *handle, const int bits, KEY *key)
{
fatal_assert(bits == 128);
nettle_aes128_set_encrypt_key(key, (const uint8_t *)handle);
}
static void set_decrypt_key(const unsigned char *handle, const int bits, KEY *key)
{
fatal_assert(bits == 128);
nettle_aes128_set_decrypt_key(key, (const uint8_t *)handle);
}
static void encrypt(unsigned char *src, unsigned char *dst, KEY *key) {
nettle_aes128_encrypt(key, AES_BLOCK_SIZE, dst, src);
}
#if 0
/* unused */
static void decrypt(unsigned char *src, unsigned char *dst, KEY *key) {
nettle_aes128_decrypt(key, AES_BLOCK_SIZE, dst, src);
}
#endif
static void ecb_encrypt_blks(block *blks, unsigned nblks, KEY *key) {
nettle_aes128_encrypt(key, nblks * AES_BLOCK_SIZE, (unsigned char*)blks, (unsigned char*)blks);
}
static void ecb_decrypt_blks(block *blks, unsigned nblks, KEY *key) {
nettle_aes128_decrypt(key, nblks * AES_BLOCK_SIZE, (unsigned char*)blks, (unsigned char*)blks);
}
} // namespace ocb_aes
#define BPI 4 /* Number of blocks in buffer per ECB call */
#else
#error "No AES implementation selected."
#endif
/* ----------------------------------------------------------------------- */
/* Define OCB context structure. */
/* ----------------------------------------------------------------------- */
/*------------------------------------------------------------------------
/ Each item in the OCB context is stored either "memory correct" or
/ "register correct". On big-endian machines, this is identical. On
/ little-endian machines, one must choose whether the byte-string
/ is in the correct order when it resides in memory or in registers.
/ It must be register correct whenever it is to be manipulated
/ arithmetically, but must be memory correct whenever it interacts
/ with the plaintext or ciphertext.
/------------------------------------------------------------------------- */
struct _ae_ctx {
block offset; /* Memory correct */
block checksum; /* Memory correct */
block Lstar; /* Memory correct */
block Ldollar; /* Memory correct */
block L[L_TABLE_SZ]; /* Memory correct */
block ad_checksum; /* Memory correct */
block ad_offset; /* Memory correct */
block cached_Top; /* Memory correct */
uint64_t KtopStr[3]; /* Register correct, each item */
uint32_t ad_blocks_processed;
uint32_t blocks_processed;
ocb_aes::KEY *decrypt_key;
ocb_aes::KEY *encrypt_key;
#if (OCB_TAG_LEN == 0)
unsigned tag_len;
#endif
};
/* ----------------------------------------------------------------------- */
/* L table lookup (or on-the-fly generation) */
/* ----------------------------------------------------------------------- */
#if L_TABLE_SZ_IS_ENOUGH
#define getL(_ctx, _tz) ((_ctx)->L[_tz])
#else
static block getL(const ae_ctx *ctx, unsigned tz)
{
if (tz < L_TABLE_SZ)
return ctx->L[tz];
else {
unsigned i;
/* Bring L[MAX] into registers, make it register correct */
block rval = swap_if_le(ctx->L[L_TABLE_SZ-1]);
rval = double_block(rval);
for (i=L_TABLE_SZ; i < tz; i++)
rval = double_block(rval);
return swap_if_le(rval); /* To memory correct */
}
}
#endif
/* ----------------------------------------------------------------------- */
/* Public functions */
/* ----------------------------------------------------------------------- */
/* 32-bit SSE2 and Altivec systems need to be forced to allocate memory
on 16-byte alignments. (I believe all major 64-bit systems do already.) */
/* Mosh uses its own AlignedBuffer class, not ae_allocate() or ae_free(). */
/* ----------------------------------------------------------------------- */
int ae_clear (ae_ctx *ctx) /* Zero ae_ctx and undo initialization */
{
ocb_aes::KEY_delete(ctx->encrypt_key);
ocb_aes::KEY_delete(ctx->decrypt_key);
memset(ctx, 0, sizeof(ae_ctx));
return AE_SUCCESS;
}
int ae_ctx_sizeof(void) { return (int) sizeof(ae_ctx); }
/* ----------------------------------------------------------------------- */
int ae_init(ae_ctx *ctx, const void *key, int key_len, int nonce_len, int tag_len)
{
unsigned i;
block tmp_blk;
if (nonce_len != 12)
return AE_NOT_SUPPORTED;
ctx->decrypt_key = ocb_aes::KEY_new();
ctx->encrypt_key = ocb_aes::KEY_new();
/* Initialize encryption & decryption keys */
#if (OCB_KEY_LEN > 0)
key_len = OCB_KEY_LEN;
#endif
ocb_aes::set_encrypt_key(reinterpret_cast<const unsigned char *>(key), key_len*8, ctx->encrypt_key);
ocb_aes::set_decrypt_key(reinterpret_cast<const unsigned char *>(key), static_cast<int>(key_len*8), ctx->decrypt_key);
/* Zero things that need zeroing */
ctx->cached_Top = ctx->ad_checksum = zero_block();
ctx->ad_blocks_processed = 0;
/* Compute key-dependent values */
ocb_aes::encrypt(reinterpret_cast<unsigned char *>(&ctx->cached_Top),
reinterpret_cast<unsigned char *>(&ctx->Lstar), ctx->encrypt_key);
tmp_blk = swap_if_le(ctx->Lstar);
tmp_blk = double_block(tmp_blk);
ctx->Ldollar = swap_if_le(tmp_blk);
tmp_blk = double_block(tmp_blk);
ctx->L[0] = swap_if_le(tmp_blk);
for (i = 1; i < L_TABLE_SZ; i++) {
tmp_blk = double_block(tmp_blk);
ctx->L[i] = swap_if_le(tmp_blk);
}
#if (OCB_TAG_LEN == 0)
ctx->tag_len = tag_len;
#else
(void) tag_len; /* Suppress var not used error */
#endif
return AE_SUCCESS;
}
/* ----------------------------------------------------------------------- */
static block gen_offset_from_nonce(ae_ctx *ctx, const void *nonce)
{
const union { unsigned x; unsigned char endian; } little = { 1 };
union { uint32_t u32[4]; uint8_t u8[16]; block bl; } tmp;
unsigned idx;
/* Replace cached nonce Top if needed */
tmp.u32[0] = (little.endian?0x01000000:0x00000001);
tmp.u32[1] = ((uint32_t *)nonce)[0];
tmp.u32[2] = ((uint32_t *)nonce)[1];
tmp.u32[3] = ((uint32_t *)nonce)[2];
idx = (unsigned)(tmp.u8[15] & 0x3f); /* Get low 6 bits of nonce */
tmp.u8[15] = tmp.u8[15] & 0xc0; /* Zero low 6 bits of nonce */
if ( unequal_blocks(tmp.bl,ctx->cached_Top) ) { /* Cached? */
ctx->cached_Top = tmp.bl; /* Update cache, KtopStr */
ocb_aes::encrypt(tmp.u8, (unsigned char *)&ctx->KtopStr, ctx->encrypt_key);
if (little.endian) { /* Make Register Correct */
ctx->KtopStr[0] = bswap64(ctx->KtopStr[0]);
ctx->KtopStr[1] = bswap64(ctx->KtopStr[1]);
}
ctx->KtopStr[2] = ctx->KtopStr[0] ^
(ctx->KtopStr[0] << 8) ^ (ctx->KtopStr[1] >> 56);
}
return gen_offset(ctx->KtopStr, idx);
}
static void process_ad(ae_ctx *ctx, const void *ad, int ad_len, int final)
{
union { uint32_t u32[4]; uint8_t u8[16]; block bl; } tmp;
block ad_offset, ad_checksum;
const block * adp = (block *)ad;
unsigned i,k,tz,remaining;
ad_offset = ctx->ad_offset;
ad_checksum = ctx->ad_checksum;
i = ad_len/(BPI*16);
if (i) {
unsigned ad_block_num = ctx->ad_blocks_processed;
do {
block ta[BPI], oa[BPI];
ad_block_num += BPI;
tz = ntz(ad_block_num);
oa[0] = xor_block(ad_offset, ctx->L[0]);
ta[0] = xor_block(oa[0], adp[0]);
oa[1] = xor_block(oa[0], ctx->L[1]);
ta[1] = xor_block(oa[1], adp[1]);
oa[2] = xor_block(ad_offset, ctx->L[1]);
ta[2] = xor_block(oa[2], adp[2]);
#if BPI == 4
ad_offset = xor_block(oa[2], getL(ctx, tz));
ta[3] = xor_block(ad_offset, adp[3]);
#elif BPI == 8
oa[3] = xor_block(oa[2], ctx->L[2]);
ta[3] = xor_block(oa[3], adp[3]);
oa[4] = xor_block(oa[1], ctx->L[2]);
ta[4] = xor_block(oa[4], adp[4]);
oa[5] = xor_block(oa[0], ctx->L[2]);
ta[5] = xor_block(oa[5], adp[5]);
oa[6] = xor_block(ad_offset, ctx->L[2]);
ta[6] = xor_block(oa[6], adp[6]);
ad_offset = xor_block(oa[6], getL(ctx, tz));
ta[7] = xor_block(ad_offset, adp[7]);
#endif
ocb_aes::ecb_encrypt_blks(ta, BPI, ctx->encrypt_key);
ad_checksum = xor_block(ad_checksum, ta[0]);
ad_checksum = xor_block(ad_checksum, ta[1]);
ad_checksum = xor_block(ad_checksum, ta[2]);
ad_checksum = xor_block(ad_checksum, ta[3]);
#if (BPI == 8)
ad_checksum = xor_block(ad_checksum, ta[4]);
ad_checksum = xor_block(ad_checksum, ta[5]);
ad_checksum = xor_block(ad_checksum, ta[6]);
ad_checksum = xor_block(ad_checksum, ta[7]);
#endif
adp += BPI;
} while (--i);
ctx->ad_blocks_processed = ad_block_num;
ctx->ad_offset = ad_offset;
ctx->ad_checksum = ad_checksum;
}
if (final) {
block ta[BPI];
/* Process remaining associated data, compute its tag contribution */
remaining = ((unsigned)ad_len) % (BPI*16);
if (remaining) {
k=0;
#if (BPI == 8)
if (remaining >= 64) {
tmp.bl = xor_block(ad_offset, ctx->L[0]);
ta[0] = xor_block(tmp.bl, adp[0]);
tmp.bl = xor_block(tmp.bl, ctx->L[1]);
ta[1] = xor_block(tmp.bl, adp[1]);
ad_offset = xor_block(ad_offset, ctx->L[1]);
ta[2] = xor_block(ad_offset, adp[2]);
ad_offset = xor_block(ad_offset, ctx->L[2]);
ta[3] = xor_block(ad_offset, adp[3]);
remaining -= 64;
k=4;
}
#endif
if (remaining >= 32) {
ad_offset = xor_block(ad_offset, ctx->L[0]);
ta[k] = xor_block(ad_offset, adp[k]);
ad_offset = xor_block(ad_offset, getL(ctx, ntz(k+2)));
ta[k+1] = xor_block(ad_offset, adp[k+1]);
remaining -= 32;
k+=2;
}
if (remaining >= 16) {
ad_offset = xor_block(ad_offset, ctx->L[0]);
ta[k] = xor_block(ad_offset, adp[k]);
remaining = remaining - 16;
++k;
}
if (remaining) {
ad_offset = xor_block(ad_offset,ctx->Lstar);
tmp.bl = zero_block();
memcpy(tmp.u8, adp+k, remaining);
tmp.u8[remaining] = (unsigned char)0x80u;
ta[k] = xor_block(ad_offset, tmp.bl);
++k;
}
ocb_aes::ecb_encrypt_blks(ta, k, ctx->encrypt_key);
switch (k) {
#if (BPI == 8)
case 8: ad_checksum = xor_block(ad_checksum, ta[7]);
/* fallthrough */
case 7: ad_checksum = xor_block(ad_checksum, ta[6]);
/* fallthrough */
case 6: ad_checksum = xor_block(ad_checksum, ta[5]);
/* fallthrough */
case 5: ad_checksum = xor_block(ad_checksum, ta[4]);
/* fallthrough */
#endif
case 4: ad_checksum = xor_block(ad_checksum, ta[3]);
/* fallthrough */
case 3: ad_checksum = xor_block(ad_checksum, ta[2]);
/* fallthrough */
case 2: ad_checksum = xor_block(ad_checksum, ta[1]);
/* fallthrough */
case 1: ad_checksum = xor_block(ad_checksum, ta[0]);
}
ctx->ad_checksum = ad_checksum;
}
}
}
/* ----------------------------------------------------------------------- */
int ae_encrypt(ae_ctx * ctx,
const void * nonce,
const void *pt,
int pt_len,
const void *ad,
int ad_len,
void *ct,
void *tag,
int final)
{
union { uint32_t u32[4]; uint8_t u8[16]; block bl; } tmp;
block offset, checksum;
unsigned i, k;
block * ctp = (block *)ct;
const block * ptp = (block *)pt;
/* Non-null nonce means start of new message, init per-message values */
if (nonce) {
ctx->offset = gen_offset_from_nonce(ctx, nonce);
ctx->ad_offset = ctx->checksum = zero_block();
ctx->ad_blocks_processed = ctx->blocks_processed = 0;
if (ad_len >= 0)
ctx->ad_checksum = zero_block();
}
/* Process associated data */
if (ad_len > 0)
process_ad(ctx, ad, ad_len, final);
/* Encrypt plaintext data BPI blocks at a time */
offset = ctx->offset;
checksum = ctx->checksum;
i = pt_len/(BPI*16);
if (i) {
block oa[BPI];
unsigned block_num = ctx->blocks_processed;
oa[BPI-1] = offset;
do {
block ta[BPI];
block_num += BPI;
oa[0] = xor_block(oa[BPI-1], ctx->L[0]);
ta[0] = xor_block(oa[0], ptp[0]);
checksum = xor_block(checksum, ptp[0]);
oa[1] = xor_block(oa[0], ctx->L[1]);
ta[1] = xor_block(oa[1], ptp[1]);
checksum = xor_block(checksum, ptp[1]);
oa[2] = xor_block(oa[1], ctx->L[0]);
ta[2] = xor_block(oa[2], ptp[2]);
checksum = xor_block(checksum, ptp[2]);
#if BPI == 4
oa[3] = xor_block(oa[2], getL(ctx, ntz(block_num)));
ta[3] = xor_block(oa[3], ptp[3]);
checksum = xor_block(checksum, ptp[3]);
#elif BPI == 8
oa[3] = xor_block(oa[2], ctx->L[2]);
ta[3] = xor_block(oa[3], ptp[3]);
checksum = xor_block(checksum, ptp[3]);
oa[4] = xor_block(oa[1], ctx->L[2]);
ta[4] = xor_block(oa[4], ptp[4]);
checksum = xor_block(checksum, ptp[4]);
oa[5] = xor_block(oa[0], ctx->L[2]);
ta[5] = xor_block(oa[5], ptp[5]);
checksum = xor_block(checksum, ptp[5]);
oa[6] = xor_block(oa[7], ctx->L[2]);
ta[6] = xor_block(oa[6], ptp[6]);
checksum = xor_block(checksum, ptp[6]);
oa[7] = xor_block(oa[6], getL(ctx, ntz(block_num)));
ta[7] = xor_block(oa[7], ptp[7]);
checksum = xor_block(checksum, ptp[7]);
#endif
ocb_aes::ecb_encrypt_blks(ta, BPI, ctx->encrypt_key);
ctp[0] = xor_block(ta[0], oa[0]);
ctp[1] = xor_block(ta[1], oa[1]);
ctp[2] = xor_block(ta[2], oa[2]);
ctp[3] = xor_block(ta[3], oa[3]);
#if (BPI == 8)
ctp[4] = xor_block(ta[4], oa[4]);
ctp[5] = xor_block(ta[5], oa[5]);
ctp[6] = xor_block(ta[6], oa[6]);
ctp[7] = xor_block(ta[7], oa[7]);
#endif
ptp += BPI;
ctp += BPI;
} while (--i);
ctx->offset = offset = oa[BPI-1];
ctx->blocks_processed = block_num;
ctx->checksum = checksum;
}
if (final) {
block ta[BPI+1], oa[BPI];
/* Process remaining plaintext and compute its tag contribution */
unsigned remaining = ((unsigned)pt_len) % (BPI*16);
k = 0; /* How many blocks in ta[] need ECBing */
if (remaining) {
#if (BPI == 8)
if (remaining >= 64) {
oa[0] = xor_block(offset, ctx->L[0]);
ta[0] = xor_block(oa[0], ptp[0]);
checksum = xor_block(checksum, ptp[0]);
oa[1] = xor_block(oa[0], ctx->L[1]);
ta[1] = xor_block(oa[1], ptp[1]);
checksum = xor_block(checksum, ptp[1]);
oa[2] = xor_block(oa[1], ctx->L[0]);
ta[2] = xor_block(oa[2], ptp[2]);
checksum = xor_block(checksum, ptp[2]);
offset = oa[3] = xor_block(oa[2], ctx->L[2]);
ta[3] = xor_block(offset, ptp[3]);
checksum = xor_block(checksum, ptp[3]);
remaining -= 64;
k = 4;
}
#endif
if (remaining >= 32) {
oa[k] = xor_block(offset, ctx->L[0]);
ta[k] = xor_block(oa[k], ptp[k]);
checksum = xor_block(checksum, ptp[k]);
offset = oa[k+1] = xor_block(oa[k], ctx->L[1]);
ta[k+1] = xor_block(offset, ptp[k+1]);
checksum = xor_block(checksum, ptp[k+1]);
remaining -= 32;
k+=2;
}
if (remaining >= 16) {
offset = oa[k] = xor_block(offset, ctx->L[0]);
ta[k] = xor_block(offset, ptp[k]);
checksum = xor_block(checksum, ptp[k]);
remaining -= 16;
++k;
}
if (remaining) {
tmp.bl = zero_block();
memcpy(tmp.u8, ptp+k, remaining);
tmp.u8[remaining] = (unsigned char)0x80u;
checksum = xor_block(checksum, tmp.bl);
ta[k] = offset = xor_block(offset,ctx->Lstar);
++k;
}
}
offset = xor_block(offset, ctx->Ldollar); /* Part of tag gen */
ta[k] = xor_block(offset, checksum); /* Part of tag gen */
ocb_aes::ecb_encrypt_blks(ta, k + 1, ctx->encrypt_key);
offset = xor_block(ta[k], ctx->ad_checksum); /* Part of tag gen */
if (remaining) {
--k;
tmp.bl = xor_block(tmp.bl, ta[k]);
memcpy(ctp+k, tmp.u8, remaining);
}
switch (k) {
#if (BPI == 8)
case 7: ctp[6] = xor_block(ta[6], oa[6]);
/* fallthrough */
case 6: ctp[5] = xor_block(ta[5], oa[5]);
/* fallthrough */
case 5: ctp[4] = xor_block(ta[4], oa[4]);
/* fallthrough */
case 4: ctp[3] = xor_block(ta[3], oa[3]);
/* fallthrough */
#endif
case 3: ctp[2] = xor_block(ta[2], oa[2]);
/* fallthrough */
case 2: ctp[1] = xor_block(ta[1], oa[1]);
/* fallthrough */
case 1: ctp[0] = xor_block(ta[0], oa[0]);
}
/* Tag is placed at the correct location
*/
if (tag) {
#if (OCB_TAG_LEN == 16)
*(block *)tag = offset;
#elif (OCB_TAG_LEN > 0)
memcpy((char *)tag, &offset, OCB_TAG_LEN);
#else
memcpy((char *)tag, &offset, ctx->tag_len);
#endif
} else {
#if (OCB_TAG_LEN > 0)
memcpy((char *)ct + pt_len, &offset, OCB_TAG_LEN);
pt_len += OCB_TAG_LEN;
#else
memcpy((char *)ct + pt_len, &offset, ctx->tag_len);
pt_len += ctx->tag_len;
#endif
}
}
return (int) pt_len;
}
/* ----------------------------------------------------------------------- */
/* Compare two regions of memory, taking a constant amount of time for a
given buffer size -- under certain assumptions about the compiler
and machine, of course.
Use this to avoid timing side-channel attacks.
Returns 0 for memory regions with equal contents; non-zero otherwise. */
static int constant_time_memcmp(const void *av, const void *bv, size_t n) {
const uint8_t *a = (const uint8_t *) av;
const uint8_t *b = (const uint8_t *) bv;
uint8_t result = 0;
size_t i;
for (i=0; i<n; i++) {
result |= *a ^ *b;
a++;
b++;
}
return (int) result;
}
int ae_decrypt(ae_ctx *ctx,
const void *nonce,
const void *ct,
int ct_len,
const void *ad,
int ad_len,
void *pt,
const void *tag,
int final)
{
union { uint32_t u32[4]; uint8_t u8[16]; block bl; } tmp;
block offset, checksum;
unsigned i, k;
block *ctp = (block *)ct;
block *ptp = (block *)pt;
/* Reduce ct_len tag bundled in ct */
if ((final) && (!tag))
#if (OCB_TAG_LEN > 0)
ct_len -= OCB_TAG_LEN;
#else
ct_len -= ctx->tag_len;
#endif
/* Non-null nonce means start of new message, init per-message values */
if (nonce) {
ctx->offset = gen_offset_from_nonce(ctx, nonce);
ctx->ad_offset = ctx->checksum = zero_block();
ctx->ad_blocks_processed = ctx->blocks_processed = 0;
if (ad_len >= 0)
ctx->ad_checksum = zero_block();
}
/* Process associated data */
if (ad_len > 0)
process_ad(ctx, ad, ad_len, final);
/* Encrypt plaintext data BPI blocks at a time */
offset = ctx->offset;
checksum = ctx->checksum;
i = ct_len/(BPI*16);
if (i) {
block oa[BPI];
unsigned block_num = ctx->blocks_processed;
oa[BPI-1] = offset;
do {
block ta[BPI];
block_num += BPI;
oa[0] = xor_block(oa[BPI-1], ctx->L[0]);
ta[0] = xor_block(oa[0], ctp[0]);
oa[1] = xor_block(oa[0], ctx->L[1]);
ta[1] = xor_block(oa[1], ctp[1]);
oa[2] = xor_block(oa[1], ctx->L[0]);
ta[2] = xor_block(oa[2], ctp[2]);
#if BPI == 4
oa[3] = xor_block(oa[2], getL(ctx, ntz(block_num)));
ta[3] = xor_block(oa[3], ctp[3]);
#elif BPI == 8
oa[3] = xor_block(oa[2], ctx->L[2]);
ta[3] = xor_block(oa[3], ctp[3]);
oa[4] = xor_block(oa[1], ctx->L[2]);
ta[4] = xor_block(oa[4], ctp[4]);
oa[5] = xor_block(oa[0], ctx->L[2]);
ta[5] = xor_block(oa[5], ctp[5]);
oa[6] = xor_block(oa[7], ctx->L[2]);
ta[6] = xor_block(oa[6], ctp[6]);
oa[7] = xor_block(oa[6], getL(ctx, ntz(block_num)));
ta[7] = xor_block(oa[7], ctp[7]);
#endif
ocb_aes::ecb_decrypt_blks(ta,BPI,ctx->decrypt_key);
ptp[0] = xor_block(ta[0], oa[0]);
checksum = xor_block(checksum, ptp[0]);
ptp[1] = xor_block(ta[1], oa[1]);
checksum = xor_block(checksum, ptp[1]);
ptp[2] = xor_block(ta[2], oa[2]);
checksum = xor_block(checksum, ptp[2]);
ptp[3] = xor_block(ta[3], oa[3]);
checksum = xor_block(checksum, ptp[3]);
#if (BPI == 8)
ptp[4] = xor_block(ta[4], oa[4]);
checksum = xor_block(checksum, ptp[4]);
ptp[5] = xor_block(ta[5], oa[5]);
checksum = xor_block(checksum, ptp[5]);
ptp[6] = xor_block(ta[6], oa[6]);
checksum = xor_block(checksum, ptp[6]);
ptp[7] = xor_block(ta[7], oa[7]);
checksum = xor_block(checksum, ptp[7]);
#endif
ptp += BPI;
ctp += BPI;
} while (--i);
ctx->offset = offset = oa[BPI-1];
ctx->blocks_processed = block_num;
ctx->checksum = checksum;
}
if (final) {
block ta[BPI+1], oa[BPI];
/* Process remaining plaintext and compute its tag contribution */
unsigned remaining = ((unsigned)ct_len) % (BPI*16);
k = 0; /* How many blocks in ta[] need ECBing */
if (remaining) {
#if (BPI == 8)
if (remaining >= 64) {
oa[0] = xor_block(offset, ctx->L[0]);
ta[0] = xor_block(oa[0], ctp[0]);
oa[1] = xor_block(oa[0], ctx->L[1]);
ta[1] = xor_block(oa[1], ctp[1]);
oa[2] = xor_block(oa[1], ctx->L[0]);
ta[2] = xor_block(oa[2], ctp[2]);
offset = oa[3] = xor_block(oa[2], ctx->L[2]);
ta[3] = xor_block(offset, ctp[3]);
remaining -= 64;
k = 4;
}
#endif
if (remaining >= 32) {
oa[k] = xor_block(offset, ctx->L[0]);
ta[k] = xor_block(oa[k], ctp[k]);
offset = oa[k+1] = xor_block(oa[k], ctx->L[1]);
ta[k+1] = xor_block(offset, ctp[k+1]);
remaining -= 32;
k+=2;
}
if (remaining >= 16) {
offset = oa[k] = xor_block(offset, ctx->L[0]);
ta[k] = xor_block(offset, ctp[k]);
remaining -= 16;
++k;
}
if (remaining) {
block pad;
offset = xor_block(offset,ctx->Lstar);
ocb_aes::encrypt(reinterpret_cast<unsigned char *>(&offset), tmp.u8, ctx->encrypt_key);
pad = tmp.bl;
memcpy(tmp.u8,ctp+k,remaining);
tmp.bl = xor_block(tmp.bl, pad);
tmp.u8[remaining] = (unsigned char)0x80u;
memcpy(ptp+k, tmp.u8, remaining);
checksum = xor_block(checksum, tmp.bl);
}
}
ocb_aes::ecb_decrypt_blks(ta,k,ctx->decrypt_key);
switch (k) {
#if (BPI == 8)
case 7: ptp[6] = xor_block(ta[6], oa[6]);
checksum = xor_block(checksum, ptp[6]);
/* fallthrough */
case 6: ptp[5] = xor_block(ta[5], oa[5]);
checksum = xor_block(checksum, ptp[5]);
/* fallthrough */
case 5: ptp[4] = xor_block(ta[4], oa[4]);
checksum = xor_block(checksum, ptp[4]);
/* fallthrough */
case 4: ptp[3] = xor_block(ta[3], oa[3]);
checksum = xor_block(checksum, ptp[3]);
/* fallthrough */
#endif
case 3: ptp[2] = xor_block(ta[2], oa[2]);
checksum = xor_block(checksum, ptp[2]);
/* fallthrough */
case 2: ptp[1] = xor_block(ta[1], oa[1]);
checksum = xor_block(checksum, ptp[1]);
/* fallthrough */
case 1: ptp[0] = xor_block(ta[0], oa[0]);
checksum = xor_block(checksum, ptp[0]);
}
/* Calculate expected tag */
offset = xor_block(offset, ctx->Ldollar);
tmp.bl = xor_block(offset, checksum);
ocb_aes::encrypt(tmp.u8, tmp.u8, ctx->encrypt_key);
tmp.bl = xor_block(tmp.bl, ctx->ad_checksum); /* Full tag */
/* Compare with proposed tag, change ct_len if invalid */
if ((OCB_TAG_LEN == 16) && tag) {
if (unequal_blocks(tmp.bl, *(block *)tag))
ct_len = AE_INVALID;
} else {
#if (OCB_TAG_LEN > 0)
int len = OCB_TAG_LEN;
#else
int len = ctx->tag_len;
#endif
if (tag) {
if (constant_time_memcmp(tag,tmp.u8,len) != 0)
ct_len = AE_INVALID;
} else {
if (constant_time_memcmp((char *)ct + ct_len,tmp.u8,len) != 0)
ct_len = AE_INVALID;
}
}
}
return ct_len;
}
/* ----------------------------------------------------------------------- */
/* Simple test program */
/* ----------------------------------------------------------------------- */
#if defined(OCB_TEST_PROGRAM)
#include <stdio.h>
#include <time.h>
#if __GNUC__
#define ALIGN(n) __attribute__ ((aligned(n)))
#elif _MSC_VER
#define ALIGN(n) __declspec(align(n))
#else /* Not GNU/Microsoft: delete alignment uses. */
#define ALIGN(n)
#endif
static void pbuf(void *p, unsigned len, const void *s)
{
unsigned i;
if (s)
printf("%s", (char *)s);
for (i = 0; i < len; i++)
printf("%02X", (unsigned)(((unsigned char *)p)[i]));
printf("\n");
}
static void vectors(ae_ctx *ctx, int len)
{
ALIGN(16) uint8_t pt[128];
ALIGN(16) uint8_t ct[144];
ALIGN(16) uint8_t nonce[] = {0,1,2,3,4,5,6,7,8,9,10,11};
int i;
for (i=0; i < 128; i++) pt[i] = i;
i = ae_encrypt(ctx,nonce,pt,len,pt,len,ct,NULL,AE_FINALIZE);
printf("P=%d,A=%d: ",len,len); pbuf(ct, i, NULL);
i = ae_encrypt(ctx,nonce,pt,0,pt,len,ct,NULL,AE_FINALIZE);
printf("P=%d,A=%d: ",0,len); pbuf(ct, i, NULL);
i = ae_encrypt(ctx,nonce,pt,len,pt,0,ct,NULL,AE_FINALIZE);
printf("P=%d,A=%d: ",len,0); pbuf(ct, i, NULL);
}
static void validate()
{
ALIGN(16) uint8_t pt[1024];
ALIGN(16) uint8_t ct[1024];
ALIGN(16) uint8_t tag[16];
ALIGN(16) uint8_t nonce[12] = {0,};
ALIGN(16) uint8_t key[32] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
ALIGN(16) uint8_t valid[] = {0xB2,0xB4,0x1C,0xBF,0x9B,0x05,0x03,0x7D,
0xA7,0xF1,0x6C,0x24,0xA3,0x5C,0x1C,0x94};
ae_ctx ctx;
uint8_t *val_buf, *next;
int i, len;
val_buf = (uint8_t *)malloc(22400 + 16);
next = val_buf = (uint8_t *)(((size_t)val_buf + 16) & ~((size_t)15));
if (0) {
ae_init(&ctx, key, 16, 12, 16);
/* pbuf(&ctx, sizeof(ctx), "CTX: "); */
vectors(&ctx,0);
vectors(&ctx,8);
vectors(&ctx,16);
vectors(&ctx,24);
vectors(&ctx,32);
vectors(&ctx,40);
}
memset(key,0,32);
memset(pt,0,128);
ae_init(&ctx, key, 16, 12, 16);
/* RFC Vector test */
for (i = 0; i < 128; i++) {
int first = ((i/3)/(BPI*16))*(BPI*16);
int second = first;
int third = i - (first + second);
nonce[11] = i;
if (0) {
ae_encrypt(&ctx,nonce,pt,i,pt,i,ct,NULL,AE_FINALIZE);
memcpy(next,ct,(size_t)i+16);
next = next+i+16;
ae_encrypt(&ctx,nonce,pt,i,pt,0,ct,NULL,AE_FINALIZE);
memcpy(next,ct,(size_t)i+16);
next = next+i+16;
ae_encrypt(&ctx,nonce,pt,0,pt,i,ct,NULL,AE_FINALIZE);
memcpy(next,ct,16);
next = next+16;
} else {
ae_encrypt(&ctx,nonce,pt,first,pt,first,ct,NULL,AE_PENDING);
ae_encrypt(&ctx,NULL,pt+first,second,pt+first,second,ct+first,NULL,AE_PENDING);
ae_encrypt(&ctx,NULL,pt+first+second,third,pt+first+second,third,ct+first+second,NULL,AE_FINALIZE);
memcpy(next,ct,(size_t)i+16);
next = next+i+16;
ae_encrypt(&ctx,nonce,pt,first,pt,0,ct,NULL,AE_PENDING);
ae_encrypt(&ctx,NULL,pt+first,second,pt,0,ct+first,NULL,AE_PENDING);
ae_encrypt(&ctx,NULL,pt+first+second,third,pt,0,ct+first+second,NULL,AE_FINALIZE);
memcpy(next,ct,(size_t)i+16);
next = next+i+16;
ae_encrypt(&ctx,nonce,pt,0,pt,first,ct,NULL,AE_PENDING);
ae_encrypt(&ctx,NULL,pt,0,pt+first,second,ct,NULL,AE_PENDING);
ae_encrypt(&ctx,NULL,pt,0,pt+first+second,third,ct,NULL,AE_FINALIZE);
memcpy(next,ct,16);
next = next+16;
}
}
nonce[11] = 0;
ae_encrypt(&ctx,nonce,NULL,0,val_buf,next-val_buf,ct,tag,AE_FINALIZE);
pbuf(tag,16,0);
if (memcmp(valid,tag,16) == 0)
printf("Vectors: PASS\n");
else
printf("Vectors: FAIL\n");
/* Encrypt/Decrypt test */
for (i = 0; i < 128; i++) {
int first = ((i/3)/(BPI*16))*(BPI*16);
int second = first;
int third = i - (first + second);
nonce[11] = i%128;
if (1) {
len = ae_encrypt(&ctx,nonce,val_buf,i,val_buf,i,ct,tag,AE_FINALIZE);
len = ae_encrypt(&ctx,nonce,val_buf,i,val_buf,-1,ct,tag,AE_FINALIZE);
len = ae_decrypt(&ctx,nonce,ct,len,val_buf,-1,pt,tag,AE_FINALIZE);
if (len == -1) { printf("Authentication error: %d\n", i); return; }
if (len != i) { printf("Length error: %d\n", i); return; }
if (memcmp(val_buf,pt,i)) { printf("Decrypt error: %d\n", i); return; }
} else {
len = ae_encrypt(&ctx,nonce,val_buf,i,val_buf,i,ct,NULL,AE_FINALIZE);
ae_decrypt(&ctx,nonce,ct,first,val_buf,first,pt,NULL,AE_PENDING);
ae_decrypt(&ctx,NULL,ct+first,second,val_buf+first,second,pt+first,NULL,AE_PENDING);
len = ae_decrypt(&ctx,NULL,ct+first+second,len-(first+second),val_buf+first+second,third,pt+first+second,NULL,AE_FINALIZE);
if (len == -1) { printf("Authentication error: %d\n", i); return; }
if (memcmp(val_buf,pt,i)) { printf("Decrypt error: %d\n", i); return; }
}
}
printf("Decrypt: PASS\n");
}
int main()
{
validate();
return 0;
}
#endif
#if USE_OPENSSL_AES
char infoString[] = "OCB3 (OpenSSL)";
#endif
| 50,110
|
C++
|
.cc
| 1,319
| 33.843821
| 135
| 0.572876
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,547
|
ocb_openssl.cc
|
mobile-shell_mosh/src/crypto/ocb_openssl.cc
|
#include "src/crypto/ae.h"
#include "src/include/config.h"
#include <cstring>
#include <openssl/crypto.h>
#include <openssl/evp.h>
struct _ae_ctx
{
EVP_CIPHER_CTX* enc_ctx;
EVP_CIPHER_CTX* dec_ctx;
int tag_len;
};
int ae_clear( ae_ctx* ctx )
{
EVP_CIPHER_CTX_free( ctx->enc_ctx );
EVP_CIPHER_CTX_free( ctx->dec_ctx );
OPENSSL_cleanse( ctx, sizeof( *ctx ) );
return AE_SUCCESS;
}
int ae_ctx_sizeof()
{
return sizeof( _ae_ctx );
}
// If direction is 1, initializes encryption. If 0, initializes
// decryption. See the documentation of EVP_CipherInit_ex
static int ae_evp_cipher_init( EVP_CIPHER_CTX** in_ctx,
int direction,
const unsigned char* key,
int nonce_len,
int tag_len )
{
// Create an OpenSSL EVP context. It does not yet have any specific
// cipher associated with it.
if ( !( *in_ctx = EVP_CIPHER_CTX_new() ) ) {
return -3;
}
EVP_CIPHER_CTX* ctx = *in_ctx;
// Although OCB-AES has the same initialization process between
// encryption and decryption, an EVP_CIPHER_CTX must be initialized
// for a specific direction.
if ( EVP_CipherInit_ex( ctx,
EVP_aes_128_ocb(),
/*impl=*/NULL,
/*key=*/key,
/*iv=*/NULL,
direction )
!= 1 ) {
return -3;
}
// Attempt to set the nonce length. If it fails, the length must not
// be supported. However, that should have been handled by the
// pre-condition check above.
if ( EVP_CIPHER_CTX_ctrl( ctx, EVP_CTRL_AEAD_SET_IVLEN, nonce_len, NULL ) != 1 ) {
return -3;
}
// A NULL tag length means that EVP_CTRL_AEAD_SET_TAG is only being
// used to set the length
if ( EVP_CIPHER_CTX_ctrl( ctx, EVP_CTRL_AEAD_SET_TAG, tag_len, NULL ) != 1 ) {
return -3;
}
return AE_SUCCESS;
}
int ae_init( ae_ctx* ctx, const void* key, int key_len, int nonce_len, int tag_len )
{
// Pre-condition: Only nonces of length 12 are supported. The
// documentation of `ae_init` in ae.h specifies that `ctx` is
// untouched if an invalid configuration is requested. Delegating
// this to OpenSSL would happen too late; `ctx` has already been
// modified.
if ( nonce_len != 12 ) {
return AE_NOT_SUPPORTED;
}
// Pre-condition: Only AES-128 is supported.
if ( key_len != 16 ) {
return AE_NOT_SUPPORTED;
}
int r = AE_SUCCESS;
if ( ( r = ae_evp_cipher_init(
&ctx->enc_ctx, 1, reinterpret_cast<const unsigned char*>( key ), nonce_len, tag_len ) )
!= AE_SUCCESS ) {
return r;
}
if ( ( r = ae_evp_cipher_init(
&ctx->dec_ctx, 0, reinterpret_cast<const unsigned char*>( key ), nonce_len, tag_len ) )
!= AE_SUCCESS ) {
return r;
}
ctx->tag_len = tag_len;
return AE_SUCCESS;
}
int ae_encrypt( ae_ctx* ctx,
const void* nonce_ptr,
const void* pt_ptr,
int pt_len,
const void* ad_ptr,
int ad_len,
void* ct_ptr,
void* tag,
int final )
{
const unsigned char* nonce = reinterpret_cast<const unsigned char*>( nonce_ptr );
const unsigned char* pt = reinterpret_cast<const unsigned char*>( pt_ptr );
const unsigned char* ad = reinterpret_cast<const unsigned char*>( ad_ptr );
unsigned char* ct = reinterpret_cast<unsigned char*>( ct_ptr );
// Streaming mode is not supported; nonce must always be provided.
if ( final != AE_FINALIZE ) {
return AE_NOT_SUPPORTED;
}
if ( nonce == NULL ) {
return AE_NOT_SUPPORTED;
}
if ( EVP_EncryptInit_ex( ctx->enc_ctx,
/*type=*/NULL,
/*impl=*/NULL,
/*key=*/NULL,
nonce )
!= 1 ) {
return -3;
}
int len = 0;
if ( ad != NULL && ad_len > 0 && EVP_EncryptUpdate( ctx->enc_ctx, /*out=*/NULL, &len, ad, ad_len ) != 1 ) {
return -3;
}
len = 0;
if ( pt != NULL && pt_len > 0 && EVP_EncryptUpdate( ctx->enc_ctx, ct, &len, pt, pt_len ) != 1 ) {
return -3;
}
int ciphertext_len = len;
if ( EVP_EncryptFinal_ex( ctx->enc_ctx, ct + ciphertext_len, &len ) != 1 ) {
return -3;
}
ciphertext_len += len;
// If `tag` is provided, the authentication tag goes
// there. Otherwise, it is appended after the ciphertext.
void* tag_location = tag != NULL ? tag : ct + ciphertext_len;
if ( EVP_CIPHER_CTX_ctrl( ctx->enc_ctx, EVP_CTRL_AEAD_GET_TAG, ctx->tag_len, tag_location ) != 1 ) {
return -3;
}
if ( tag == NULL ) {
ciphertext_len += ctx->tag_len;
}
return ciphertext_len;
}
int ae_decrypt( ae_ctx* ctx,
const void* nonce_ptr,
const void* ct_ptr,
int ct_len,
const void* ad_ptr,
int ad_len,
void* pt_ptr,
const void* tag,
int final )
{
const unsigned char* nonce = reinterpret_cast<const unsigned char*>( nonce_ptr );
const unsigned char* ct = reinterpret_cast<const unsigned char*>( ct_ptr );
const unsigned char* ad = reinterpret_cast<const unsigned char*>( ad_ptr );
unsigned char* pt = reinterpret_cast<unsigned char*>( pt_ptr );
if ( ct_len < ctx->tag_len ) {
return AE_INVALID;
}
// If an external tag is not provided, then the tag is assumed to be
// the final bytes of the cipher text. Subtract it off now so the
// plaintext does not accidentally try to decrypt the AEAD tag (and
// then cause an authentication failure).
if ( tag == NULL ) {
ct_len -= ctx->tag_len;
}
// Like encryption, nonce must always be provided and streaming is not supported.
if ( final != AE_FINALIZE ) {
return AE_NOT_SUPPORTED;
}
if ( nonce == NULL ) {
return AE_NOT_SUPPORTED;
}
if ( EVP_DecryptInit_ex( ctx->dec_ctx,
/*type=*/NULL,
/*impl=*/NULL,
/*key=*/NULL,
nonce )
!= 1 ) {
return -3;
}
int len = 0;
if ( ad != NULL && ad_len > 0 && EVP_DecryptUpdate( ctx->dec_ctx, /*out=*/NULL, &len, ad, ad_len ) != 1 ) {
return -3;
}
len = 0;
if ( ct != NULL && ct_len > 0 && EVP_DecryptUpdate( ctx->dec_ctx, pt, &len, ct, ct_len ) != 1 ) {
return -3;
}
int plaintext_len = len;
// If `tag` is provided, the authentication is read from
// there. Otherwise, it's the last bytes of the ciphertext. (This is
// a convention, not a requirement of OCB mode).
const void* tag_location = tag != NULL ? tag : ct + ct_len;
if ( EVP_CIPHER_CTX_ctrl( ctx->dec_ctx, EVP_CTRL_AEAD_SET_TAG, ctx->tag_len, (void*)tag_location ) != 1 ) {
return -3;
}
if ( EVP_DecryptFinal_ex( ctx->dec_ctx, pt + plaintext_len, &len ) != 1 ) {
return AE_INVALID;
}
plaintext_len += len;
return plaintext_len;
}
| 6,974
|
C++
|
.cc
| 203
| 27.881773
| 109
| 0.581103
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,548
|
ntester.cc
|
mobile-shell_mosh/src/examples/ntester.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include <memory>
#include <termios.h>
#include <unistd.h>
#include "src/network/networktransport-impl.h"
#include "src/statesync/user.h"
#include "src/util/fatal_assert.h"
#include "src/util/pty_compat.h"
#include "src/util/select.h"
using namespace Network;
int main( int argc, char* argv[] )
{
bool server = true;
char* key;
char* ip;
char* port;
UserStream me, remote;
using NetworkPointer = std::shared_ptr<Transport<UserStream, UserStream>>;
Transport<UserStream, UserStream>* raw_n;
try {
if ( argc > 1 ) {
server = false;
/* client */
key = argv[1];
ip = argv[2];
port = argv[3];
raw_n = new Transport<UserStream, UserStream>( me, remote, key, ip, port );
} else {
raw_n = new Transport<UserStream, UserStream>( me, remote, NULL, NULL );
}
} catch ( const std::exception& e ) {
fprintf( stderr, "Fatal startup error: %s\n", e.what() );
exit( 1 );
}
NetworkPointer n( raw_n );
fprintf( stderr, "Port bound is %s, key is %s\n", n->port().c_str(), n->get_key().c_str() );
if ( server ) {
Select& sel = Select::get_instance();
uint64_t last_num = n->get_remote_state_num();
while ( true ) {
try {
sel.clear_fds();
std::vector<int> fd_list( n->fds() );
assert( fd_list.size() == 1 ); /* servers don't hop */
int network_fd = fd_list.back();
sel.add_fd( network_fd );
if ( sel.select( n->wait_time() ) < 0 ) {
perror( "select" );
exit( 1 );
}
n->tick();
if ( sel.read( network_fd ) ) {
n->recv();
if ( n->get_remote_state_num() != last_num ) {
fprintf(
stderr, "[%d=>%d %s]", (int)last_num, (int)n->get_remote_state_num(), n->get_remote_diff().c_str() );
last_num = n->get_remote_state_num();
}
}
} catch ( const std::exception& e ) {
fprintf( stderr, "Server error: %s\n", e.what() );
}
}
} else {
struct termios saved_termios;
struct termios the_termios;
if ( tcgetattr( STDIN_FILENO, &the_termios ) < 0 ) {
perror( "tcgetattr" );
exit( 1 );
}
saved_termios = the_termios;
cfmakeraw( &the_termios );
if ( tcsetattr( STDIN_FILENO, TCSANOW, &the_termios ) < 0 ) {
perror( "tcsetattr" );
exit( 1 );
}
Select& sel = Select::get_instance();
while ( true ) {
sel.clear_fds();
sel.add_fd( STDIN_FILENO );
std::vector<int> fd_list( n->fds() );
for ( std::vector<int>::const_iterator it = fd_list.begin(); it != fd_list.end(); it++ ) {
sel.add_fd( *it );
}
try {
if ( sel.select( n->wait_time() ) < 0 ) {
perror( "select" );
}
n->tick();
if ( sel.read( STDIN_FILENO ) ) {
char x;
fatal_assert( read( STDIN_FILENO, &x, 1 ) == 1 );
n->get_current_state().push_back( Parser::UserByte( x ) );
}
bool network_ready_to_read = false;
for ( std::vector<int>::const_iterator it = fd_list.begin(); it != fd_list.end(); it++ ) {
if ( sel.read( *it ) ) {
/* packet received from the network */
/* we only read one socket each run */
network_ready_to_read = true;
}
}
if ( network_ready_to_read ) {
n->recv();
}
} catch ( const std::exception& e ) {
fprintf( stderr, "Client error: %s\n", e.what() );
}
}
if ( tcsetattr( STDIN_FILENO, TCSANOW, &saved_termios ) < 0 ) {
perror( "tcsetattr" );
exit( 1 );
}
}
}
| 5,125
|
C++
|
.cc
| 140
| 30.135714
| 115
| 0.599596
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,549
|
encrypt.cc
|
mobile-shell_mosh/src/examples/encrypt.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include <cstdio>
#include <iostream>
#include <sstream>
#include "src/crypto/crypto.h"
using namespace Crypto;
int main( int argc, char* argv[] )
{
if ( argc != 2 ) {
fprintf( stderr, "Usage: %s NONCE\n", argv[0] );
return 1;
}
try {
Base64Key key;
Session session( key );
Nonce nonce( myatoi( argv[1] ) );
/* Read input */
std::ostringstream input;
input << std::cin.rdbuf();
/* Encrypt message */
std::string ciphertext = session.encrypt( Message( nonce, input.str() ) );
std::cerr << "Key: " << key.printable_key() << std::endl;
std::cout << ciphertext;
} catch ( const CryptoException& e ) {
std::cerr << e.what() << std::endl;
exit( 1 );
}
return 0;
}
| 2,206
|
C++
|
.cc
| 54
| 36.518519
| 78
| 0.709738
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,550
|
termemu.cc
|
mobile-shell_mosh/src/examples/termemu.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include "src/include/config.h"
#include <cassert>
#include <cerrno>
#include <clocale>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cwchar>
#include <cwctype>
#include <exception>
#include <typeinfo>
#include <fcntl.h>
#include <pwd.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <termios.h>
#include <unistd.h>
#if HAVE_PTY_H
#include <pty.h>
#elif HAVE_UTIL_H
#include <util.h>
#elif HAVE_LIBUTIL_H
#include <libutil.h>
#endif
#include "src/statesync/completeterminal.h"
#include "src/terminal/parser.h"
#include "src/util/fatal_assert.h"
#include "src/util/locale_utils.h"
#include "src/util/pty_compat.h"
#include "src/util/select.h"
#include "src/util/swrite.h"
const size_t buf_size = 16384;
static void emulate_terminal( int fd );
int main( int argc, char* argv[] )
{
int master;
struct termios saved_termios, raw_termios, child_termios;
set_native_locale();
fatal_assert( is_utf8_locale() );
if ( tcgetattr( STDIN_FILENO, &saved_termios ) < 0 ) {
perror( "tcgetattr" );
exit( 1 );
}
child_termios = saved_termios;
#ifdef HAVE_IUTF8
if ( !( child_termios.c_iflag & IUTF8 ) ) {
fprintf( stderr, "Warning: Locale is UTF-8 but termios IUTF8 flag not set. Setting IUTF8 flag.\n" );
child_termios.c_iflag |= IUTF8;
}
#else
fprintf( stderr,
"Warning: termios IUTF8 flag not defined. Character-erase of multibyte character sequence probably does "
"not work properly on this platform.\n" );
#endif /* HAVE_IUTF8 */
pid_t child = forkpty( &master, NULL, &child_termios, NULL );
if ( child == -1 ) {
perror( "forkpty" );
exit( 1 );
}
if ( child == 0 ) {
/* child */
if ( setenv( "TERM", "xterm-256color", true ) < 0 ) {
perror( "setenv" );
exit( 1 );
}
/* ask ncurses to send UTF-8 instead of ISO 2022 for line-drawing chars */
if ( setenv( "NCURSES_NO_UTF8_ACS", "1", true ) < 0 ) {
perror( "setenv" );
exit( 1 );
}
char* my_argv[2];
if ( argc > 1 ) {
argv++;
} else {
/* get shell name */
my_argv[0] = getenv( "SHELL" );
if ( my_argv[0] == NULL || *my_argv[0] == '\0' ) {
struct passwd* pw = getpwuid( getuid() );
if ( pw == NULL ) {
perror( "getpwuid" );
exit( 1 );
}
my_argv[0] = strdup( pw->pw_shell );
}
assert( my_argv[0] );
my_argv[1] = NULL;
argv = my_argv;
}
if ( execvp( argv[0], argv ) < 0 ) {
perror( "execve" );
exit( 1 );
}
exit( 0 );
} else {
/* parent */
raw_termios = saved_termios;
cfmakeraw( &raw_termios );
if ( tcsetattr( STDIN_FILENO, TCSANOW, &raw_termios ) < 0 ) {
perror( "tcsetattr" );
exit( 1 );
}
try {
emulate_terminal( master );
} catch ( const std::exception& e ) {
fprintf( stderr, "\r\nException caught: %s\r\n", e.what() );
}
if ( tcsetattr( STDIN_FILENO, TCSANOW, &saved_termios ) < 0 ) {
perror( "tcsetattr" );
exit( 1 );
}
}
printf( "[stm is exiting.]\n" );
return 0;
}
/* Print a frame if the last frame was more than 1/50 seconds ago */
static bool tick( Terminal::Framebuffer& state, Terminal::Framebuffer& new_frame, const Terminal::Display& display )
{
static bool initialized = false;
static struct timeval last_time;
struct timeval this_time;
if ( gettimeofday( &this_time, NULL ) < 0 ) {
perror( "gettimeofday" );
}
double diff = ( this_time.tv_sec - last_time.tv_sec ) + .000001 * ( this_time.tv_usec - last_time.tv_usec );
if ( ( !initialized ) || ( diff >= 0.02 ) ) {
std::string update = display.new_frame( initialized, state, new_frame );
swrite( STDOUT_FILENO, update.c_str() );
state = new_frame;
initialized = true;
last_time = this_time;
return true;
}
return false;
}
/* This is the main loop.
1. New bytes from the user get applied to the terminal emulator
as "UserByte" actions.
2. New bytes from the host get sent to the Parser, and then
those actions are applied to the terminal.
3. Resize events (from a SIGWINCH signal) get turned into
"Resize" actions and applied to the terminal.
At every event from select(), we run the tick() function to
possibly print a new frame (if we haven't printed one in the
last 1/50 second). The new frames are "differential" -- they
assume the previous frame was sent to the real terminal.
*/
static void emulate_terminal( int fd )
{
/* get current window size */
struct winsize window_size;
if ( ioctl( STDIN_FILENO, TIOCGWINSZ, &window_size ) < 0 ) {
perror( "ioctl TIOCGWINSZ" );
return;
}
/* tell child process */
if ( ioctl( fd, TIOCSWINSZ, &window_size ) < 0 ) {
perror( "ioctl TIOCSWINSZ" );
return;
}
/* open parser and terminal */
Terminal::Complete complete( window_size.ws_col, window_size.ws_row );
Terminal::Framebuffer state( window_size.ws_col, window_size.ws_row );
/* open display */
Terminal::Display display( true ); /* use TERM to initialize */
Select& sel = Select::get_instance();
sel.add_fd( STDIN_FILENO );
sel.add_fd( fd );
sel.add_signal( SIGWINCH );
swrite( STDOUT_FILENO, display.open().c_str() );
int timeout = -1;
while ( 1 ) {
int active_fds = sel.select( timeout );
if ( active_fds < 0 ) {
perror( "select" );
break;
}
if ( sel.read( STDIN_FILENO ) ) {
/* input from user */
char buf[buf_size];
/* fill buffer if possible */
ssize_t bytes_read = read( STDIN_FILENO, buf, buf_size );
if ( bytes_read == 0 ) { /* EOF */
return;
} else if ( bytes_read < 0 ) {
perror( "read" );
return;
}
std::string terminal_to_host;
for ( int i = 0; i < bytes_read; i++ ) {
terminal_to_host += complete.act( Parser::UserByte( buf[i] ) );
}
if ( swrite( fd, terminal_to_host.c_str(), terminal_to_host.length() ) < 0 ) {
break;
}
} else if ( sel.read( fd ) ) {
/* input from host */
char buf[buf_size];
/* fill buffer if possible */
ssize_t bytes_read = read( fd, buf, buf_size );
if ( bytes_read == 0 ) { /* EOF */
return;
} else if ( bytes_read < 0 ) {
perror( "read" );
return;
}
std::string terminal_to_host = complete.act( std::string( buf, bytes_read ) );
if ( swrite( fd, terminal_to_host.c_str(), terminal_to_host.length() ) < 0 ) {
break;
}
} else if ( sel.signal( SIGWINCH ) ) {
/* get new size */
if ( ioctl( STDIN_FILENO, TIOCGWINSZ, &window_size ) < 0 ) {
perror( "ioctl TIOCGWINSZ" );
return;
}
/* tell emulator */
complete.act( Parser::Resize( window_size.ws_col, window_size.ws_row ) );
/* tell child process */
if ( ioctl( fd, TIOCSWINSZ, &window_size ) < 0 ) {
perror( "ioctl TIOCSWINSZ" );
return;
}
}
Terminal::Framebuffer new_frame( complete.get_fb() );
if ( tick( state, new_frame, display ) ) { /* there was a frame */
timeout = -1;
} else {
timeout = 20;
}
}
std::string update = display.new_frame( true, state, complete.get_fb() );
swrite( STDOUT_FILENO, update.c_str() );
swrite( STDOUT_FILENO, display.close().c_str() );
}
| 8,921
|
C++
|
.cc
| 263
| 29.102662
| 116
| 0.631646
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,551
|
parse.cc
|
mobile-shell_mosh/src/examples/parse.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include "src/include/config.h"
#include <cassert>
#include <cerrno>
#include <clocale>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cwchar>
#include <cwctype>
#include <typeinfo>
#include <termios.h>
#include <unistd.h>
#if HAVE_PTY_H
#include <pty.h>
#elif HAVE_UTIL_H
#include <util.h>
#elif HAVE_LIBUTIL_H
#include <libutil.h>
#endif
#include "src/terminal/parser.h"
#include "src/util/fatal_assert.h"
#include "src/util/locale_utils.h"
#include "src/util/pty_compat.h"
#include "src/util/select.h"
#include "src/util/swrite.h"
const size_t buf_size = 1024;
static void emulate_terminal( int fd );
static int copy( int src, int dest );
static int vt_parser( int fd, Parser::UTF8Parser* parser );
int main( int argc __attribute__( ( unused ) ), char* argv[] __attribute__( ( unused ) ), char* envp[] )
{
int master;
struct termios saved_termios, raw_termios, child_termios;
set_native_locale();
fatal_assert( is_utf8_locale() );
if ( tcgetattr( STDIN_FILENO, &saved_termios ) < 0 ) {
perror( "tcgetattr" );
exit( 1 );
}
child_termios = saved_termios;
#ifdef HAVE_IUTF8
if ( !( child_termios.c_iflag & IUTF8 ) ) {
fprintf( stderr, "Warning: Locale is UTF-8 but termios IUTF8 flag not set. Setting IUTF8 flag.\n" );
child_termios.c_iflag |= IUTF8;
}
#else
fprintf( stderr,
"Warning: termios IUTF8 flag not defined. Character-erase of multibyte character sequence probably does "
"not work properly on this platform.\n" );
#endif /* HAVE_IUTF8 */
pid_t child = forkpty( &master, NULL, &child_termios, NULL );
if ( child == -1 ) {
perror( "forkpty" );
exit( 1 );
}
if ( child == 0 ) {
/* child */
char* my_argv[2];
my_argv[0] = strdup( "/bin/bash" );
assert( my_argv[0] );
my_argv[1] = NULL;
if ( execve( "/bin/bash", my_argv, envp ) < 0 ) {
perror( "execve" );
exit( 1 );
}
exit( 0 );
} else {
/* parent */
raw_termios = saved_termios;
cfmakeraw( &raw_termios );
if ( tcsetattr( STDIN_FILENO, TCSANOW, &raw_termios ) < 0 ) {
perror( "tcsetattr" );
exit( 1 );
}
emulate_terminal( master );
if ( tcsetattr( STDIN_FILENO, TCSANOW, &saved_termios ) < 0 ) {
perror( "tcsetattr" );
exit( 1 );
}
}
return 0;
}
static void emulate_terminal( int fd )
{
Parser::UTF8Parser parser;
Select& sel = Select::get_instance();
sel.add_fd( STDIN_FILENO );
sel.add_fd( fd );
while ( 1 ) {
int active_fds = sel.select( -1 );
if ( active_fds <= 0 ) {
perror( "select" );
return;
}
if ( sel.read( STDIN_FILENO ) ) {
if ( copy( STDIN_FILENO, fd ) < 0 ) {
return;
}
} else if ( sel.read( fd ) ) {
if ( vt_parser( fd, &parser ) < 0 ) {
return;
}
} else {
fprintf( stderr, "select mysteriously woken up\n" );
}
}
}
static int copy( int src, int dest )
{
char buf[buf_size];
ssize_t bytes_read = read( src, buf, buf_size );
if ( bytes_read == 0 ) { /* EOF */
return -1;
} else if ( bytes_read < 0 ) {
perror( "read" );
return -1;
}
return swrite( dest, buf, bytes_read );
}
static int vt_parser( int fd, Parser::UTF8Parser* parser )
{
char buf[buf_size];
/* fill buffer if possible */
ssize_t bytes_read = read( fd, buf, buf_size );
if ( bytes_read == 0 ) { /* EOF */
return -1;
} else if ( bytes_read < 0 ) {
perror( "read" );
return -1;
}
/* feed to parser */
Parser::Actions actions;
for ( int i = 0; i < bytes_read; i++ ) {
parser->input( buf[i], actions );
for ( Parser::Actions::iterator j = actions.begin(); j != actions.end(); j++ ) {
assert( *j );
Parser::Action& act = **j;
if ( act.char_present ) {
if ( iswprint( act.ch ) ) {
printf( "%s(0x%02x=%lc) ", act.name().c_str(), (unsigned int)act.ch, (wint_t)act.ch );
} else {
printf( "%s(0x%02x) ", act.name().c_str(), (unsigned int)act.ch );
}
} else {
printf( "[%s] ", act.name().c_str() );
}
fflush( stdout );
}
actions.clear();
}
return 0;
}
| 5,661
|
C++
|
.cc
| 179
| 27.402235
| 116
| 0.637383
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,552
|
decrypt.cc
|
mobile-shell_mosh/src/examples/decrypt.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include <cstdio>
#include <iostream>
#include <sstream>
#include "src/crypto/crypto.h"
using namespace Crypto;
int main( int argc, char* argv[] )
{
if ( argc != 2 ) {
fprintf( stderr, "Usage: %s KEY\n", argv[0] );
return 1;
}
try {
Base64Key key( argv[1] );
Session session( key );
/* Read input */
std::ostringstream input;
input << std::cin.rdbuf();
/* Decrypt message */
Message message = session.decrypt( input.str() );
fprintf( stderr, "Nonce = %ld\n", (long)message.nonce.val() );
std::cout << message.text;
} catch ( const CryptoException& e ) {
std::cerr << e.what() << std::endl;
exit( 1 );
}
return 0;
}
| 2,158
|
C++
|
.cc
| 53
| 36.415094
| 73
| 0.712919
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,553
|
benchmark.cc
|
mobile-shell_mosh/src/examples/benchmark.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include "src/include/config.h"
#include <cerrno>
#include <climits>
#include <clocale>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <exception>
#include <pwd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <unistd.h>
#if HAVE_PTY_H
#include <pty.h>
#elif HAVE_UTIL_H
#include <util.h>
#endif
#include "src/frontend/terminaloverlay.h"
#include "src/statesync/completeterminal.h"
#include "src/statesync/user.h"
#include "src/util/fatal_assert.h"
#include "src/util/locale_utils.h"
#include "src/util/swrite.h"
const int ITERATIONS = 100000;
using namespace Terminal;
int main( int argc, char** argv )
{
try {
int fbmod = 0;
int width = 80, height = 24;
int iterations = ITERATIONS;
if ( argc > 1 ) {
iterations = atoi( argv[1] );
if ( iterations < 1 || iterations > 1000000000 ) {
fprintf( stderr, "bogus iteration count\n" );
exit( 1 );
}
}
if ( argc > 3 ) {
width = atoi( argv[2] );
height = atoi( argv[3] );
if ( width < 1 || width > 1000 || height < 1 || height > 1000 ) {
fprintf( stderr, "bogus window size\n" );
exit( 1 );
}
}
Framebuffer local_framebuffers[2] = { Framebuffer( width, height ), Framebuffer( width, height ) };
Framebuffer* local_framebuffer = &( local_framebuffers[fbmod] );
Framebuffer* new_state = &( local_framebuffers[!fbmod] );
Overlay::OverlayManager overlays;
Display display( true );
Complete local_terminal( width, height );
/* Adopt native locale */
set_native_locale();
fatal_assert( is_utf8_locale() );
for ( int i = 0; i < iterations; i++ ) {
/* type a character */
overlays.get_prediction_engine().new_user_byte( i + 'x', *local_framebuffer );
/* fetch target state */
*new_state = local_terminal.get_fb();
/* apply local overlays */
overlays.apply( *new_state );
/* calculate minimal difference from where we are */
const std::string diff( display.new_frame( false, *local_framebuffer, *new_state ) );
/* make sure to use diff */
if ( diff.size() > INT_MAX ) {
exit( 1 );
}
fbmod = !fbmod;
local_framebuffer = &( local_framebuffers[fbmod] );
new_state = &( local_framebuffers[!fbmod] );
}
} catch ( const std::exception& e ) {
fprintf( stderr, "Exception caught: %s\n", e.what() );
return 1;
}
return 0;
}
| 3,949
|
C++
|
.cc
| 106
| 32.764151
| 103
| 0.679048
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,554
|
is-utf8-locale.cc
|
mobile-shell_mosh/src/tests/is-utf8-locale.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include <cstdio>
#include "src/util/locale_utils.h"
int main( int argc __attribute__( ( unused ) ), char** argv __attribute__( ( unused ) ) )
{
set_native_locale();
if ( !is_utf8_locale() ) {
fprintf( stderr, "not a UTF-8 locale\n" );
return 1;
}
return 0;
}
| 1,748
|
C++
|
.cc
| 37
| 43
| 89
| 0.736935
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,555
|
base64.cc
|
mobile-shell_mosh/src/tests/base64.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
/* Test suite for the OCB-AES reference implementation included with Mosh.
This tests cryptographic primitives implemented by others. It uses the
same interfaces and indeed the same compiled object code as the Mosh
client and server. It does not particularly test any code written for
the Mosh project. */
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include "base64_vector.h"
#include "src/crypto/base64.h"
#include "src/crypto/crypto.h"
#include "src/crypto/prng.h"
#include "src/util/fatal_assert.h"
// #include "test_utils.h"
#define KEY_LEN 16
#define NONCE_LEN 12
#define TAG_LEN 16
bool verbose = false;
static void test_base64( void )
{
/* run through a test vector */
char encoded[25];
uint8_t decoded[16];
size_t b64_len = 24;
size_t raw_len = 16;
for ( base64_test_row* row = static_base64_vector; *row->native != '\0'; row++ ) {
memset( encoded, '\0', sizeof encoded );
memset( decoded, '\0', sizeof decoded );
base64_encode( static_cast<const uint8_t*>( row->native ), raw_len, encoded, b64_len );
fatal_assert( b64_len == 24 );
fatal_assert( !memcmp( row->encoded, encoded, sizeof encoded ) );
fatal_assert( base64_decode( row->encoded, b64_len, decoded, &raw_len ) );
fatal_assert( raw_len == 16 );
fatal_assert( !memcmp( row->native, decoded, sizeof decoded ) );
}
if ( verbose ) {
printf( "validation PASSED\n" );
}
/* try 0..255 in the last byte; make sure the final two characters are output properly */
uint8_t source[16];
memset( source, '\0', sizeof source );
for ( int i = 0; i < 256; i++ ) {
source[15] = i;
base64_encode( source, raw_len, encoded, b64_len );
fatal_assert( b64_len == 24 );
fatal_assert( base64_decode( encoded, b64_len, decoded, &raw_len ) );
fatal_assert( raw_len == 16 );
fatal_assert( !memcmp( source, decoded, sizeof decoded ) );
}
if ( verbose ) {
printf( "last-byte PASSED\n" );
}
/* randomly try keys */
PRNG prng;
for ( int i = 0; i < ( 1 << 17 ); i++ ) {
Base64Key key1( prng );
Base64Key key2( key1.printable_key() );
fatal_assert( key1.printable_key() == key2.printable_key() && !memcmp( key1.data(), key2.data(), 16 ) );
}
if ( verbose ) {
printf( "random PASSED\n" );
}
/* test bad keys */
const char* bad_keys[] = {
"",
"AAAAAAAAAAAAAAAAAAAAAA",
"AAAAAAAAAAAAAAAAAAAAAA=",
"AAAAAAAAAAAAAAAAAAAAA==",
"AAAAAAAAAAAAAAAAAAAAAAA==",
"AAAAAAAAAAAAAAAAAAAAAAAA==",
"AAAAAAAAAAAAAAAAAAAAAA~=",
"AAAAAAAAAAAAAAAAAAAAAA=~",
"~AAAAAAAAAAAAAAAAAAAAA==",
"AAAAAAAAAAAAAAAAAAAA~A==",
"AAAAAAAAAAAAAAAAAAAAA~==",
"AAAAAAAAAA~AAAAAAAAAAA==",
"AAAAAAAAAA==",
NULL,
};
for ( const char** key = bad_keys; *key != NULL; key++ ) {
b64_len = 24;
raw_len = 16;
fatal_assert( !base64_decode( *key, b64_len, decoded, &raw_len ) );
}
if ( verbose ) {
printf( "bad-keys PASSED\n" );
}
}
int main( int argc, char* argv[] )
{
if ( argc >= 2 && strcmp( argv[1], "-v" ) == 0 ) {
verbose = true;
}
try {
test_base64();
} catch ( const std::exception& e ) {
fprintf( stderr, "Error: %s\r\n", e.what() );
return 1;
}
return 0;
}
| 4,700
|
C++
|
.cc
| 127
| 33.133858
| 108
| 0.677426
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,556
|
ocb-aes.cc
|
mobile-shell_mosh/src/tests/ocb-aes.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
/* Test suite for the OCB-AES reference implementation included with Mosh.
This tests cryptographic primitives implemented by others. It uses the
same interfaces and indeed the same compiled object code as the Mosh
client and server. It does not particularly test any code written for
the Mosh project. */
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <memory>
#include "src/crypto/ae.h"
#include "src/crypto/crypto.h"
#include "src/crypto/prng.h"
#include "src/util/fatal_assert.h"
#include "test_utils.h"
#define KEY_LEN 16
#define NONCE_LEN 12
#define TAG_LEN 16
using Crypto::AlignedBuffer;
bool verbose = false;
static bool equal( const AlignedBuffer& a, const AlignedBuffer& b )
{
return ( a.len() == b.len() ) && !memcmp( a.data(), b.data(), a.len() );
}
using AlignedPointer = std::shared_ptr<AlignedBuffer>;
static AlignedBuffer* get_ctx( const AlignedBuffer& key )
{
AlignedBuffer* ctx_buf = new AlignedBuffer( ae_ctx_sizeof() );
fatal_assert( ctx_buf );
fatal_assert( AE_SUCCESS == ae_init( (ae_ctx*)ctx_buf->data(), key.data(), key.len(), NONCE_LEN, TAG_LEN ) );
return ctx_buf;
}
static void scrap_ctx( AlignedBuffer& ctx_buf )
{
fatal_assert( AE_SUCCESS == ae_clear( (ae_ctx*)ctx_buf.data() ) );
}
static void test_encrypt( const AlignedBuffer& key,
const AlignedBuffer& nonce,
const AlignedBuffer& plaintext,
const AlignedBuffer& assoc,
const AlignedBuffer& expected_ciphertext )
{
AlignedPointer ctx_buf( get_ctx( key ) );
ae_ctx* ctx = (ae_ctx*)ctx_buf->data();
AlignedBuffer observed_ciphertext( plaintext.len() + TAG_LEN );
const int ret = ae_encrypt( ctx,
nonce.data(),
plaintext.data(),
plaintext.len(),
assoc.data(),
assoc.len(),
observed_ciphertext.data(),
NULL,
AE_FINALIZE );
if ( verbose ) {
printf( "ret %d\n", ret );
hexdump( observed_ciphertext, "obs ct" );
}
fatal_assert( ret == int( expected_ciphertext.len() ) );
fatal_assert( equal( expected_ciphertext, observed_ciphertext ) );
scrap_ctx( *ctx_buf );
}
static void test_decrypt( const AlignedBuffer& key,
const AlignedBuffer& nonce,
const AlignedBuffer& ciphertext,
const AlignedBuffer& assoc,
const AlignedBuffer& expected_plaintext,
bool valid )
{
AlignedPointer ctx_buf( get_ctx( key ) );
ae_ctx* ctx = (ae_ctx*)ctx_buf->data();
AlignedBuffer observed_plaintext( ciphertext.len() - TAG_LEN );
const int ret = ae_decrypt( ctx,
nonce.data(),
ciphertext.data(),
ciphertext.len(),
assoc.data(),
assoc.len(),
observed_plaintext.data(),
NULL,
AE_FINALIZE );
if ( verbose ) {
printf( "ret %d\n", ret );
}
if ( valid ) {
if ( verbose ) {
hexdump( observed_plaintext, "obs pt" );
}
fatal_assert( ret == int( expected_plaintext.len() ) );
fatal_assert( equal( expected_plaintext, observed_plaintext ) );
} else {
fatal_assert( ret == AE_INVALID );
}
scrap_ctx( *ctx_buf );
}
static void test_vector( const char* key_p,
const char* nonce_p,
size_t assoc_len,
const char* assoc_p,
size_t plaintext_len,
const char* plaintext_p,
size_t ciphertext_len,
const char* ciphertext_p )
{
AlignedBuffer key( KEY_LEN, key_p );
AlignedBuffer nonce( NONCE_LEN, nonce_p );
AlignedBuffer plaintext( plaintext_len, plaintext_p );
AlignedBuffer assoc( assoc_len, assoc_p );
AlignedBuffer ciphertext( ciphertext_len, ciphertext_p );
if ( verbose ) {
hexdump( key, "key" );
hexdump( nonce, "nonce" );
hexdump( assoc, "assoc" );
hexdump( plaintext, "exp pt" );
hexdump( ciphertext, "exp ct" );
}
test_encrypt( key, nonce, plaintext, assoc, ciphertext );
test_decrypt( key, nonce, ciphertext, assoc, plaintext, true );
/* Try some bad ciphertexts and make sure they don't validate. */
PRNG prng;
for ( size_t i = 0; i < 64; i++ ) {
AlignedBuffer bad_ct( ciphertext.len(), ciphertext.data() );
( (uint8_t*)bad_ct.data() )[prng.uint32() % bad_ct.len()] ^= ( 1 << ( prng.uint8() % 8 ) );
test_decrypt( key, nonce, bad_ct, assoc, plaintext, false );
}
if ( verbose ) {
printf( "PASSED\n\n" );
}
}
#define TEST_VECTOR( _key, _nonce, _assoc, _pt, _ct ) \
test_vector( _key, _nonce, sizeof( _assoc ) - 1, _assoc, sizeof( _pt ) - 1, _pt, sizeof( _ct ) - 1, _ct )
static void test_all_vectors( void )
{
/* Test vectors from http://tools.ietf.org/html/draft-krovetz-ocb-03#appendix-A */
const char ietf_key[] = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F";
const char ietf_nonce[] = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B";
TEST_VECTOR( ietf_key,
ietf_nonce,
"" /* associated data */
,
"" /* plaintext */
/* ciphertext including tag */
,
"\x19\x7B\x9C\x3C\x44\x1D\x3C\x83\xEA\xFB\x2B\xEF\x63\x3B\x91\x82" );
TEST_VECTOR( ietf_key,
ietf_nonce,
"\x00\x01\x02\x03\x04\x05\x06\x07",
"\x00\x01\x02\x03\x04\x05\x06\x07",
"\x92\xB6\x57\x13\x0A\x74\xB8\x5A\x16\xDC\x76\xA4\x6D\x47\xE1\xEA"
"\xD5\x37\x20\x9E\x8A\x96\xD1\x4E" );
TEST_VECTOR( ietf_key,
ietf_nonce,
"\x00\x01\x02\x03\x04\x05\x06\x07",
"",
"\x98\xB9\x15\x52\xC8\xC0\x09\x18\x50\x44\xE3\x0A\x6E\xB2\xFE\x21" );
TEST_VECTOR( ietf_key,
ietf_nonce,
"",
"\x00\x01\x02\x03\x04\x05\x06\x07",
"\x92\xB6\x57\x13\x0A\x74\xB8\x5A\x97\x1E\xFF\xCA\xE1\x9A\xD4\x71"
"\x6F\x88\xE8\x7B\x87\x1F\xBE\xED" );
TEST_VECTOR( ietf_key,
ietf_nonce,
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F",
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F",
"\xBE\xA5\xE8\x79\x8D\xBE\x71\x10\x03\x1C\x14\x4D\xA0\xB2\x61\x22"
"\x77\x6C\x99\x24\xD6\x72\x3A\x1F\xC4\x52\x45\x32\xAC\x3E\x5B\xEB" );
TEST_VECTOR( ietf_key,
ietf_nonce,
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F",
"",
"\x7D\xDB\x8E\x6C\xEA\x68\x14\x86\x62\x12\x50\x96\x19\xB1\x9C\xC6" );
TEST_VECTOR( ietf_key,
ietf_nonce,
"",
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F",
"\xBE\xA5\xE8\x79\x8D\xBE\x71\x10\x03\x1C\x14\x4D\xA0\xB2\x61\x22"
"\x13\xCC\x8B\x74\x78\x07\x12\x1A\x4C\xBB\x3E\x4B\xD6\xB4\x56\xAF" );
TEST_VECTOR( ietf_key,
ietf_nonce,
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"
"\x10\x11\x12\x13\x14\x15\x16\x17",
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"
"\x10\x11\x12\x13\x14\x15\x16\x17",
"\xBE\xA5\xE8\x79\x8D\xBE\x71\x10\x03\x1C\x14\x4D\xA0\xB2\x61\x22"
"\xFC\xFC\xEE\x7A\x2A\x8D\x4D\x48\x5F\xA9\x4F\xC3\xF3\x88\x20\xF1"
"\xDC\x3F\x3D\x1F\xD4\xE5\x5E\x1C" );
TEST_VECTOR( ietf_key,
ietf_nonce,
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"
"\x10\x11\x12\x13\x14\x15\x16\x17",
"",
"\x28\x20\x26\xDA\x30\x68\xBC\x9F\xA1\x18\x68\x1D\x55\x9F\x10\xF6" );
TEST_VECTOR( ietf_key,
ietf_nonce,
"",
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"
"\x10\x11\x12\x13\x14\x15\x16\x17",
"\xBE\xA5\xE8\x79\x8D\xBE\x71\x10\x03\x1C\x14\x4D\xA0\xB2\x61\x22"
"\xFC\xFC\xEE\x7A\x2A\x8D\x4D\x48\x6E\xF2\xF5\x25\x87\xFD\xA0\xED"
"\x97\xDC\x7E\xED\xE2\x41\xDF\x68" );
TEST_VECTOR( ietf_key,
ietf_nonce,
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"
"\x10\x11\x12\x13\x14\x15\x16\x17",
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"
"\x10\x11\x12\x13\x14\x15\x16\x17",
"\xBE\xA5\xE8\x79\x8D\xBE\x71\x10\x03\x1C\x14\x4D\xA0\xB2\x61\x22"
"\xFC\xFC\xEE\x7A\x2A\x8D\x4D\x48\x5F\xA9\x4F\xC3\xF3\x88\x20\xF1"
"\xDC\x3F\x3D\x1F\xD4\xE5\x5E\x1C" );
TEST_VECTOR( ietf_key,
ietf_nonce,
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17",
"",
"\x28\x20\x26\xDA\x30\x68\xBC\x9F\xA1\x18\x68\x1D\x55\x9F\x10\xF6" );
TEST_VECTOR( ietf_key,
ietf_nonce,
"",
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"
"\x10\x11\x12\x13\x14\x15\x16\x17",
"\xBE\xA5\xE8\x79\x8D\xBE\x71\x10\x03\x1C\x14\x4D\xA0\xB2\x61\x22"
"\xFC\xFC\xEE\x7A\x2A\x8D\x4D\x48\x6E\xF2\xF5\x25\x87\xFD\xA0\xED"
"\x97\xDC\x7E\xED\xE2\x41\xDF\x68" );
TEST_VECTOR( ietf_key,
ietf_nonce,
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"
"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F",
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"
"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F",
"\xBE\xA5\xE8\x79\x8D\xBE\x71\x10\x03\x1C\x14\x4D\xA0\xB2\x61\x22"
"\xCE\xAA\xB9\xB0\x5D\xF7\x71\xA6\x57\x14\x9D\x53\x77\x34\x63\xCB"
"\xB2\xA0\x40\xDD\x3B\xD5\x16\x43\x72\xD7\x6D\x7B\xB6\x82\x42\x40" );
TEST_VECTOR( ietf_key,
ietf_nonce,
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"
"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F",
"",
"\xE1\xE0\x72\x63\x3B\xAD\xE5\x1A\x60\xE8\x59\x51\xD9\xC4\x2A\x1B" );
TEST_VECTOR( ietf_key,
ietf_nonce,
"",
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"
"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F",
"\xBE\xA5\xE8\x79\x8D\xBE\x71\x10\x03\x1C\x14\x4D\xA0\xB2\x61\x22"
"\xCE\xAA\xB9\xB0\x5D\xF7\x71\xA6\x57\x14\x9D\x53\x77\x34\x63\xCB"
"\x4A\x3B\xAE\x82\x44\x65\xCF\xDA\xF8\xC4\x1F\xC5\x0C\x7D\xF9\xD9" );
TEST_VECTOR( ietf_key,
ietf_nonce,
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"
"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F"
"\x20\x21\x22\x23\x24\x25\x26\x27",
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"
"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F"
"\x20\x21\x22\x23\x24\x25\x26\x27",
"\xBE\xA5\xE8\x79\x8D\xBE\x71\x10\x03\x1C\x14\x4D\xA0\xB2\x61\x22"
"\xCE\xAA\xB9\xB0\x5D\xF7\x71\xA6\x57\x14\x9D\x53\x77\x34\x63\xCB"
"\x68\xC6\x57\x78\xB0\x58\xA6\x35\x65\x9C\x62\x32\x11\xDE\xEA\x0D"
"\xE3\x0D\x2C\x38\x18\x79\xF4\xC8" );
TEST_VECTOR( ietf_key,
ietf_nonce,
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"
"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F"
"\x20\x21\x22\x23\x24\x25\x26\x27",
"",
"\x7A\xEB\x7A\x69\xA1\x68\x7D\xD0\x82\xCA\x27\xB0\xD9\xA3\x70\x96" );
TEST_VECTOR( ietf_key,
ietf_nonce,
"",
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"
"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F"
"\x20\x21\x22\x23\x24\x25\x26\x27",
"\xBE\xA5\xE8\x79\x8D\xBE\x71\x10\x03\x1C\x14\x4D\xA0\xB2\x61\x22"
"\xCE\xAA\xB9\xB0\x5D\xF7\x71\xA6\x57\x14\x9D\x53\x77\x34\x63\xCB"
"\x68\xC6\x57\x78\xB0\x58\xA6\x35\x06\x0C\x84\x67\xF4\xAB\xAB\x5E"
"\x8B\x3C\x20\x67\xA2\xE1\x15\xDC" );
/* Some big texts. These were originally encrypted using this program;
they are regression tests. */
TEST_VECTOR( "\x06\xF8\x9F\x69\xDA\x49\xDA\xD7\x68\x48\xFF\xB3\x60\xB6\x8F\x00",
"\xDC\xBF\x85\x18\x23\xD9\x67\x85\x45\x59\x6F\xAD",
"",
"\xC4\x8E\x1F\x04\x10\x2F\xA5\x58\x68\x42\x62\xF3\x1B\xE7\x63\xA7"
"\x77\x89\x64\x16\xE6\xB0\xF7\xFA\xFE\xF0\xB9\x50\x22\xDC\xCE\x78"
"\xA5\x01\xA4\x2D\xA2\x0F\x50\xEA\x9A\xAE\x23\x60\x1C\xC9\x11\x84"
"\x5F\xD0\x0A\x88\x99\xCD\xF1\x1B\x7C\xF9\x71\xC2\xD8\xE3\x7B\xB1"
"\xBC\x91\xCE\x10\xDA\xED\xBF\xA5\xDF\x96\x69\x7A\xFA\xCA\x9A\x91"
"\x40\xF9\x8F\xF1\xFE\x5A\x2B\x21\x17\xA5\xAE\x97\xBD\x0B\x68\xE0"
"\x58\x7A\xB4\x10\x89\xDE\x30\x12\xB7\x14\xEB\xE8\xFA\xA5\x87\x7A"
"\x7E\xEA\xD0\x34\x0B\xAF\x73\x0B\x1C\xA7\xC5\xCB\x84\x15\x5F\x45"
"\x53\x8E\x27\xD7\xA0\x7D\xAF\x99\x05\x6E\x9F\xF4\xCD\xE5\xA1\x11"
"\x43\xBD\x7A\x24\xA3\xB7\xB6\x92\x7C\xB7\xD8\x6F\x17\x78\xB3\x30"
"\x53\x6E\x46\x14\x11\x86\xF6\x70\x2E\x25\x8E\x54\xF8\x70\x2F\x47"
"\x2B\xF8\xF6\xC3\xEE\xFB\x9B\x7D\xF0\x73\xAD\x24\xC0\xE9\x58\xA8"
"\x79\xDC\x92\x25\x6D\xF3\x9D\xA8\x8F\x07\xA3\xE7\xAB\xF4\xBC\x32"
"\x29\xB6\xEF\xDB\x20\x42\x51\xCF\xD5\x57\xDA\x14\xC7\x2A\xB3\x19"
"\xDE\x31\xF7\x77\x95\x8D\x33\x57\x1D\xEB\x9A\x80\x98\x4D\x95\x07"
"\xEB\x38\x42\xEB\xE0\xAB\x2D\xF3\x9E\x16\xFA\x6D\x06\x62\x41\x58"
"\x81\xBF\x3D\x01\x1A\xF7\xBA\x53\xCE\x60\xEF\x86\xC9\x11\xED\x89"
"\x5B\xCF\x98\xB4\xD3\xD4\xAC\xB9\x71\x69\xEE\xF6\xA7\x77\x4E\x46"
"\x0F\xF7\x1D\x7D\x36\x4E\x86\x15\xCD\xF3\xD3\x5C\xAA\x97\x74\xCC"
"\x5D\xD6\xF0\x5C\x62\x27\x0D\x4B\x01\xDD\x8B\xE6\x2C\x72\x99\xBA"
"\x5B\x95\x87\x0F\xB9\x9A\xBE\xA2\x42\x5E\x7D\x1B\x19\x08\xBC\xEF"
"\x66\x24\x2F\xB3\xFC\xE7\xDA\xB1\x79\x51\xE9\x3B\x45\x66\xDC\xD8"
"\x0F\xA7\x56\xBF\x56\x15\x4B\x15\xCC\x3E\x9F\x44\xB9\xED\xC2\x0A"
"\x7C\xA9\x6D\x87\xCD\xE2\x00\x9F\x2F\x2C\xF0\xBC\x1B\xB0\x27\xE8"
"\x46\x3E\x06\x1E\xD5\xB6\xB4\x82\xF7\x88\xB7\x48\xF3\x58\xB0\x23"
"\x6D\xC2\xD3\x85\x9D\x1F\xE5\x30\xFC\xC8\x46\x62\xD1\xE1\xAE\x3B"
"\x3A\xA9\x57\xE0\xD7\x8F\x7E\x4D\x59\x7D\x7A\xEB\xBF\xD3\x10\x00"
"\xA0\xE4\x76\x76\xE3\xA8\x14\xD0\x03\xBF\x1F\x6A\xF9\x11\xCE\x98"
"\x2C\x2A\x86\x25\x77\x85\x14\x76\xD4\x51\xAB\xC7\x3A\xA7\xE1\xF7"
"\x23\xF7\x2B\xA3\xBA\xE4\x0B\xA4\x81\x9A\x83\x98\x69\xC3\x1C\x8A"
"\xBD\x26\x12\x36\x22\x9D\xCE\x85\x5D\xA3\xA0\xDF\x66\xD0\x59\xF6"
"\x47\xF2\xC5\x37\xF1\x62\x0D\x0C\x45\x5B\xE5\xFE\x3C\x8D\x28\x75",
"\xa1\xd8\xa0\xe0\x75\x5c\xb4\xf4\xab\x59\x6d\x14\xfc\x2e\x75\x54"
"\xa3\x35\x4f\x57\x69\x48\x7a\x46\x17\x5f\xd9\x34\x50\xf9\x35\xe5"
"\x6f\xee\x27\xdb\x28\x0f\x06\x0b\xaf\xd5\x50\x4e\x20\x78\x35\xd6"
"\x4d\xa0\x18\xe8\x6c\x5b\x07\xbb\xb6\xd0\x3f\x4a\x0e\x14\x32\xaf"
"\x0d\x6a\x5d\xb6\xe4\x36\xb0\x1c\xae\x2e\x75\x85\x19\x53\x9d\xf2"
"\xc6\xc6\xf5\x29\x4a\x5d\x73\xd6\xcd\x3a\xec\x38\x15\x7b\x1f\x3d"
"\x19\x8f\x7f\x85\x53\x75\xfe\x6c\x8a\x5d\x4f\x05\x3f\x16\x5e\x73"
"\x9c\xbe\xbe\xdb\xe8\xb2\x3e\xea\x0f\x2e\x2c\xf3\x2c\x9c\x56\x5b"
"\xf7\xf2\xed\x87\x07\xfb\x87\x74\x09\xda\xb8\xad\x57\xc0\xa0\x79"
"\xc6\x69\x1c\x79\x08\x69\x35\x18\xc4\x54\xca\x6b\xed\x89\xa0\x27"
"\x32\x19\x1f\xaf\xff\x12\x1c\x1b\x08\xa6\x9f\x0e\xe3\x01\x98\x77"
"\xdb\x75\xdf\x87\x67\x6d\xd9\xb4\x23\x39\xd0\x81\x54\xf8\x89\x18"
"\x5c\xbd\xb7\x4d\xf4\xb1\x8b\x37\x2e\x9b\x20\x29\x9f\x95\x9e\xdd"
"\x73\x2c\xdb\x37\xe5\x7d\x9f\x8a\x79\xff\x8f\x5b\x99\x10\xe1\xe9"
"\x1d\xcb\x1f\x17\xef\x7d\xb7\xd1\x50\x23\x4a\x38\x92\xfb\xbe\x1c"
"\xff\x23\x68\x3a\xb9\xc8\xbc\xa0\xab\xa7\xbe\xc8\x84\xce\x66\xa7"
"\x11\x17\xc6\x48\x91\x4d\x77\xe1\x64\xc4\x26\x08\xcd\xb4\xea\x10"
"\x42\x60\x5a\x7c\x5a\x72\xba\xb4\x93\xf7\x02\xa1\xd4\x44\xdb\x1a"
"\x4a\xc3\xb1\xea\x69\x74\xea\x18\xb3\x5a\x27\x09\x6f\x5b\x1f\x30"
"\xe2\xeb\x2a\x37\x5e\xd2\xe2\x23\xec\xbc\xcb\xcb\x65\x41\xed\x0e"
"\x23\xda\x71\x45\xf3\x3f\x7d\x44\x73\xd7\x14\x4d\xab\x03\xf7\x7d"
"\x24\x33\x9d\x25\x83\x1f\x3d\xf3\xc9\x34\x42\x6c\x2f\x61\xa2\x83"
"\xa0\x0f\xb6\x28\xe8\x27\xf0\x91\xf6\xc5\x7e\xa1\x74\x74\xaf\xa7"
"\x7f\xba\x99\x29\xb2\x91\x9f\xf0\xf7\x71\x1f\xf0\x0b\xd6\xd9\xf9"
"\x72\xaa\x04\x09\x5d\x75\x76\x5f\x18\xc8\xd5\xd5\x84\x1a\x40\x3f"
"\xe5\x38\xe4\x38\xdf\xf9\x0d\x79\xdc\x71\xc8\xa8\xef\x86\x4e\x26"
"\xf4\xc2\x46\xf4\xe0\x64\xd6\x5e\xfb\x1c\x47\x58\x3d\x87\x7c\xba"
"\xa3\xf5\x98\xdc\xd5\xdf\xaf\x62\x96\xee\x4e\x39\x32\x4c\x6d\xd2"
"\x0a\x6f\xf8\x34\x98\x76\xae\x21\xa1\x41\x3d\x96\xfc\x52\xdb\xdd"
"\xf3\x9a\xb1\xf3\x78\x3d\xb8\x2f\xae\xae\x7d\xe0\x4b\xb2\xdf\x2b"
"\x12\xac\xee\xfb\xf8\x54\x60\xea\x74\xd5\xde\x43\x7b\x38\x45\x5f"
"\xa0\xb8\xe8\xcc\x8a\xe3\xcc\x0c\x92\xe6\xb1\xb0\xe2\xc1\x99\xca"
"\x1b\xa1\xac\x6e\x7a\x8a\xa0\x20\x3d\xeb\x29\x8b\xf4\x55\x41\x62" );
TEST_VECTOR( "\x7A\x54\x0D\x3E\x56\x38\xF7\xC6\xCF\xAB\xF9\x56\xDC\xCA\x14\x23",
"\x9B\x0E\xC1\x15\xD5\xE6\xC9\xAB\xE6\x88\x2A\x18",
"",
"\x52\xDB\xA7\x44\x2B\x1C\x9C\x24\x4D\xF3\xA1\xE4\x53\x7B\x9B\xB2"
"\x25\xC5\xA3\x81\x42\x23\xA9\xB4\x12\xF8\xFC\xE4\xF6\x8E\x20\xD4"
"\x59\x7B\x39\x2D\x5D\x7C\x6E\xB7\x51\x02\x90\x7A\x8E\xAA\x30\xD0"
"\xEB\xDF\x70\x09\x5A\xEC\xFB\xD4\xDB\x0B\xE9\x1B\x79\xAF\x40\xA3"
"\xC9\xD1\x3F\x0E\x7E\x9B\xA8\xF2\x4E\xA2\xAE\x81\xE7\x8F\xE9\x4A"
"\xF8\x84\x38\x20\x9B\xCB\x0D\x9E\x46\x87\xCC\x0C\x71\xF2\x4C\xE5"
"\x57\x47\xFB\x52\x1D\x0C\x92\xCD\x9B\xD0\xA3\xA3\xFE\x44\x4F\x2A"
"\x2D\x7D\xC8\x48\x87\x71\x8A\x83\x83\x43\x52\xD9\x87\x72\x0A\x1F"
"\x72\x7D\xE0\x0D\xE4\xBA\x38\x2D\xAB\x89\x85\x34\xFE\x30\xE9\x47"
"\x99\x69\x96\x37\x3B\x88\x0D\x08\x5B\x41\xF0\x55\x3A\x90\xB6\x5D"
"\xC9\xB8\xFA\x22\xEB\x54\x67\x1B\x43\x3B\x2A\x13\xDF\x76\x71\xBF"
"\x8F\xBA\xF6\x5F\xE0\xAE\x84\x80\xD3\x9A\x9E\xFE\x35\x29\x0C\x44"
"\xB8\x3B\xC8\x58\x3F\x51\x18\xF0\x8E\x3F\xE0\xFE\xFF\x55\xE1\xFD"
"\x79\xED\x71\x6D\xB9\xBE\xF0\x76\x25\x4E\x6F\xA2\x49\x5B\xEC\x20"
"\x61\x95\x65\x67\xBF\xA3\x73\x18\x65\x7C\x2F\x94\x29\x3B\x57\x7D"
"\x78\x6A\xBD\x22\x2B\x17\x5E\xDA\x2B\x4E\xC3\xA5\xF0\x9A\xD9\x1C"
"\xCF\xC4\xDD\x7E\x07\xB4\xE6\x50\xD0\x9D\xAF\x86\x9D\x3F\xFE\x70"
"\x64\x18\xBA\x32\x90\xE5\x63\xA0\x08\x3D\x1D\xCE\xB2\x77\x31\x59"
"\xD4\xB4\x03\x2C\xE2\x15\x11\x17\xD1\xBA\x5E\x1E\x7D\x38\x09\xCF"
"\x25\x3E\x3D\x89\x7E\x13\xAE\x11\xFA\xCD\x46\x23\x86\xC5\x78\xC8"
"\x1A\xE8\x8F\x9A\x9C\xCE\xBE\x01\x5D\x70\x56\xA8\x84\x07\x07\x2A"
"\x1C\xD4\x33\x8B\x2F\x01\x0F\xD0\xCC\xCD\x29\xEC\x73\x6E\xDE\xB2"
"\xBC\xA7\x32\x6A\x12\x93\x13\xCD\xE0\xA9\x55\x97\x36\x6B\xDA\xC5"
"\xC5\xD2\x44\x80\xBD\x00\x37\xD7\x21\x80\x27\x1F\x2E\x02\x76\x1A"
"\x57\xA5\x5F\xCE\x8B\x20\x6A\x6A\x0F\x70\x9B\xDB\x07\x64\x96\x7B"
"\x43\xFD\xCA\xBF\x9D\x52\xEB\x24\x7B\x1B\xEE\x43\x10\x2C\xDB\x92"
"\xA1\xA8\xA9\xF7\x2F\xD2\x39\xA8\x85\x9C\xFE\x2C\x2A\xCF\x52\x73"
"\xFB\xCA\x20\xAD\xC9\xDD\xFC\x4A\x91\x39\x6C\x7C\x84\x67\xC5\xE4"
"\x9B\x3E\x3D\x6B\x56\x3B\x2B\xDC\x8A\x46\xF6\x7C\x36\xF9\x27\x29"
"\x37\x38\x7C\x9D\xA0\x6E\x5D\x4C\xE5\xB2\x6F\x0C\xDC\xEF\xFE\x35"
"\xFE\x3D\x56\x40\x7F\xBD\x4D\xDD\x40\x79\xDD\xA7\x0A\x7B\xA2\xCE"
"\x22\x38\x94\xEA\x90\xF5\x95\xB6\xE6\x6F\x14\xFB\xA2",
"\xec\xa9\xcc\x30\x66\x6c\x04\x16\x21\x8d\xc8\x15\x47\xa2\x18\xcf"
"\x19\x90\x4f\x82\x27\x25\xa2\x1e\xfa\x1c\xe4\x58\x78\x43\x52\x4c"
"\xac\x24\xde\xcb\xad\x80\x05\x7a\xeb\x2d\xc0\x33\x05\x31\x25\x44"
"\xd7\x11\xa1\xf2\xcb\x09\x6f\xf0\x14\x3c\x3f\xf2\xc7\x79\xfb\x3f"
"\xb0\x0a\x65\xae\xd7\xe5\x5d\x35\x0c\xb4\x69\x7a\x89\x6b\xa9\xdc"
"\x02\x69\x96\xd2\x9f\xe7\x3c\x99\xd4\xd3\x55\x97\xc4\x59\xad\xc4"
"\x0c\x7b\xf8\x47\x1c\xbe\x36\x2a\x53\x6b\xb1\x21\x5f\xc1\x6e\xca"
"\x0a\x4f\x16\x3a\xf0\xd4\x12\xa6\xf8\x68\x9f\x12\xad\x36\x4c\xd8"
"\x5a\x5b\x17\xb8\xbd\xc7\x2c\x48\x51\x7d\x45\x74\x00\xb0\x02\xe9"
"\x1b\xd6\x0c\x41\xa7\x5d\x65\xca\x68\xa7\x3e\x3c\xf5\xaa\x9b\xbd"
"\x25\x98\x00\xd8\x4d\xbc\xd1\x7a\x25\x34\x92\x24\xa4\x84\x62\x63"
"\x2c\x40\xa5\x58\x81\x90\xf1\x0f\x75\xaa\x70\xe4\x4e\x0f\xa3\x03"
"\x90\xd1\x07\x18\x0a\x50\x9a\x3e\x28\x1f\x33\xb7\x11\xed\x3c\x2c"
"\x40\xc8\xd7\xe3\x12\xdc\xef\x94\x93\x7b\x11\xc3\x24\x51\x61\xbf"
"\x8b\xa4\xa4\x5c\x85\x0d\x50\x49\x45\x69\xbe\x5b\x36\x90\x84\x30"
"\x66\x67\x76\x3d\xcc\x02\x8b\x9f\xb7\x90\x57\xef\xe1\x21\x34\x65"
"\x3e\xca\xbf\x70\x1d\x76\x63\xbf\xae\x1f\xb2\x55\xf0\x87\x3e\x42"
"\xf9\x71\x28\x02\x06\x9e\xf7\x6a\x47\x3b\xda\x38\x54\x66\xd9\xaf"
"\xba\x7b\xec\xbf\xe3\x52\x63\x02\x8b\xa7\xad\x1d\x76\x16\xa2\x20"
"\x38\xec\x40\xb7\xc8\x35\x6b\xc2\x80\x9d\x20\x02\xc6\x34\xdb\x65"
"\xd8\x27\x0b\xc5\x2d\x85\xe4\xdc\x85\xae\x10\x36\x01\xdb\x4b\xaf"
"\x44\x79\xea\x23\x21\xa0\x83\xa3\x91\xf5\xc5\x16\x9b\xeb\x43\x92"
"\x1f\x88\xd2\x00\x60\x40\xe9\x52\x0b\x39\x86\x3b\x9e\x3b\x9a\x4a"
"\x31\xdf\xb6\x57\x78\x38\xcf\x77\x7c\x0c\xf4\x14\x90\x25\xed\x27"
"\xd2\x86\x20\x4c\x1a\x52\xeb\xbe\x1e\xac\x2b\xce\xb7\x72\x86\x87"
"\xfd\xac\x11\x90\xc5\xea\x96\xcb\xdc\x89\xe9\x77\xf0\x83\xc3\xa7"
"\xa7\xd1\xe1\xc9\x7e\x89\xb3\x4e\xf1\x12\xa3\x9c\xfe\x66\xcc\x5d"
"\xcf\x1d\x5a\x11\x21\x2f\x10\x66\x37\x5f\xd7\x35\xeb\x09\x62\x99"
"\xa6\xf8\xc7\xc7\xef\xd3\xf0\x56\x2b\xa7\x14\x65\x6a\xce\xa9\x68"
"\xe7\xa4\x89\xb4\x1e\x16\x99\xbf\x8d\x2d\x5e\x67\xb4\x3a\x0b\xf3"
"\x37\x14\x1e\x5d\xc6\xb4\xb5\x9e\xa5\x69\xa4\xaf\xcc\x0f\x46\xe9"
"\xd5\xbb\x10\x49\x07\x0d\x92\x42\x0c\x04\xb9\xdf\xa4\xb5\xef\xcc"
"\x05\x81\x3f\xc1\x21\x12\x2c\x33\xb7\x79\xfd\x5d\x8a" );
}
/* http://tools.ietf.org/html/draft-krovetz-ocb-03#appendix-A
also specifies an iterative test algorithm, which we implement here. */
static void test_iterative( void )
{
/* Key is always all zeros */
AlignedBuffer key( KEY_LEN );
memset( key.data(), 0, KEY_LEN );
AlignedPointer ctx_buf( get_ctx( key ) );
ae_ctx* ctx = (ae_ctx*)ctx_buf->data();
AlignedBuffer nonce( NONCE_LEN );
memset( nonce.data(), 0, NONCE_LEN );
/* The loop below fills this buffer in order.
Each iteration adds 2*i + 3*TAG_LEN bytes. */
AlignedBuffer accumulator( 22400 );
uint8_t* acc = (uint8_t*)accumulator.data();
for ( size_t i = 0; i < 128; i++ ) {
/* i bytes of zeros */
AlignedBuffer s( i );
memset( s.data(), 0, s.len() );
/* Nonce is 11 bytes of zeros followed by 1 byte i */
( (uint8_t*)nonce.data() )[11] = i;
/* We can't write directly to acc because it might not be aligned. */
AlignedBuffer out( s.len() + TAG_LEN );
/* OCB-ENCRYPT(K,N,S,S) */
fatal_assert(
0 <= ae_encrypt( ctx, nonce.data(), s.data(), s.len(), s.data(), s.len(), out.data(), NULL, AE_FINALIZE ) );
memcpy( acc, out.data(), s.len() + TAG_LEN );
acc += s.len() + TAG_LEN;
/* OCB-ENCRYPT(K,N,<empty string>,S) */
fatal_assert( 0 <= ae_encrypt( ctx, nonce.data(), s.data(), s.len(), NULL, 0, out.data(), NULL, AE_FINALIZE ) );
memcpy( acc, out.data(), s.len() + TAG_LEN );
acc += s.len() + TAG_LEN;
/* OCB-ENCRYPT(K,N,S,<empty string>) */
fatal_assert( 0 <= ae_encrypt( ctx, nonce.data(), NULL, 0, s.data(), s.len(), out.data(), NULL, AE_FINALIZE ) );
memcpy( acc, out.data(), TAG_LEN );
acc += TAG_LEN;
}
/* OCB-ENCRYPT(K,N,C,<empty string>) */
AlignedBuffer out( TAG_LEN );
memset( nonce.data(), 0, NONCE_LEN );
fatal_assert(
0 <= ae_encrypt(
ctx, nonce.data(), NULL, 0, accumulator.data(), accumulator.len(), out.data(), NULL, AE_FINALIZE ) );
/* Check this final tag against the known value */
AlignedBuffer correct( TAG_LEN, "\xB2\xB4\x1C\xBF\x9B\x05\x03\x7D\xA7\xF1\x6C\x24\xA3\x5C\x1C\x94" );
fatal_assert( equal( out, correct ) );
if ( verbose ) {
printf( "iterative PASSED\n\n" );
}
scrap_ctx( *ctx_buf );
}
int main( int argc, char* argv[] )
{
if ( argc >= 2 && strcmp( argv[1], "-v" ) == 0 ) {
verbose = true;
}
try {
test_all_vectors();
test_iterative();
} catch ( const std::exception& e ) {
fprintf( stderr, "Error: %s\r\n", e.what() );
return 1;
}
return 0;
}
| 28,226
|
C++
|
.cc
| 504
| 44.539683
| 116
| 0.583014
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,557
|
test_utils.cc
|
mobile-shell_mosh/src/tests/test_utils.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include <cstdio>
#include "test_utils.h"
void hexdump( const void* buf, size_t len, const char* name )
{
const unsigned char* data = (const unsigned char*)buf;
printf( DUMP_NAME_FMT, name );
for ( size_t i = 0; i < len; i++ ) {
// Although data[i] is an unsigned char, it will be promoted to a signed int
// when passed as an argument. Explicitly cast it back to an unsigned type
// so it can be printed in hex.
printf( "%02x", static_cast<unsigned>( data[i] ) );
}
printf( "\n" );
}
void hexdump( const Crypto::AlignedBuffer& buf, const char* name )
{
hexdump( buf.data(), buf.len(), name );
}
void hexdump( const std::string& buf, const char* name )
{
hexdump( buf.data(), buf.size(), name );
}
| 2,202
|
C++
|
.cc
| 48
| 42.041667
| 80
| 0.727612
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,558
|
nonce-incr.cc
|
mobile-shell_mosh/src/tests/nonce-incr.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
/* Tests that the Mosh network layer seems to be using unique nonces */
#include <cstdlib>
#include <iostream>
#include <set>
#include "src/network/network.h"
int main()
{
std::set<uint64_t> nonces;
const unsigned int NUM_EXAMPLES = 1000000;
for ( unsigned int i = 0; i < NUM_EXAMPLES; i++ ) {
Network::Packet packet( Network::TO_CLIENT, 0, 0, "test" );
nonces.insert( packet.toMessage().nonce.val() );
}
for ( unsigned int i = 0; i < NUM_EXAMPLES; i++ ) {
Network::Packet packet( Network::TO_SERVER, 0, 0, "test" );
nonces.insert( packet.toMessage().nonce.val() );
}
for ( unsigned int i = 0; i < NUM_EXAMPLES; i++ ) {
{
Network::Packet packet( Network::TO_SERVER, 0, 0, "test" );
nonces.insert( packet.toMessage().nonce.val() );
}
{
Network::Packet packet( Network::TO_CLIENT, 0, 0, "test" );
nonces.insert( packet.toMessage().nonce.val() );
}
}
if ( nonces.size() == 4 * NUM_EXAMPLES ) {
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
| 2,498
|
C++
|
.cc
| 58
| 38.741379
| 73
| 0.707629
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,559
|
encrypt-decrypt.cc
|
mobile-shell_mosh/src/tests/encrypt-decrypt.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
/* Tests the Mosh crypto layer by encrypting and decrypting a bunch of random
messages, interspersed with some random bad ciphertexts which we need to
reject. */
#include <cstdio>
#define __STDC_FORMAT_MACROS
#include <cinttypes>
#include "src/crypto/crypto.h"
#include "src/crypto/prng.h"
#include "src/util/fatal_assert.h"
#include "test_utils.h"
using namespace Crypto;
PRNG prng;
const size_t MESSAGE_SIZE_MAX = ( 2048 - 16 );
const size_t MESSAGES_PER_SESSION = 256;
const size_t NUM_SESSIONS = 64;
bool verbose = false;
#define NONCE_FMT "%016" PRIx64
static std::string random_payload( void )
{
const size_t len = prng.uint32() % MESSAGE_SIZE_MAX;
char buf[MESSAGE_SIZE_MAX];
prng.fill( buf, len );
std::string payload( buf, len );
return payload;
}
static void test_bad_decrypt( Session& decryption_session )
{
std::string bad_ct = random_payload();
bool got_exn = false;
try {
decryption_session.decrypt( bad_ct );
} catch ( const CryptoException& e ) {
got_exn = true;
/* The "bad decrypt" exception needs to be non-fatal, otherwise we are
vulnerable to an easy DoS. */
fatal_assert( !e.fatal );
}
if ( verbose ) {
hexdump( bad_ct, "bad ct" );
}
fatal_assert( got_exn );
}
/* Generate a single key and initial nonce, then perform some encryptions. */
static void test_one_session( void )
{
Base64Key key;
Session encryption_session( key );
Session decryption_session( key );
uint64_t nonce_int = prng.uint64();
if ( verbose ) {
hexdump( key.data(), 16, "key" );
}
for ( size_t i = 0; i < MESSAGES_PER_SESSION; i++ ) {
Nonce nonce( nonce_int );
fatal_assert( nonce.val() == nonce_int );
std::string plaintext = random_payload();
if ( verbose ) {
printf( DUMP_NAME_FMT NONCE_FMT "\n", "nonce", nonce_int );
hexdump( plaintext, "pt" );
}
std::string ciphertext = encryption_session.encrypt( Message( nonce, plaintext ) );
if ( verbose ) {
hexdump( ciphertext, "ct" );
}
Message decrypted = decryption_session.decrypt( ciphertext );
if ( verbose ) {
printf( DUMP_NAME_FMT NONCE_FMT "\n", "dec nonce", decrypted.nonce.val() );
hexdump( decrypted.text, "dec pt" );
}
fatal_assert( decrypted.nonce.val() == nonce_int );
fatal_assert( decrypted.text == plaintext );
nonce_int++;
if ( !( prng.uint8() % 16 ) ) {
test_bad_decrypt( decryption_session );
}
if ( verbose ) {
printf( "\n" );
}
}
}
int main( int argc, char* argv[] )
{
if ( argc >= 2 && strcmp( argv[1], "-v" ) == 0 ) {
verbose = true;
}
for ( size_t i = 0; i < NUM_SESSIONS; i++ ) {
try {
test_one_session();
} catch ( const CryptoException& e ) {
fprintf( stderr, "Crypto exception: %s\r\n", e.what() );
return 1;
}
}
return 0;
}
| 4,329
|
C++
|
.cc
| 121
| 31.743802
| 87
| 0.683517
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,560
|
inpty.cc
|
mobile-shell_mosh/src/tests/inpty.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include "src/include/config.h"
#include <cerrno>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sys/types.h>
#include <sys/wait.h>
#include <termios.h>
#include <unistd.h>
#if HAVE_PTY_H
#include <pty.h>
#elif HAVE_UTIL_H
#include <util.h>
#endif
#if FORKPTY_IN_LIBUTIL
#include <libutil.h>
#endif
#include "src/util/pty_compat.h"
#include "src/util/swrite.h"
int main( int argc, char* argv[] )
{
if ( argc < 2 ) {
fprintf( stderr, "usage: inpty COMMAND [ARGS...]\n" );
return 1;
}
struct winsize winsize;
memset( &winsize, 0, sizeof( winsize ) );
winsize.ws_col = 80;
winsize.ws_row = 24;
int saved_stderr = dup( STDERR_FILENO );
if ( saved_stderr < 0 ) {
perror( "dup" );
return 1;
}
int master;
pid_t child = forkpty( &master, NULL, NULL, &winsize );
if ( child == -1 ) {
perror( "forkpty" );
/* The Debian and Ubuntu build systems fail to set up a working
* /dev/ptmx (https://bugs.debian.org/817236). There is not much
* we can do about that except skip the test. In the future when
* this is fixed, we should turn this into an failure.
*/
return 77;
} else if ( child == 0 ) {
if ( dup2( saved_stderr, STDERR_FILENO ) < 0 ) {
perror( "dup2" );
exit( 1 );
}
if ( close( saved_stderr ) < 0 ) {
perror( "close" );
exit( 1 );
}
if ( execvp( argv[1], argv + 1 ) < 0 ) {
perror( "execve" );
exit( 1 );
}
exit( 0 );
}
while ( 1 ) {
char buf[1024];
ssize_t bytes_read = read( master, buf, sizeof( buf ) );
if ( bytes_read == 0 || ( bytes_read < 0 && errno == EIO ) ) { /* EOF */
break;
} else if ( bytes_read < 0 ) {
perror( "read" );
return 1;
}
swrite( STDOUT_FILENO, buf, bytes_read );
}
int wstatus;
if ( waitpid( child, &wstatus, 0 ) < 0 ) {
perror( "waitpid" );
return 1;
}
if ( WIFSIGNALED( wstatus ) ) {
fprintf( stderr, "inpty: child exited with signal %d\n", WTERMSIG( wstatus ) );
raise( WTERMSIG( wstatus ) );
return -1;
} else {
return WIFEXITED( wstatus ) ? WEXITSTATUS( wstatus ) : -1;
}
}
| 3,648
|
C++
|
.cc
| 110
| 29.109091
| 83
| 0.661932
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,561
|
user.cc
|
mobile-shell_mosh/src/statesync/user.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include <cassert>
#include <typeinfo>
#include "src/protobufs/userinput.pb.h"
#include "src/statesync/user.h"
#include "src/util/fatal_assert.h"
using namespace Parser;
using namespace Network;
using namespace ClientBuffers;
void UserStream::subtract( const UserStream* prefix )
{
// if we are subtracting ourself from ourself, just clear the std::deque
if ( this == prefix ) {
actions.clear();
return;
}
for ( std::deque<UserEvent>::const_iterator i = prefix->actions.begin(); i != prefix->actions.end(); i++ ) {
assert( this != prefix );
assert( !actions.empty() );
assert( *i == actions.front() );
actions.pop_front();
}
}
std::string UserStream::diff_from( const UserStream& existing ) const
{
std::deque<UserEvent>::const_iterator my_it = actions.begin();
for ( std::deque<UserEvent>::const_iterator i = existing.actions.begin(); i != existing.actions.end(); i++ ) {
assert( my_it != actions.end() );
assert( *i == *my_it );
my_it++;
}
ClientBuffers::UserMessage output;
while ( my_it != actions.end() ) {
switch ( my_it->type ) {
case UserByteType: {
char the_byte = my_it->userbyte.c;
/* can we combine this with a previous Keystroke? */
if ( ( output.instruction_size() > 0 )
&& ( output.instruction( output.instruction_size() - 1 ).HasExtension( keystroke ) ) ) {
output.mutable_instruction( output.instruction_size() - 1 )
->MutableExtension( keystroke )
->mutable_keys()
->append( std::string( &the_byte, 1 ) );
} else {
Instruction* new_inst = output.add_instruction();
new_inst->MutableExtension( keystroke )->set_keys( &the_byte, 1 );
}
} break;
case ResizeType: {
Instruction* new_inst = output.add_instruction();
new_inst->MutableExtension( resize )->set_width( my_it->resize.width );
new_inst->MutableExtension( resize )->set_height( my_it->resize.height );
} break;
default:
assert( !"unexpected event type" );
break;
}
my_it++;
}
return output.SerializeAsString();
}
void UserStream::apply_string( const std::string& diff )
{
ClientBuffers::UserMessage input;
fatal_assert( input.ParseFromString( diff ) );
for ( int i = 0; i < input.instruction_size(); i++ ) {
if ( input.instruction( i ).HasExtension( keystroke ) ) {
std::string the_bytes = input.instruction( i ).GetExtension( keystroke ).keys();
for ( unsigned int loc = 0; loc < the_bytes.size(); loc++ ) {
actions.push_back( UserEvent( UserByte( the_bytes.at( loc ) ) ) );
}
} else if ( input.instruction( i ).HasExtension( resize ) ) {
actions.push_back( UserEvent( Resize( input.instruction( i ).GetExtension( resize ).width(),
input.instruction( i ).GetExtension( resize ).height() ) ) );
}
}
}
const Parser::Action& UserStream::get_action( unsigned int i ) const
{
switch ( actions[i].type ) {
case UserByteType:
return actions[i].userbyte;
case ResizeType:
return actions[i].resize;
default:
assert( !"unexpected action type" );
static const Parser::Ignore nothing = Parser::Ignore();
return nothing;
}
}
| 4,772
|
C++
|
.cc
| 115
| 36
| 112
| 0.669325
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,562
|
completeterminal.cc
|
mobile-shell_mosh/src/statesync/completeterminal.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include <climits>
#include "src/protobufs/hostinput.pb.h"
#include "src/statesync/completeterminal.h"
#include "src/util/fatal_assert.h"
using namespace std;
using namespace Parser;
using namespace Terminal;
using namespace HostBuffers;
string Complete::act( const string& str )
{
for ( unsigned int i = 0; i < str.size(); i++ ) {
/* parse octet into up to three actions */
parser.input( str[i], actions );
/* apply actions to terminal and delete them */
for ( Actions::iterator it = actions.begin(); it != actions.end(); it++ ) {
Action& act = **it;
act.act_on_terminal( &terminal );
}
actions.clear();
}
return terminal.read_octets_to_host();
}
string Complete::act( const Action& act )
{
/* apply action to terminal */
act.act_on_terminal( &terminal );
return terminal.read_octets_to_host();
}
/* interface for Network::Transport */
string Complete::diff_from( const Complete& existing ) const
{
HostBuffers::HostMessage output;
if ( existing.get_echo_ack() != get_echo_ack() ) {
assert( get_echo_ack() >= existing.get_echo_ack() );
Instruction* new_echo = output.add_instruction();
new_echo->MutableExtension( echoack )->set_echo_ack_num( get_echo_ack() );
}
if ( !( existing.get_fb() == get_fb() ) ) {
if ( ( existing.get_fb().ds.get_width() != terminal.get_fb().ds.get_width() )
|| ( existing.get_fb().ds.get_height() != terminal.get_fb().ds.get_height() ) ) {
Instruction* new_res = output.add_instruction();
new_res->MutableExtension( resize )->set_width( terminal.get_fb().ds.get_width() );
new_res->MutableExtension( resize )->set_height( terminal.get_fb().ds.get_height() );
}
string update = display.new_frame( true, existing.get_fb(), terminal.get_fb() );
if ( !update.empty() ) {
Instruction* new_inst = output.add_instruction();
new_inst->MutableExtension( hostbytes )->set_hoststring( update );
}
}
return output.SerializeAsString();
}
string Complete::init_diff( void ) const
{
return diff_from( Complete( get_fb().ds.get_width(), get_fb().ds.get_height() ) );
}
void Complete::apply_string( const string& diff )
{
HostBuffers::HostMessage input;
fatal_assert( input.ParseFromString( diff ) );
for ( int i = 0; i < input.instruction_size(); i++ ) {
if ( input.instruction( i ).HasExtension( hostbytes ) ) {
string terminal_to_host = act( input.instruction( i ).GetExtension( hostbytes ).hoststring() );
assert( terminal_to_host.empty() ); /* server never interrogates client terminal */
} else if ( input.instruction( i ).HasExtension( resize ) ) {
act( Resize( input.instruction( i ).GetExtension( resize ).width(),
input.instruction( i ).GetExtension( resize ).height() ) );
} else if ( input.instruction( i ).HasExtension( echoack ) ) {
uint64_t inst_echo_ack_num = input.instruction( i ).GetExtension( echoack ).echo_ack_num();
assert( inst_echo_ack_num >= echo_ack );
echo_ack = inst_echo_ack_num;
}
}
}
bool Complete::operator==( Complete const& x ) const
{
// assert( parser == x.parser ); /* parser state is irrelevant for us */
return ( terminal == x.terminal ) && ( echo_ack == x.echo_ack );
}
bool Complete::set_echo_ack( uint64_t now )
{
bool ret = false;
uint64_t newest_echo_ack = 0;
for ( input_history_type::const_iterator i = input_history.begin(); i != input_history.end(); i++ ) {
if ( i->second <= now - ECHO_TIMEOUT ) {
newest_echo_ack = i->first;
}
}
for ( input_history_type::iterator i = input_history.begin(); i != input_history.end(); ) {
input_history_type::iterator i_next = i;
i_next++;
if ( i->first < newest_echo_ack ) {
input_history.erase( i );
}
i = i_next;
}
if ( echo_ack != newest_echo_ack ) {
ret = true;
}
echo_ack = newest_echo_ack;
return ret;
}
void Complete::register_input_frame( uint64_t n, uint64_t now )
{
input_history.push_back( std::make_pair( n, now ) );
}
int Complete::wait_time( uint64_t now ) const
{
if ( input_history.size() < 2 ) {
return INT_MAX;
}
input_history_type::const_iterator it = input_history.begin();
it++;
uint64_t next_echo_ack_time = it->second + ECHO_TIMEOUT;
if ( next_echo_ack_time <= now ) {
return 0;
}
return next_echo_ack_time - now;
}
bool Complete::compare( const Complete& other ) const
{
bool ret = false;
const Framebuffer& fb = terminal.get_fb();
const Framebuffer& other_fb = other.terminal.get_fb();
const int height = fb.ds.get_height();
const int other_height = other_fb.ds.get_height();
const int width = fb.ds.get_width();
const int other_width = other_fb.ds.get_width();
if ( height != other_height || width != other_width ) {
fprintf( stderr, "Framebuffer size (%dx%d, %dx%d) differs.\n", width, height, other_width, other_height );
return true;
}
for ( int y = 0; y < height; y++ ) {
for ( int x = 0; x < width; x++ ) {
if ( fb.get_cell( y, x )->compare( *other_fb.get_cell( y, x ) ) ) {
fprintf( stderr, "Cell (%d, %d) differs.\n", y, x );
ret = true;
}
}
}
if ( ( fb.ds.get_cursor_row() != other_fb.ds.get_cursor_row() )
|| ( fb.ds.get_cursor_col() != other_fb.ds.get_cursor_col() ) ) {
fprintf( stderr,
"Cursor mismatch: (%d, %d) vs. (%d, %d).\n",
fb.ds.get_cursor_row(),
fb.ds.get_cursor_col(),
other_fb.ds.get_cursor_row(),
other_fb.ds.get_cursor_col() );
ret = true;
}
/* XXX should compare other terminal state too (mouse mode, bell. etc.) */
return ret;
}
| 7,137
|
C++
|
.cc
| 179
| 35.569832
| 110
| 0.658963
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,563
|
compressor.cc
|
mobile-shell_mosh/src/network/compressor.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include <zlib.h>
#include "compressor.h"
#include "src/util/dos_assert.h"
using namespace Network;
std::string Compressor::compress_str( const std::string& input )
{
long unsigned int len = BUFFER_SIZE;
dos_assert( Z_OK
== compress( buffer, &len, reinterpret_cast<const unsigned char*>( input.data() ), input.size() ) );
return std::string( reinterpret_cast<char*>( buffer ), len );
}
std::string Compressor::uncompress_str( const std::string& input )
{
long unsigned int len = BUFFER_SIZE;
dos_assert( Z_OK
== uncompress( buffer, &len, reinterpret_cast<const unsigned char*>( input.data() ), input.size() ) );
return std::string( reinterpret_cast<char*>( buffer ), len );
}
/* construct on first use */
Compressor& Network::get_compressor( void )
{
static Compressor the_compressor;
return the_compressor;
}
| 2,329
|
C++
|
.cc
| 50
| 42.56
| 116
| 0.736772
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,564
|
network.cc
|
mobile-shell_mosh/src/network/network.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include "src/include/config.h"
#include <cassert>
#include <cerrno>
#include <cstring>
#include <sys/socket.h>
#include <sys/types.h>
#ifdef HAVE_SYS_UIO_H
#include <sys/uio.h>
#endif
#include <netdb.h>
#include <netinet/in.h>
#include <unistd.h>
#include "src/crypto/byteorder.h"
#include "src/crypto/crypto.h"
#include "src/network/network.h"
#include "src/util/dos_assert.h"
#include "src/util/fatal_assert.h"
#include "src/util/timestamp.h"
#ifndef MSG_DONTWAIT
#define MSG_DONTWAIT MSG_NONBLOCK
#endif
#ifndef AI_NUMERICSERV
#define AI_NUMERICSERV 0
#endif
using namespace Network;
using namespace Crypto;
const uint64_t DIRECTION_MASK = uint64_t( 1 ) << 63;
const uint64_t SEQUENCE_MASK = uint64_t( -1 ) ^ DIRECTION_MASK;
/* Read in packet */
Packet::Packet( const Message& message )
: seq( message.nonce.val() & SEQUENCE_MASK ),
direction( ( message.nonce.val() & DIRECTION_MASK ) ? TO_CLIENT : TO_SERVER ), timestamp( -1 ),
timestamp_reply( -1 ), payload()
{
dos_assert( message.text.size() >= 2 * sizeof( uint16_t ) );
const uint16_t* data = (uint16_t*)message.text.data();
timestamp = be16toh( data[0] );
timestamp_reply = be16toh( data[1] );
payload = std::string( message.text.begin() + 2 * sizeof( uint16_t ), message.text.end() );
}
/* Output from packet */
Message Packet::toMessage( void )
{
uint64_t direction_seq = ( uint64_t( direction == TO_CLIENT ) << 63 ) | ( seq & SEQUENCE_MASK );
uint16_t ts_net[2]
= { static_cast<uint16_t>( htobe16( timestamp ) ), static_cast<uint16_t>( htobe16( timestamp_reply ) ) };
std::string timestamps = std::string( (char*)ts_net, 2 * sizeof( uint16_t ) );
return Message( Nonce( direction_seq ), timestamps + payload );
}
Packet Connection::new_packet( const std::string& s_payload )
{
uint16_t outgoing_timestamp_reply = -1;
uint64_t now = timestamp();
if ( now - saved_timestamp_received_at < 1000 ) { /* we have a recent received timestamp */
/* send "corrected" timestamp advanced by how long we held it */
outgoing_timestamp_reply = saved_timestamp + ( now - saved_timestamp_received_at );
saved_timestamp = -1;
saved_timestamp_received_at = 0;
}
Packet p( direction, timestamp16(), outgoing_timestamp_reply, s_payload );
return p;
}
void Connection::hop_port( void )
{
assert( !server );
setup();
assert( remote_addr_len != 0 );
socks.push_back( Socket( remote_addr.sa.sa_family ) );
prune_sockets();
}
void Connection::prune_sockets( void )
{
/* don't keep old sockets if the new socket has been working for long enough */
if ( socks.size() > 1 ) {
if ( timestamp() - last_port_choice > MAX_OLD_SOCKET_AGE ) {
int num_to_kill = socks.size() - 1;
for ( int i = 0; i < num_to_kill; i++ ) {
socks.pop_front();
}
}
} else {
return;
}
/* make sure we don't have too many receive sockets open */
if ( socks.size() > MAX_PORTS_OPEN ) {
int num_to_kill = socks.size() - MAX_PORTS_OPEN;
for ( int i = 0; i < num_to_kill; i++ ) {
socks.pop_front();
}
}
}
Connection::Socket::Socket( int family ) : _fd( socket( family, SOCK_DGRAM, 0 ) )
{
if ( _fd < 0 ) {
throw NetworkException( "socket", errno );
}
/* Disable path MTU discovery */
#ifdef HAVE_IP_MTU_DISCOVER
int flag = IP_PMTUDISC_DONT;
if ( setsockopt( _fd, IPPROTO_IP, IP_MTU_DISCOVER, &flag, sizeof flag ) < 0 ) {
throw NetworkException( "setsockopt", errno );
}
#endif
// int dscp = 0x92; /* OS X does not have IPTOS_DSCP_AF42 constant */
int dscp = 0x02; /* ECN-capable transport only */
if ( setsockopt( _fd, IPPROTO_IP, IP_TOS, &dscp, sizeof dscp ) < 0 ) {
// perror( "setsockopt( IP_TOS )" );
}
/* request explicit congestion notification on received datagrams */
#ifdef HAVE_IP_RECVTOS
int tosflag = true;
if ( setsockopt( _fd, IPPROTO_IP, IP_RECVTOS, &tosflag, sizeof tosflag ) < 0
&& family == IPPROTO_IP ) { /* FreeBSD disallows this option on IPv6 sockets. */
perror( "setsockopt( IP_RECVTOS )" );
}
#endif
}
void Connection::setup( void )
{
last_port_choice = timestamp();
}
const std::vector<int> Connection::fds( void ) const
{
std::vector<int> ret;
for ( std::deque<Socket>::const_iterator it = socks.begin(); it != socks.end(); it++ ) {
ret.push_back( it->fd() );
}
return ret;
}
void Connection::set_MTU( int family )
{
switch ( family ) {
case AF_INET:
MTU = DEFAULT_IPV4_MTU - IPV4_HEADER_LEN;
break;
case AF_INET6:
MTU = DEFAULT_IPV6_MTU - IPV6_HEADER_LEN;
break;
default:
throw NetworkException( "Unknown address family", 0 );
}
}
class AddrInfo
{
public:
struct addrinfo* res;
AddrInfo( const char* node, const char* service, const struct addrinfo* hints ) : res( NULL )
{
int errcode = getaddrinfo( node, service, hints, &res );
if ( errcode != 0 ) {
throw NetworkException( std::string( "Bad IP address (" ) + ( node != NULL ? node : "(null)" )
+ "): " + gai_strerror( errcode ),
0 );
}
}
~AddrInfo() { freeaddrinfo( res ); }
private:
AddrInfo( const AddrInfo& );
AddrInfo& operator=( const AddrInfo& );
};
Connection::Connection( const char* desired_ip, const char* desired_port ) /* server */
: socks(), has_remote_addr( false ), remote_addr(), remote_addr_len( 0 ), server( true ), MTU( DEFAULT_SEND_MTU ),
key(), session( key ), direction( TO_CLIENT ), saved_timestamp( -1 ), saved_timestamp_received_at( 0 ),
expected_receiver_seq( 0 ), last_heard( -1 ), last_port_choice( -1 ), last_roundtrip_success( -1 ),
RTT_hit( false ), SRTT( 1000 ), RTTVAR( 500 ), send_error()
{
setup();
/* The mosh wrapper always gives an IP request, in order
to deal with multihomed servers. The port is optional. */
/* If an IP request is given, we try to bind to that IP, but we also
try INADDR_ANY. If a port request is given, we bind only to that port. */
/* convert port numbers */
int desired_port_low = -1;
int desired_port_high = -1;
if ( desired_port && !parse_portrange( desired_port, desired_port_low, desired_port_high ) ) {
throw NetworkException( "Invalid port range", 0 );
}
/* try to bind to desired IP first */
if ( desired_ip ) {
try {
if ( try_bind( desired_ip, desired_port_low, desired_port_high ) ) {
return;
}
} catch ( const NetworkException& e ) {
fprintf( stderr, "Error binding to IP %s: %s\n", desired_ip, e.what() );
}
}
/* now try any local interface */
try {
if ( try_bind( NULL, desired_port_low, desired_port_high ) ) {
return;
}
} catch ( const NetworkException& e ) {
fprintf( stderr, "Error binding to any interface: %s\n", e.what() );
throw; /* this time it's fatal */
}
throw NetworkException( "Could not bind", errno );
}
bool Connection::try_bind( const char* addr, int port_low, int port_high )
{
struct addrinfo hints;
memset( &hints, 0, sizeof( hints ) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST | AI_NUMERICSERV;
AddrInfo ai( addr, "0", &hints );
Addr local_addr;
socklen_t local_addr_len = ai.res->ai_addrlen;
memcpy( &local_addr.sa, ai.res->ai_addr, local_addr_len );
int search_low = PORT_RANGE_LOW, search_high = PORT_RANGE_HIGH;
if ( port_low != -1 ) { /* low port preference */
search_low = port_low;
}
if ( port_high != -1 ) { /* high port preference */
search_high = port_high;
}
socks.push_back( Socket( local_addr.sa.sa_family ) );
for ( int i = search_low; i <= search_high; i++ ) {
switch ( local_addr.sa.sa_family ) {
case AF_INET:
local_addr.sin.sin_port = htons( i );
break;
case AF_INET6:
local_addr.sin6.sin6_port = htons( i );
break;
default:
throw NetworkException( "Unknown address family", 0 );
}
if ( local_addr.sa.sa_family == AF_INET6
&& memcmp( &local_addr.sin6.sin6_addr, &in6addr_any, sizeof( in6addr_any ) ) == 0 ) {
const int off = 0;
if ( setsockopt( sock(), IPPROTO_IPV6, IPV6_V6ONLY, &off, sizeof( off ) ) ) {
perror( "setsockopt( IPV6_V6ONLY, off )" );
}
}
if ( ::bind( sock(), &local_addr.sa, local_addr_len ) == 0 ) {
set_MTU( local_addr.sa.sa_family );
return true;
} // else fallthrough to below code, on last iteration.
}
int saved_errno = errno;
socks.pop_back();
char host[NI_MAXHOST], serv[NI_MAXSERV];
int errcode = getnameinfo( &local_addr.sa,
local_addr_len,
host,
sizeof( host ),
serv,
sizeof( serv ),
NI_DGRAM | NI_NUMERICHOST | NI_NUMERICSERV );
if ( errcode != 0 ) {
throw NetworkException( std::string( "bind: getnameinfo: " ) + gai_strerror( errcode ), 0 );
}
fprintf( stderr, "Failed binding to %s:%s\n", host, serv );
throw NetworkException( "bind", saved_errno );
}
Connection::Connection( const char* key_str, const char* ip, const char* port ) /* client */
: socks(), has_remote_addr( false ), remote_addr(), remote_addr_len( 0 ), server( false ),
MTU( DEFAULT_SEND_MTU ), key( key_str ), session( key ), direction( TO_SERVER ), saved_timestamp( -1 ),
saved_timestamp_received_at( 0 ), expected_receiver_seq( 0 ), last_heard( -1 ), last_port_choice( -1 ),
last_roundtrip_success( -1 ), RTT_hit( false ), SRTT( 1000 ), RTTVAR( 500 ), send_error()
{
setup();
/* associate socket with remote host and port */
struct addrinfo hints;
memset( &hints, 0, sizeof( hints ) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV;
AddrInfo ai( ip, port, &hints );
fatal_assert( static_cast<size_t>( ai.res->ai_addrlen ) <= sizeof( remote_addr ) );
remote_addr_len = ai.res->ai_addrlen;
memcpy( &remote_addr.sa, ai.res->ai_addr, remote_addr_len );
has_remote_addr = true;
socks.push_back( Socket( remote_addr.sa.sa_family ) );
set_MTU( remote_addr.sa.sa_family );
}
void Connection::send( const std::string& s )
{
if ( !has_remote_addr ) {
return;
}
Packet px = new_packet( s );
std::string p = session.encrypt( px.toMessage() );
ssize_t bytes_sent = sendto( sock(), p.data(), p.size(), MSG_DONTWAIT, &remote_addr.sa, remote_addr_len );
if ( bytes_sent != static_cast<ssize_t>( p.size() ) ) {
/* Make sendto() failure available to the frontend. */
send_error = "sendto: ";
send_error += strerror( errno );
if ( errno == EMSGSIZE ) {
MTU = DEFAULT_SEND_MTU; /* payload MTU of last resort */
}
}
uint64_t now = timestamp();
if ( server ) {
if ( now - last_heard > SERVER_ASSOCIATION_TIMEOUT ) {
has_remote_addr = false;
fprintf( stderr, "Server now detached from client.\n" );
}
} else { /* client */
if ( ( now - last_port_choice > PORT_HOP_INTERVAL ) && ( now - last_roundtrip_success > PORT_HOP_INTERVAL ) ) {
hop_port();
}
}
}
std::string Connection::recv( void )
{
assert( !socks.empty() );
for ( std::deque<Socket>::const_iterator it = socks.begin(); it != socks.end(); it++ ) {
std::string payload;
try {
payload = recv_one( it->fd() );
} catch ( NetworkException& e ) {
if ( ( e.the_errno == EAGAIN ) || ( e.the_errno == EWOULDBLOCK ) ) {
continue;
} else {
throw;
}
}
/* succeeded */
prune_sockets();
return payload;
}
throw NetworkException( "No packet received" );
}
std::string Connection::recv_one( int sock_to_recv )
{
/* receive source address, ECN, and payload in msghdr structure */
Addr packet_remote_addr;
struct msghdr header;
struct iovec msg_iovec;
char msg_payload[Session::RECEIVE_MTU];
char msg_control[Session::RECEIVE_MTU];
/* receive source address */
header.msg_name = &packet_remote_addr;
header.msg_namelen = sizeof packet_remote_addr;
/* receive payload */
msg_iovec.iov_base = msg_payload;
msg_iovec.iov_len = sizeof msg_payload;
header.msg_iov = &msg_iovec;
header.msg_iovlen = 1;
/* receive explicit congestion notification */
header.msg_control = msg_control;
header.msg_controllen = sizeof msg_control;
/* receive flags */
header.msg_flags = 0;
ssize_t received_len = recvmsg( sock_to_recv, &header, MSG_DONTWAIT );
if ( received_len < 0 ) {
throw NetworkException( "recvmsg", errno );
}
if ( header.msg_flags & MSG_TRUNC ) {
throw NetworkException( "Received oversize datagram", errno );
}
/* receive ECN */
bool congestion_experienced = false;
struct cmsghdr* ecn_hdr = CMSG_FIRSTHDR( &header );
if ( ecn_hdr && ecn_hdr->cmsg_level == IPPROTO_IP
&& ( ecn_hdr->cmsg_type == IP_TOS
#ifdef IP_RECVTOS
|| ecn_hdr->cmsg_type == IP_RECVTOS
#endif
) ) {
/* got one */
uint8_t* ecn_octet_p = (uint8_t*)CMSG_DATA( ecn_hdr );
assert( ecn_octet_p );
congestion_experienced = ( *ecn_octet_p & 0x03 ) == 0x03;
}
Packet p( session.decrypt( msg_payload, received_len ) );
dos_assert( p.direction == ( server ? TO_SERVER : TO_CLIENT ) ); /* prevent malicious playback to sender */
if ( p.seq
< expected_receiver_seq ) { /* don't use (but do return) out-of-order packets for timestamp or targeting */
return p.payload;
}
expected_receiver_seq = p.seq + 1; /* this is security-sensitive because a replay attack could otherwise
screw up the timestamp and targeting */
if ( p.timestamp != uint16_t( -1 ) ) {
saved_timestamp = p.timestamp;
saved_timestamp_received_at = timestamp();
if ( congestion_experienced ) {
/* signal counterparty to slow down */
/* this will gradually slow the counterparty down to the minimum frame rate */
saved_timestamp -= CONGESTION_TIMESTAMP_PENALTY;
if ( server ) {
fprintf( stderr, "Received explicit congestion notification.\n" );
}
}
}
if ( p.timestamp_reply != uint16_t( -1 ) ) {
uint16_t now = timestamp16();
double R = timestamp_diff( now, p.timestamp_reply );
if ( R < 5000 ) { /* ignore large values, e.g. server was Ctrl-Zed */
if ( !RTT_hit ) { /* first measurement */
SRTT = R;
RTTVAR = R / 2;
RTT_hit = true;
} else {
const double alpha = 1.0 / 8.0;
const double beta = 1.0 / 4.0;
RTTVAR = ( 1 - beta ) * RTTVAR + ( beta * fabs( SRTT - R ) );
SRTT = ( 1 - alpha ) * SRTT + ( alpha * R );
}
}
}
/* auto-adjust to remote host */
has_remote_addr = true;
last_heard = timestamp();
if ( server && /* only client can roam */
( remote_addr_len != header.msg_namelen
|| memcmp( &remote_addr, &packet_remote_addr, remote_addr_len ) != 0 ) ) {
remote_addr = packet_remote_addr;
remote_addr_len = header.msg_namelen;
char host[NI_MAXHOST], serv[NI_MAXSERV];
int errcode = getnameinfo( &remote_addr.sa,
remote_addr_len,
host,
sizeof( host ),
serv,
sizeof( serv ),
NI_DGRAM | NI_NUMERICHOST | NI_NUMERICSERV );
if ( errcode != 0 ) {
throw NetworkException( std::string( "recv_one: getnameinfo: " ) + gai_strerror( errcode ), 0 );
}
fprintf( stderr, "Server now attached to client at %s:%s\n", host, serv );
}
return p.payload;
}
std::string Connection::port( void ) const
{
Addr local_addr;
socklen_t addrlen = sizeof( local_addr );
if ( getsockname( sock(), &local_addr.sa, &addrlen ) < 0 ) {
throw NetworkException( "getsockname", errno );
}
char serv[NI_MAXSERV];
int errcode = getnameinfo( &local_addr.sa, addrlen, NULL, 0, serv, sizeof( serv ), NI_DGRAM | NI_NUMERICSERV );
if ( errcode != 0 ) {
throw NetworkException( std::string( "port: getnameinfo: " ) + gai_strerror( errcode ), 0 );
}
return std::string( serv );
}
uint64_t Network::timestamp( void )
{
return frozen_timestamp();
}
uint16_t Network::timestamp16( void )
{
uint16_t ts = timestamp() % 65536;
if ( ts == uint16_t( -1 ) ) {
ts++;
}
return ts;
}
uint16_t Network::timestamp_diff( uint16_t tsnew, uint16_t tsold )
{
int diff = tsnew - tsold;
if ( diff < 0 ) {
diff += 65536;
}
assert( diff >= 0 );
assert( diff <= 65535 );
return diff;
}
uint64_t Connection::timeout( void ) const
{
uint64_t RTO = lrint( ceil( SRTT + 4 * RTTVAR ) );
if ( RTO < MIN_RTO ) {
RTO = MIN_RTO;
} else if ( RTO > MAX_RTO ) {
RTO = MAX_RTO;
}
return RTO;
}
Connection::Socket::~Socket()
{
fatal_assert( close( _fd ) == 0 );
}
Connection::Socket::Socket( const Socket& other ) : _fd( dup( other._fd ) )
{
if ( _fd < 0 ) {
throw NetworkException( "socket", errno );
}
}
Connection::Socket& Connection::Socket::operator=( const Socket& other )
{
if ( dup2( other._fd, _fd ) < 0 ) {
throw NetworkException( "socket", errno );
}
return *this;
}
bool Connection::parse_portrange( const char* desired_port, int& desired_port_low, int& desired_port_high )
{
/* parse "port" or "portlow:porthigh" */
desired_port_low = desired_port_high = 0;
char* end;
long value;
/* parse first (only?) port */
errno = 0;
value = strtol( desired_port, &end, 10 );
if ( ( errno != 0 ) || ( *end != '\0' && *end != ':' ) ) {
fprintf( stderr, "Invalid (low) port number (%s)\n", desired_port );
return false;
}
if ( ( value < 0 ) || ( value > 65535 ) ) {
fprintf( stderr, "(Low) port number %ld outside valid range [0..65535]\n", value );
return false;
}
desired_port_low = (int)value;
if ( *end == '\0' ) { /* not a port range */
desired_port_high = desired_port_low;
return true;
}
/* port range; parse high port */
const char* cp = end + 1;
errno = 0;
value = strtol( cp, &end, 10 );
if ( ( errno != 0 ) || ( *end != '\0' ) ) {
fprintf( stderr, "Invalid high port number (%s)\n", cp );
return false;
}
if ( ( value < 0 ) || ( value > 65535 ) ) {
fprintf( stderr, "High port number %ld outside valid range [0..65535]\n", value );
return false;
}
desired_port_high = (int)value;
if ( desired_port_low > desired_port_high ) {
fprintf( stderr, "Low port %d greater than high port %d\n", desired_port_low, desired_port_high );
return false;
}
if ( desired_port_low == 0 ) {
fprintf( stderr, "Low port 0 incompatible with port ranges\n" );
return false;
}
return true;
}
| 20,258
|
C++
|
.cc
| 560
| 31.5625
| 116
| 0.630278
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,565
|
transportfragment.cc
|
mobile-shell_mosh/src/network/transportfragment.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include <cassert>
#include "compressor.h"
#include "src/crypto/byteorder.h"
#include "src/protobufs/transportinstruction.pb.h"
#include "src/util/fatal_assert.h"
#include "transportfragment.h"
using namespace Network;
using namespace TransportBuffers;
static std::string network_order_string( uint16_t host_order )
{
uint16_t net_int = htobe16( host_order );
return std::string( (char*)&net_int, sizeof( net_int ) );
}
static std::string network_order_string( uint64_t host_order )
{
uint64_t net_int = htobe64( host_order );
return std::string( (char*)&net_int, sizeof( net_int ) );
}
std::string Fragment::tostring( void )
{
assert( initialized );
std::string ret;
ret += network_order_string( id );
fatal_assert(
!( fragment_num & 0x8000 ) ); /* effective limit on size of a terminal screen change or buffered user input */
uint16_t combined_fragment_num = ( final << 15 ) | fragment_num;
ret += network_order_string( combined_fragment_num );
assert( ret.size() == frag_header_len );
ret += contents;
return ret;
}
Fragment::Fragment( const std::string& x )
: id( -1 ), fragment_num( -1 ), final( false ), initialized( true ), contents()
{
fatal_assert( x.size() >= frag_header_len );
contents = std::string( x.begin() + frag_header_len, x.end() );
uint64_t data64;
uint16_t* data16 = (uint16_t*)x.data();
memcpy( &data64, x.data(), sizeof( data64 ) );
id = be64toh( data64 );
fragment_num = be16toh( data16[4] );
final = ( fragment_num & 0x8000 ) >> 15;
fragment_num &= 0x7FFF;
}
bool FragmentAssembly::add_fragment( Fragment& frag )
{
/* see if this is a totally new packet */
if ( current_id != frag.id ) {
fragments.clear();
fragments.resize( frag.fragment_num + 1 );
fragments.at( frag.fragment_num ) = frag;
fragments_arrived = 1;
fragments_total = -1; /* unknown */
current_id = frag.id;
} else { /* not a new packet */
/* see if we already have this fragment */
if ( ( fragments.size() > frag.fragment_num ) && ( fragments.at( frag.fragment_num ).initialized ) ) {
/* make sure new version is same as what we already have */
assert( fragments.at( frag.fragment_num ) == frag );
} else {
if ( (int)fragments.size() < frag.fragment_num + 1 ) {
fragments.resize( frag.fragment_num + 1 );
}
fragments.at( frag.fragment_num ) = frag;
fragments_arrived++;
}
}
if ( frag.final ) {
fragments_total = frag.fragment_num + 1;
assert( (int)fragments.size() <= fragments_total );
fragments.resize( fragments_total );
}
if ( fragments_total != -1 ) {
assert( fragments_arrived <= fragments_total );
}
/* see if we're done */
return fragments_arrived == fragments_total;
}
Instruction FragmentAssembly::get_assembly( void )
{
assert( fragments_arrived == fragments_total );
std::string encoded;
for ( int i = 0; i < fragments_total; i++ ) {
assert( fragments.at( i ).initialized );
encoded += fragments.at( i ).contents;
}
Instruction ret;
fatal_assert( ret.ParseFromString( get_compressor().uncompress_str( encoded ) ) );
fragments.clear();
fragments_arrived = 0;
fragments_total = -1;
return ret;
}
bool Fragment::operator==( const Fragment& x ) const
{
return ( id == x.id ) && ( fragment_num == x.fragment_num ) && ( final == x.final )
&& ( initialized == x.initialized ) && ( contents == x.contents );
}
std::vector<Fragment> Fragmenter::make_fragments( const Instruction& inst, size_t MTU )
{
MTU -= Fragment::frag_header_len;
if ( ( inst.old_num() != last_instruction.old_num() ) || ( inst.new_num() != last_instruction.new_num() )
|| ( inst.ack_num() != last_instruction.ack_num() )
|| ( inst.throwaway_num() != last_instruction.throwaway_num() )
|| ( inst.chaff() != last_instruction.chaff() )
|| ( inst.protocol_version() != last_instruction.protocol_version() ) || ( last_MTU != MTU ) ) {
next_instruction_id++;
}
if ( ( inst.old_num() == last_instruction.old_num() ) && ( inst.new_num() == last_instruction.new_num() ) ) {
assert( inst.diff() == last_instruction.diff() );
}
last_instruction = inst;
last_MTU = MTU;
std::string payload = get_compressor().compress_str( inst.SerializeAsString() );
uint16_t fragment_num = 0;
std::vector<Fragment> ret;
while ( !payload.empty() ) {
std::string this_fragment;
bool final = false;
if ( payload.size() > MTU ) {
this_fragment = std::string( payload.begin(), payload.begin() + MTU );
payload = std::string( payload.begin() + MTU, payload.end() );
} else {
this_fragment = payload;
payload.clear();
final = true;
}
ret.push_back( Fragment( next_instruction_id, fragment_num++, final, this_fragment ) );
}
return ret;
}
| 6,298
|
C++
|
.cc
| 157
| 36.191083
| 114
| 0.674914
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,566
|
stmclient.cc
|
mobile-shell_mosh/src/frontend/stmclient.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include "src/include/config.h"
#include <cerrno>
#include <clocale>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <err.h>
#include <pwd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <unistd.h>
#if HAVE_PTY_H
#include <pty.h>
#elif HAVE_UTIL_H
#include <util.h>
#endif
#include "src/statesync/completeterminal.h"
#include "src/statesync/user.h"
#include "src/util/fatal_assert.h"
#include "src/util/locale_utils.h"
#include "src/util/pty_compat.h"
#include "src/util/select.h"
#include "src/util/swrite.h"
#include "src/util/timestamp.h"
#include "stmclient.h"
#include "src/network/networktransport-impl.h"
void STMClient::resume( void )
{
/* Restore termios state */
if ( tcsetattr( STDIN_FILENO, TCSANOW, &raw_termios ) < 0 ) {
perror( "tcsetattr" );
exit( 1 );
}
/* Put terminal in application-cursor-key mode */
swrite( STDOUT_FILENO, display.open().c_str() );
/* Flag that outer terminal state is unknown */
repaint_requested = true;
}
void STMClient::init( void )
{
if ( !is_utf8_locale() ) {
LocaleVar native_ctype = get_ctype();
std::string native_charset( locale_charset() );
fprintf( stderr,
"mosh-client needs a UTF-8 native locale to run.\n\n"
"Unfortunately, the client's environment (%s) specifies\n"
"the character set \"%s\".\n\n",
native_ctype.str().c_str(),
native_charset.c_str() );
int unused __attribute( ( unused ) ) = system( "locale" );
exit( 1 );
}
/* Verify terminal configuration */
if ( tcgetattr( STDIN_FILENO, &saved_termios ) < 0 ) {
perror( "tcgetattr" );
exit( 1 );
}
/* Put terminal driver in raw mode */
raw_termios = saved_termios;
#ifdef HAVE_IUTF8
if ( !( raw_termios.c_iflag & IUTF8 ) ) {
// fprintf( stderr, "Warning: Locale is UTF-8 but termios IUTF8 flag not set. Setting IUTF8 flag.\n" );
/* Probably not really necessary since we are putting terminal driver into raw mode anyway. */
raw_termios.c_iflag |= IUTF8;
}
#endif /* HAVE_IUTF8 */
cfmakeraw( &raw_termios );
if ( tcsetattr( STDIN_FILENO, TCSANOW, &raw_termios ) < 0 ) {
perror( "tcsetattr" );
exit( 1 );
}
/* Put terminal in application-cursor-key mode */
swrite( STDOUT_FILENO, display.open().c_str() );
/* Add our name to window title */
if ( !getenv( "MOSH_TITLE_NOPREFIX" ) ) {
overlays.set_title_prefix( std::wstring( L"[mosh] " ) );
}
/* Set terminal escape key. */
const char* escape_key_env;
if ( ( escape_key_env = getenv( "MOSH_ESCAPE_KEY" ) ) != NULL ) {
if ( strlen( escape_key_env ) == 1 ) {
escape_key = (int)escape_key_env[0];
if ( escape_key > 0 && escape_key < 128 ) {
if ( escape_key < 32 ) {
/* If escape is ctrl-something, pass it with repeating the key without ctrl. */
escape_pass_key = escape_key + (int)'@';
} else {
/* If escape is something else, pass it with repeating the key itself. */
escape_pass_key = escape_key;
}
if ( escape_pass_key >= 'A' && escape_pass_key <= 'Z' ) {
/* If escape pass is an upper case character, define optional version
as lower case of the same. */
escape_pass_key2 = escape_pass_key + (int)'a' - (int)'A';
} else {
escape_pass_key2 = escape_pass_key;
}
} else {
escape_key = 0x1E;
escape_pass_key = '^';
escape_pass_key2 = '^';
}
} else if ( strlen( escape_key_env ) == 0 ) {
escape_key = -1;
} else {
escape_key = 0x1E;
escape_pass_key = '^';
escape_pass_key2 = '^';
}
} else {
escape_key = 0x1E;
escape_pass_key = '^';
escape_pass_key2 = '^';
}
/* There are so many better ways to shoot oneself into leg than
setting escape key to Ctrl-C, Ctrl-D, NewLine, Ctrl-L or CarriageReturn
that we just won't allow that. */
if ( escape_key == 0x03 || escape_key == 0x04 || escape_key == 0x0A || escape_key == 0x0C
|| escape_key == 0x0D ) {
escape_key = 0x1E;
escape_pass_key = '^';
escape_pass_key2 = '^';
}
/* Adjust escape help differently if escape is a control character. */
if ( escape_key > 0 ) {
char escape_pass_name_buf[16];
char escape_key_name_buf[16];
snprintf( escape_pass_name_buf, sizeof escape_pass_name_buf, "\"%c\"", escape_pass_key );
if ( escape_key < 32 ) {
snprintf( escape_key_name_buf, sizeof escape_key_name_buf, "Ctrl-%c", escape_pass_key );
escape_requires_lf = false;
} else {
snprintf( escape_key_name_buf, sizeof escape_key_name_buf, "\"%c\"", escape_key );
escape_requires_lf = true;
}
std::string tmp;
tmp = std::string( escape_pass_name_buf );
std::wstring escape_pass_name = std::wstring( tmp.begin(), tmp.end() );
tmp = std::string( escape_key_name_buf );
std::wstring escape_key_name = std::wstring( tmp.begin(), tmp.end() );
escape_key_help
= L"Commands: Ctrl-Z suspends, \".\" quits, " + escape_pass_name + L" gives literal " + escape_key_name;
overlays.get_notification_engine().set_escape_key_string( tmp );
}
wchar_t tmp[128];
swprintf( tmp, 128, L"Nothing received from server on UDP port %s.", port.c_str() );
connecting_notification = std::wstring( tmp );
}
void STMClient::shutdown( void )
{
/* Restore screen state */
overlays.get_notification_engine().set_notification_string( std::wstring( L"" ) );
overlays.get_notification_engine().server_heard( timestamp() );
overlays.set_title_prefix( std::wstring( L"" ) );
output_new_frame();
/* Restore terminal and terminal-driver state */
swrite( STDOUT_FILENO, display.close().c_str() );
if ( tcsetattr( STDIN_FILENO, TCSANOW, &saved_termios ) < 0 ) {
perror( "tcsetattr" );
exit( 1 );
}
if ( still_connecting() ) {
fprintf( stderr,
"\nmosh did not make a successful connection to %s:%s.\n"
"Please verify that UDP port %s is not firewalled and can reach the server.\n\n"
"(By default, mosh uses a UDP port between 60000 and 61000. The -p option\n"
"selects a specific UDP port number.)\n",
ip.c_str(),
port.c_str(),
port.c_str() );
} else if ( network && !clean_shutdown ) {
fputs( "\n\nmosh did not shut down cleanly. Please note that the\n"
"mosh-server process may still be running on the server.\n",
stderr );
}
}
void STMClient::main_init( void )
{
Select& sel = Select::get_instance();
sel.add_signal( SIGWINCH );
sel.add_signal( SIGTERM );
sel.add_signal( SIGINT );
sel.add_signal( SIGHUP );
sel.add_signal( SIGPIPE );
sel.add_signal( SIGCONT );
/* get initial window size */
if ( ioctl( STDIN_FILENO, TIOCGWINSZ, &window_size ) < 0 ) {
perror( "ioctl TIOCGWINSZ" );
return;
}
/* local state */
local_framebuffer = Terminal::Framebuffer( window_size.ws_col, window_size.ws_row );
new_state = Terminal::Framebuffer( 1, 1 );
/* initialize screen */
std::string init = display.new_frame( false, local_framebuffer, local_framebuffer );
swrite( STDOUT_FILENO, init.data(), init.size() );
/* open network */
Network::UserStream blank;
Terminal::Complete local_terminal( window_size.ws_col, window_size.ws_row );
network = NetworkPointer( new NetworkType( blank, local_terminal, key.c_str(), ip.c_str(), port.c_str() ) );
network->set_send_delay( 1 ); /* minimal delay on outgoing keystrokes */
/* tell server the size of the terminal */
network->get_current_state().push_back( Parser::Resize( window_size.ws_col, window_size.ws_row ) );
/* be noisy as necessary */
network->set_verbose( verbose );
Select::set_verbose( verbose );
}
void STMClient::output_new_frame( void )
{
if ( !network ) { /* clean shutdown even when not initialized */
return;
}
/* fetch target state */
new_state = network->get_latest_remote_state().state.get_fb();
/* apply local overlays */
overlays.apply( new_state );
/* calculate minimal difference from where we are */
const std::string diff( display.new_frame( !repaint_requested, local_framebuffer, new_state ) );
swrite( STDOUT_FILENO, diff.data(), diff.size() );
repaint_requested = false;
local_framebuffer = new_state;
}
void STMClient::process_network_input( void )
{
network->recv();
/* Now give hints to the overlays */
overlays.get_notification_engine().server_heard( network->get_latest_remote_state().timestamp );
overlays.get_notification_engine().server_acked( network->get_sent_state_acked_timestamp() );
overlays.get_prediction_engine().set_local_frame_acked( network->get_sent_state_acked() );
overlays.get_prediction_engine().set_send_interval( network->send_interval() );
overlays.get_prediction_engine().set_local_frame_late_acked(
network->get_latest_remote_state().state.get_echo_ack() );
}
bool STMClient::process_user_input( int fd )
{
const int buf_size = 16384;
char buf[buf_size];
/* fill buffer if possible */
ssize_t bytes_read = read( fd, buf, buf_size );
if ( bytes_read == 0 ) { /* EOF */
return false;
} else if ( bytes_read < 0 ) {
perror( "read" );
return false;
}
NetworkType& net = *network;
if ( net.shutdown_in_progress() ) {
return true;
}
overlays.get_prediction_engine().set_local_frame_sent( net.get_sent_state_last() );
/* Don't predict for bulk data. */
bool paste = bytes_read > 100;
if ( paste ) {
overlays.get_prediction_engine().reset();
}
for ( int i = 0; i < bytes_read; i++ ) {
char the_byte = buf[i];
if ( !paste ) {
overlays.get_prediction_engine().new_user_byte( the_byte, local_framebuffer );
}
if ( quit_sequence_started ) {
if ( the_byte == '.' ) { /* Quit sequence is Ctrl-^ . */
if ( net.has_remote_addr() && ( !net.shutdown_in_progress() ) ) {
overlays.get_notification_engine().set_notification_string( std::wstring( L"Exiting on user request..." ),
true );
net.start_shutdown();
return true;
}
return false;
} else if ( the_byte == 0x1a ) { /* Suspend sequence is escape_key Ctrl-Z */
/* Restore terminal and terminal-driver state */
swrite( STDOUT_FILENO, display.close().c_str() );
if ( tcsetattr( STDIN_FILENO, TCSANOW, &saved_termios ) < 0 ) {
perror( "tcsetattr" );
exit( 1 );
}
fputs( "\n\033[37;44m[mosh is suspended.]\033[m\n", stdout );
fflush( NULL );
/* actually suspend */
kill( 0, SIGSTOP );
resume();
} else if ( ( the_byte == escape_pass_key ) || ( the_byte == escape_pass_key2 ) ) {
/* Emulation sequence to type escape_key is escape_key +
escape_pass_key (that is escape key without Ctrl) */
net.get_current_state().push_back( Parser::UserByte( escape_key ) );
} else {
/* Escape key followed by anything other than . and ^ gets sent literally */
net.get_current_state().push_back( Parser::UserByte( escape_key ) );
net.get_current_state().push_back( Parser::UserByte( the_byte ) );
}
quit_sequence_started = false;
if ( overlays.get_notification_engine().get_notification_string() == escape_key_help ) {
overlays.get_notification_engine().set_notification_string( L"" );
}
continue;
}
quit_sequence_started
= ( escape_key > 0 ) && ( the_byte == escape_key ) && ( lf_entered || ( !escape_requires_lf ) );
if ( quit_sequence_started ) {
lf_entered = false;
overlays.get_notification_engine().set_notification_string( escape_key_help, true, false );
continue;
}
lf_entered = ( ( the_byte == 0x0A )
|| ( the_byte == 0x0D ) ); /* LineFeed, Ctrl-J, '\n' or CarriageReturn, Ctrl-M, '\r' */
if ( the_byte == 0x0C ) { /* Ctrl-L */
repaint_requested = true;
}
net.get_current_state().push_back( Parser::UserByte( the_byte ) );
}
return true;
}
bool STMClient::process_resize( void )
{
/* get new size */
if ( ioctl( STDIN_FILENO, TIOCGWINSZ, &window_size ) < 0 ) {
perror( "ioctl TIOCGWINSZ" );
return false;
}
/* tell remote emulator */
Parser::Resize res( window_size.ws_col, window_size.ws_row );
if ( !network->shutdown_in_progress() ) {
network->get_current_state().push_back( res );
}
/* note remote emulator will probably reply with its own Resize to adjust our state */
/* tell prediction engine */
overlays.get_prediction_engine().reset();
return true;
}
bool STMClient::main( void )
{
/* initialize signal handling and structures */
main_init();
/* Drop unnecessary privileges */
#ifdef HAVE_PLEDGE
/* OpenBSD pledge() syscall */
if ( pledge( "stdio inet tty", NULL ) ) {
perror( "pledge() failed" );
exit( 1 );
}
#endif
/* prepare to poll for events */
Select& sel = Select::get_instance();
while ( 1 ) {
try {
output_new_frame();
int wait_time = std::min( network->wait_time(), overlays.wait_time() );
/* Handle startup "Connecting..." message */
if ( still_connecting() ) {
wait_time = std::min( 250, wait_time );
}
/* poll for events */
/* network->fd() can in theory change over time */
sel.clear_fds();
std::vector<int> fd_list( network->fds() );
for ( std::vector<int>::const_iterator it = fd_list.begin(); it != fd_list.end(); it++ ) {
sel.add_fd( *it );
}
sel.add_fd( STDIN_FILENO );
int active_fds = sel.select( wait_time );
if ( active_fds < 0 ) {
perror( "select" );
break;
}
bool network_ready_to_read = false;
for ( std::vector<int>::const_iterator it = fd_list.begin(); it != fd_list.end(); it++ ) {
if ( sel.read( *it ) ) {
/* packet received from the network */
/* we only read one socket each run */
network_ready_to_read = true;
}
}
if ( network_ready_to_read ) {
process_network_input();
}
if ( sel.read( STDIN_FILENO )
&& !process_user_input( STDIN_FILENO ) ) { /* input from the user needs to be fed to the network */
if ( !network->has_remote_addr() ) {
break;
} else if ( !network->shutdown_in_progress() ) {
overlays.get_notification_engine().set_notification_string( std::wstring( L"Exiting..." ), true );
network->start_shutdown();
}
}
if ( sel.signal( SIGWINCH ) && !process_resize() ) { /* resize */
return false;
}
if ( sel.signal( SIGCONT ) ) {
resume();
}
if ( sel.signal( SIGTERM ) || sel.signal( SIGINT ) || sel.signal( SIGHUP ) || sel.signal( SIGPIPE ) ) {
/* shutdown signal */
if ( !network->has_remote_addr() ) {
break;
} else if ( !network->shutdown_in_progress() ) {
overlays.get_notification_engine().set_notification_string(
std::wstring( L"Signal received, shutting down..." ), true );
network->start_shutdown();
}
}
/* quit if our shutdown has been acknowledged */
if ( network->shutdown_in_progress() && network->shutdown_acknowledged() ) {
clean_shutdown = true;
break;
}
/* quit after shutdown acknowledgement timeout */
if ( network->shutdown_in_progress() && network->shutdown_ack_timed_out() ) {
break;
}
/* quit if we received and acknowledged a shutdown request */
if ( network->counterparty_shutdown_ack_sent() ) {
clean_shutdown = true;
break;
}
/* write diagnostic message if can't reach server */
if ( still_connecting() && ( !network->shutdown_in_progress() )
&& ( timestamp() - network->get_latest_remote_state().timestamp > 250 ) ) {
if ( timestamp() - network->get_latest_remote_state().timestamp > 15000 ) {
if ( !network->shutdown_in_progress() ) {
overlays.get_notification_engine().set_notification_string(
std::wstring( L"Timed out waiting for server..." ), true );
network->start_shutdown();
}
} else {
overlays.get_notification_engine().set_notification_string( connecting_notification );
}
} else if ( ( network->get_remote_state_num() != 0 )
&& ( overlays.get_notification_engine().get_notification_string() == connecting_notification ) ) {
overlays.get_notification_engine().set_notification_string( L"" );
}
network->tick();
std::string& send_error = network->get_send_error();
if ( !send_error.empty() ) {
overlays.get_notification_engine().set_network_error( send_error );
send_error.clear();
} else {
overlays.get_notification_engine().clear_network_error();
}
} catch ( const Network::NetworkException& e ) {
if ( !network->shutdown_in_progress() ) {
overlays.get_notification_engine().set_network_error( e.what() );
}
struct timespec req;
req.tv_sec = 0;
req.tv_nsec = 200000000; /* 0.2 sec */
nanosleep( &req, NULL );
freeze_timestamp();
} catch ( const Crypto::CryptoException& e ) {
if ( e.fatal ) {
throw;
} else {
wchar_t tmp[128];
swprintf( tmp, 128, L"Crypto exception: %s", e.what() );
overlays.get_notification_engine().set_notification_string( std::wstring( tmp ) );
}
}
}
return clean_shutdown;
}
| 19,248
|
C++
|
.cc
| 487
| 33.657084
| 116
| 0.62277
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,567
|
mosh-server.cc
|
mobile-shell_mosh/src/frontend/mosh-server.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include "src/include/config.h"
#include "src/include/version.h"
#include <cerrno>
#include <clocale>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <sstream>
#include <typeinfo>
#include <err.h>
#include <fcntl.h>
#include <inttypes.h>
#include <netdb.h>
#include <pwd.h>
#include <strings.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <termios.h>
#include <unistd.h>
#ifdef HAVE_UTEMPTER
#include <utempter.h>
#endif
#ifdef HAVE_SYSLOG
#include <syslog.h>
#endif
#ifdef HAVE_UTMPX_H
#include <utmpx.h>
#endif
#ifdef HAVE_PATHS_H
#include <paths.h>
#endif
#if HAVE_PTY_H
#include <pty.h>
#elif HAVE_UTIL_H
#include <util.h>
#endif
#if FORKPTY_IN_LIBUTIL
#include <libutil.h>
#endif
#include "src/statesync/completeterminal.h"
#include "src/statesync/user.h"
#include "src/util/fatal_assert.h"
#include "src/util/locale_utils.h"
#include "src/util/pty_compat.h"
#include "src/util/select.h"
#include "src/util/swrite.h"
#include "src/util/timestamp.h"
#ifndef _PATH_BSHELL
#define _PATH_BSHELL "/bin/sh"
#endif
#include "src/network/networktransport-impl.h"
using ServerConnection = Network::Transport<Terminal::Complete, Network::UserStream>;
static void serve( int host_fd,
int pipe_fd,
Terminal::Complete& terminal,
ServerConnection& network,
long network_timeout,
long network_signaled_timeout );
static int run_server( const char* desired_ip,
const char* desired_port,
const std::string& command_path,
char* command_argv[],
const int colors,
unsigned int verbose,
bool with_motd );
static void print_version( FILE* file )
{
fputs( "mosh-server (" PACKAGE_STRING ") [build " BUILD_VERSION "]\n"
"Copyright 2012 Keith Winstein <mosh-devel@mit.edu>\n"
"License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n"
"This is free software: you are free to change and redistribute it.\n"
"There is NO WARRANTY, to the extent permitted by law.\n",
file );
}
static void print_usage( FILE* stream, const char* argv0 )
{
fprintf( stream,
"Usage: %s new [-s] [-v] [-i LOCALADDR] [-p PORT[:PORT2]] [-c COLORS] [-l NAME=VALUE] [-- COMMAND...]\n",
argv0 );
}
static bool print_motd( const char* filename );
static void chdir_homedir( void );
static bool motd_hushed( void );
static void warn_unattached( const std::string& ignore_entry );
/* Simple spinloop */
static void spin( void )
{
static unsigned int spincount = 0;
spincount++;
if ( spincount > 10 ) {
struct timespec req;
req.tv_sec = 0;
req.tv_nsec = 100000000; /* 0.1 sec */
nanosleep( &req, NULL );
freeze_timestamp();
}
}
static std::string get_SSH_IP( void )
{
const char* SSH_CONNECTION = getenv( "SSH_CONNECTION" );
if ( !SSH_CONNECTION ) { /* Older sshds don't set this */
fputs( "Warning: SSH_CONNECTION not found; binding to any interface.\n", stderr );
return std::string( "" );
}
std::istringstream ss( SSH_CONNECTION );
std::string dummy, local_interface_IP;
ss >> dummy >> dummy >> local_interface_IP;
if ( !ss ) {
fputs( "Warning: Could not parse SSH_CONNECTION; binding to any interface.\n", stderr );
return std::string( "" );
}
/* Strip IPv6 prefix. */
const char IPv6_prefix[] = "::ffff:";
if ( ( local_interface_IP.length() > strlen( IPv6_prefix ) )
&& ( 0 == strncasecmp( local_interface_IP.c_str(), IPv6_prefix, strlen( IPv6_prefix ) ) ) ) {
return local_interface_IP.substr( strlen( IPv6_prefix ) );
}
return local_interface_IP;
}
int main( int argc, char* argv[] )
{
/* For security, make sure we don't dump core */
Crypto::disable_dumping_core();
/* Detect edge case */
fatal_assert( argc > 0 );
const char* desired_ip = NULL;
std::string desired_ip_str;
const char* desired_port = NULL;
std::string command_path;
char** command_argv = NULL;
int colors = 0;
unsigned int verbose = 0; /* don't close stdin/stdout/stderr */
/* Will cause mosh-server not to correctly detach on old versions of sshd. */
std::list<std::string> locale_vars;
/* strip off command */
for ( int i = 1; i < argc; i++ ) {
if ( 0 == strcmp( argv[i], "--help" ) || 0 == strcmp( argv[i], "-h" ) ) {
print_usage( stdout, argv[0] );
exit( 0 );
}
if ( 0 == strcmp( argv[i], "--version" ) ) {
print_version( stdout );
exit( 0 );
}
if ( 0 == strcmp( argv[i], "--" ) ) { /* -- is mandatory */
if ( i != argc - 1 ) {
command_argv = argv + i + 1;
}
argc = i; /* rest of options before -- */
break;
}
}
/* Parse new command-line syntax */
if ( ( argc >= 2 ) && ( strcmp( argv[1], "new" ) == 0 ) ) {
/* new option syntax */
int opt;
while ( ( opt = getopt( argc - 1, argv + 1, "@:i:p:c:svl:" ) ) != -1 ) {
switch ( opt ) {
/*
* This undocumented option does nothing but eat its argument.
* Useful in scripting where you prepend something to a
* mosh-server argv, and might end up with something like
* "mosh-server new -v new -c 256", now you can say
* "mosh-server new -v -@ new -c 256" to discard the second
* "new".
*/
case '@':
break;
case 'i':
desired_ip = optarg;
break;
case 'p':
desired_port = optarg;
break;
case 's':
desired_ip = NULL;
desired_ip_str = get_SSH_IP();
if ( !desired_ip_str.empty() ) {
desired_ip = desired_ip_str.c_str();
fatal_assert( desired_ip );
}
break;
case 'c':
try {
colors = myatoi( optarg );
} catch ( const CryptoException& ) {
fprintf( stderr, "%s: Bad number of colors (%s)\n", argv[0], optarg );
print_usage( stderr, argv[0] );
exit( 1 );
}
break;
case 'v':
verbose++;
break;
case 'l':
locale_vars.push_back( std::string( optarg ) );
break;
default:
/* don't die on unknown options */
print_usage( stderr, argv[0] );
break;
}
}
} else if ( argc == 1 ) {
/* legacy argument parsing for older client wrapper script */
/* do nothing */
} else if ( argc == 2 ) {
desired_ip = argv[1];
} else if ( argc == 3 ) {
desired_ip = argv[1];
desired_port = argv[2];
} else {
print_usage( stderr, argv[0] );
exit( 1 );
}
/* Sanity-check arguments */
int dpl, dph;
if ( desired_port && !Connection::parse_portrange( desired_port, dpl, dph ) ) {
fprintf( stderr, "%s: Bad UDP port range (%s)\n", argv[0], desired_port );
print_usage( stderr, argv[0] );
exit( 1 );
}
bool with_motd = false;
#ifdef HAVE_SYSLOG
openlog( argv[0], LOG_PID | LOG_NDELAY, LOG_AUTH );
#endif
/* Get shell */
char* my_argv[2];
std::string shell_name;
if ( !command_argv ) {
/* get shell name */
const char* shell = getenv( "SHELL" );
if ( shell == NULL ) {
struct passwd* pw = getpwuid( getuid() );
if ( pw == NULL ) {
perror( "getpwuid" );
exit( 1 );
}
shell = pw->pw_shell;
}
std::string shell_path( shell );
if ( shell_path.empty() ) { /* empty shell means Bourne shell */
shell_path = _PATH_BSHELL;
}
command_path = shell_path;
size_t shell_slash( shell_path.rfind( '/' ) );
if ( shell_slash == std::string::npos ) {
shell_name = shell_path;
} else {
shell_name = shell_path.substr( shell_slash + 1 );
}
/* prepend '-' to make login shell */
shell_name = '-' + shell_name;
my_argv[0] = const_cast<char*>( shell_name.c_str() );
my_argv[1] = NULL;
command_argv = my_argv;
with_motd = true;
}
if ( command_path.empty() ) {
command_path = command_argv[0];
}
/* Adopt implementation locale */
set_native_locale();
if ( !is_utf8_locale() ) {
/* save details for diagnostic */
LocaleVar native_ctype = get_ctype();
std::string native_charset( locale_charset() );
/* apply locale-related environment variables from client */
clear_locale_variables();
for ( std::list<std::string>::const_iterator i = locale_vars.begin(); i != locale_vars.end(); i++ ) {
char* env_string = strdup( i->c_str() );
fatal_assert( env_string );
if ( 0 != putenv( env_string ) ) {
perror( "putenv" );
}
}
/* check again */
set_native_locale();
if ( !is_utf8_locale() ) {
LocaleVar client_ctype = get_ctype();
std::string client_charset( locale_charset() );
fprintf( stderr,
"mosh-server needs a UTF-8 native locale to run.\n\n"
"Unfortunately, the local environment (%s) specifies\n"
"the character set \"%s\",\n\n"
"The client-supplied environment (%s) specifies\n"
"the character set \"%s\".\n\n",
native_ctype.str().c_str(),
native_charset.c_str(),
client_ctype.str().c_str(),
client_charset.c_str() );
int unused __attribute( ( unused ) ) = system( "locale" );
exit( 1 );
}
}
try {
return run_server( desired_ip, desired_port, command_path, command_argv, colors, verbose, with_motd );
} catch ( const Network::NetworkException& e ) {
fprintf( stderr, "Network exception: %s\n", e.what() );
return 1;
} catch ( const Crypto::CryptoException& e ) {
fprintf( stderr, "Crypto exception: %s\n", e.what() );
return 1;
}
}
static int run_server( const char* desired_ip,
const char* desired_port,
const std::string& command_path,
char* command_argv[],
const int colors,
unsigned int verbose,
bool with_motd )
{
/* get network idle timeout */
long network_timeout = 0;
char* timeout_envar = getenv( "MOSH_SERVER_NETWORK_TMOUT" );
if ( timeout_envar && *timeout_envar ) {
errno = 0;
char* endptr;
network_timeout = strtol( timeout_envar, &endptr, 10 );
if ( *endptr != '\0' || ( network_timeout == 0 && errno == EINVAL ) ) {
fputs( "MOSH_SERVER_NETWORK_TMOUT not a valid integer, ignoring\n", stderr );
} else if ( network_timeout < 0 ) {
fputs( "MOSH_SERVER_NETWORK_TMOUT is negative, ignoring\n", stderr );
network_timeout = 0;
}
}
/* get network signaled idle timeout */
long network_signaled_timeout = 0;
char* signal_envar = getenv( "MOSH_SERVER_SIGNAL_TMOUT" );
if ( signal_envar && *signal_envar ) {
errno = 0;
char* endptr;
network_signaled_timeout = strtol( signal_envar, &endptr, 10 );
if ( *endptr != '\0' || ( network_signaled_timeout == 0 && errno == EINVAL ) ) {
fputs( "MOSH_SERVER_SIGNAL_TMOUT not a valid integer, ignoring\n", stderr );
} else if ( network_signaled_timeout < 0 ) {
fputs( "MOSH_SERVER_SIGNAL_TMOUT is negative, ignoring\n", stderr );
network_signaled_timeout = 0;
}
}
/* get initial window size */
struct winsize window_size;
if ( ioctl( STDIN_FILENO, TIOCGWINSZ, &window_size ) < 0 || window_size.ws_col == 0 || window_size.ws_row == 0 ) {
/* Fill in sensible defaults. */
/* They will be overwritten by client on first connection. */
memset( &window_size, 0, sizeof( window_size ) );
window_size.ws_col = 80;
window_size.ws_row = 24;
}
/* open parser and terminal */
Terminal::Complete terminal( window_size.ws_col, window_size.ws_row );
/* open network */
Network::UserStream blank;
using NetworkPointer = std::shared_ptr<ServerConnection>;
NetworkPointer network( new ServerConnection( terminal, blank, desired_ip, desired_port ) );
network->set_verbose( verbose );
Select::set_verbose( verbose );
/*
* If mosh-server is run on a pty, then typeahead may echo and break mosh.pl's
* detection of the MOSH CONNECT message. Print it on a new line to bodge
* around that.
*/
if ( isatty( STDIN_FILENO ) ) {
puts( "\r\n" );
}
printf( "MOSH CONNECT %s %s\n", network->port().c_str(), network->get_key().c_str() );
/* don't let signals kill us */
struct sigaction sa;
sa.sa_handler = SIG_IGN;
sa.sa_flags = 0;
fatal_assert( 0 == sigfillset( &sa.sa_mask ) );
fatal_assert( 0 == sigaction( SIGHUP, &sa, NULL ) );
fatal_assert( 0 == sigaction( SIGPIPE, &sa, NULL ) );
/* detach from terminal */
fflush( NULL );
pid_t the_pid = fork();
if ( the_pid < 0 ) {
perror( "fork" );
} else if ( the_pid > 0 ) {
fputs( "\nmosh-server (" PACKAGE_STRING ") [build " BUILD_VERSION "]\n"
"Copyright 2012 Keith Winstein <mosh-devel@mit.edu>\n"
"License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n"
"This is free software: you are free to change and redistribute it.\n"
"There is NO WARRANTY, to the extent permitted by law.\n\n",
stderr );
fprintf( stderr, "[mosh-server detached, pid = %d]\n", static_cast<int>( the_pid ) );
#ifndef HAVE_IUTF8
fputs( "\nWarning: termios IUTF8 flag not defined.\n"
"Character-erase of multibyte character sequence\n"
"probably does not work properly on this platform.\n",
stderr );
#endif /* HAVE_IUTF8 */
fflush( NULL );
if ( isatty( STDOUT_FILENO ) ) {
tcdrain( STDOUT_FILENO );
}
if ( isatty( STDERR_FILENO ) ) {
tcdrain( STDERR_FILENO );
}
exit( 0 );
}
int master;
/* close file descriptors */
if ( verbose == 0 ) {
/* Necessary to properly detach on old versions of sshd (e.g. RHEL/CentOS 5.0). */
int nullfd;
nullfd = open( "/dev/null", O_RDWR );
if ( nullfd == -1 ) {
perror( "open" );
exit( 1 );
}
if ( dup2( nullfd, STDIN_FILENO ) < 0 || dup2( nullfd, STDOUT_FILENO ) < 0
|| dup2( nullfd, STDERR_FILENO ) < 0 ) {
perror( "dup2" );
exit( 1 );
}
if ( close( nullfd ) < 0 ) {
perror( "close" );
exit( 1 );
}
}
char utmp_entry[64] = { 0 };
snprintf( utmp_entry, 64, "mosh [%ld]", static_cast<long int>( getpid() ) );
/* Fork child process */
int pipes[2];
int success = pipe( pipes );
if ( success == -1 ) {
perror( "pipe" );
exit( 1 );
}
pid_t child = forkpty( &master, NULL, NULL, &window_size );
if ( child == -1 ) {
perror( "forkpty" );
exit( 1 );
}
if ( child == 0 ) {
/* child */
if ( close( pipes[1] ) < 0 ) {
perror( "child write pipe close" );
exit( 1 );
}
/* reenable signals */
struct sigaction sa;
sa.sa_handler = SIG_DFL;
sa.sa_flags = 0;
fatal_assert( 0 == sigfillset( &sa.sa_mask ) );
fatal_assert( 0 == sigaction( SIGHUP, &sa, NULL ) );
fatal_assert( 0 == sigaction( SIGPIPE, &sa, NULL ) );
#ifdef HAVE_SYSLOG
closelog();
#endif
/* close server-related file descriptors */
network.reset();
/* set IUTF8 if available */
#ifdef HAVE_IUTF8
struct termios child_termios;
if ( tcgetattr( STDIN_FILENO, &child_termios ) < 0 ) {
perror( "tcgetattr" );
exit( 1 );
}
child_termios.c_iflag |= IUTF8;
if ( tcsetattr( STDIN_FILENO, TCSANOW, &child_termios ) < 0 ) {
perror( "tcsetattr" );
exit( 1 );
}
#endif /* HAVE_IUTF8 */
/* set TERM */
const char default_term[] = "xterm";
const char color_term[] = "xterm-256color";
if ( setenv( "TERM", ( colors == 256 ) ? color_term : default_term, true ) < 0 ) {
perror( "setenv" );
exit( 1 );
}
/* ask ncurses to send UTF-8 instead of ISO 2022 for line-drawing chars */
if ( setenv( "NCURSES_NO_UTF8_ACS", "1", true ) < 0 ) {
perror( "setenv" );
exit( 1 );
}
/* clear STY environment variable so GNU screen regards us as top level */
if ( unsetenv( "STY" ) < 0 ) {
perror( "unsetenv" );
exit( 1 );
}
chdir_homedir();
if ( with_motd && ( !motd_hushed() ) ) {
// On illumos motd is printed by /etc/profile.
#ifndef __sun
// For Ubuntu, try and print one of {,/var}/run/motd.dynamic.
// This file is only updated when pam_motd is run, but when
// mosh-server is run in the usual way with ssh via the script,
// this always happens.
// XXX Hackish knowledge of Ubuntu PAM configuration.
// But this seems less awful than build-time detection with autoconf.
if ( !print_motd( "/run/motd.dynamic" ) ) {
print_motd( "/var/run/motd.dynamic" );
}
// Always print traditional /etc/motd.
print_motd( "/etc/motd" );
#endif
warn_unattached( utmp_entry );
}
/* Wait for parent to release us. */
char linebuf[81];
// -1, errno == EINTR -- retry
// otherwise, give up
while ( read( pipes[0], linebuf, sizeof( linebuf ) ) == -1 ) {
if ( errno != EINTR ) {
err( 1, "parent signal" );
}
}
Crypto::reenable_dumping_core();
if ( execvp( command_path.c_str(), command_argv ) < 0 ) {
warn( "execvp: %s", command_path.c_str() );
sleep( 3 );
exit( 1 );
}
if ( close( pipes[0] ) < 0 ) {
perror( "child read pipe close" );
exit( 1 );
}
} else {
/* parent */
if ( close( pipes[0] ) < 0 ) {
perror( "parent read pipe close" );
exit( 1 );
}
/* Drop unnecessary privileges */
#ifdef HAVE_PLEDGE
/* OpenBSD pledge() syscall */
if ( pledge( "stdio inet tty", NULL ) ) {
perror( "pledge() failed" );
exit( 1 );
}
#endif
#ifdef HAVE_UTEMPTER
/* make utmp entry */
utempter_add_record( master, utmp_entry );
#endif
try {
serve( master, pipes[1], terminal, *network, network_timeout, network_signaled_timeout );
} catch ( const Network::NetworkException& e ) {
fprintf( stderr, "Network exception: %s\n", e.what() );
} catch ( const Crypto::CryptoException& e ) {
fprintf( stderr, "Crypto exception: %s\n", e.what() );
}
#ifdef HAVE_UTEMPTER
utempter_remove_record( master );
#endif
if ( close( master ) < 0 ) {
perror( "close" );
exit( 1 );
}
}
fputs( "\n[mosh-server is exiting.]\n", stdout );
return 0;
}
static void serve( int host_fd,
int pipe_fd,
Terminal::Complete& terminal,
ServerConnection& network,
long network_timeout,
long network_signaled_timeout )
{
/* scale timeouts */
const uint64_t network_timeout_ms = static_cast<uint64_t>( network_timeout ) * 1000;
const uint64_t network_signaled_timeout_ms = static_cast<uint64_t>( network_signaled_timeout ) * 1000;
/* prepare to poll for events */
Select& sel = Select::get_instance();
sel.add_signal( SIGTERM );
sel.add_signal( SIGINT );
sel.add_signal( SIGUSR1 );
uint64_t last_remote_num = network.get_remote_state_num();
#ifdef HAVE_UTEMPTER
bool connected_utmp = false;
#endif
#if defined( HAVE_SYSLOG ) || defined( HAVE_UTEMPTER )
bool force_connection_change_evt = false;
Addr saved_addr;
socklen_t saved_addr_len = 0;
#endif
#ifdef HAVE_SYSLOG
struct passwd* pw = getpwuid( getuid() );
if ( pw == NULL ) {
throw NetworkException( std::string( "serve: getpwuid: " ) + strerror( errno ), 0 );
}
syslog( LOG_INFO, "user %s session begin", pw->pw_name );
#endif
bool child_released = false;
while ( true ) {
try {
static const uint64_t timeout_if_no_client = 60000;
int timeout = INT_MAX;
uint64_t now = Network::timestamp();
timeout = std::min( timeout, network.wait_time() );
timeout = std::min( timeout, terminal.wait_time( now ) );
if ( ( !network.get_remote_state_num() ) || network.shutdown_in_progress() ) {
timeout = std::min( timeout, 5000 );
}
/*
* The server goes completely asleep if it has no remote peer.
* We may want to wake up sooner.
*/
if ( network_timeout_ms ) {
int64_t network_sleep = network_timeout_ms - ( now - network.get_latest_remote_state().timestamp );
if ( network_sleep < 0 ) {
network_sleep = 0;
} else if ( network_sleep > INT_MAX ) {
/* 24 days might be too soon. That's OK. */
network_sleep = INT_MAX;
}
timeout = std::min( timeout, static_cast<int>( network_sleep ) );
}
/* poll for events */
sel.clear_fds();
std::vector<int> fd_list( network.fds() );
assert( fd_list.size() == 1 ); /* servers don't hop */
int network_fd = fd_list.back();
sel.add_fd( network_fd );
if ( !network.shutdown_in_progress() ) {
sel.add_fd( host_fd );
}
int active_fds = sel.select( timeout );
if ( active_fds < 0 ) {
perror( "select" );
break;
}
now = Network::timestamp();
uint64_t time_since_remote_state = now - network.get_latest_remote_state().timestamp;
std::string terminal_to_host;
if ( sel.read( network_fd ) ) {
/* packet received from the network */
network.recv();
/* is new user input available for the terminal? */
if ( network.get_remote_state_num() != last_remote_num ) {
last_remote_num = network.get_remote_state_num();
Network::UserStream us;
us.apply_string( network.get_remote_diff() );
/* apply userstream to terminal */
for ( size_t i = 0; i < us.size(); i++ ) {
const Parser::Action& action = us.get_action( i );
if ( typeid( action ) == typeid( Parser::Resize ) ) {
/* apply only the last consecutive Resize action */
if ( i < us.size() - 1 ) {
const Parser::Action& next = us.get_action( i + 1 );
if ( typeid( next ) == typeid( Parser::Resize ) ) {
continue;
}
}
/* tell child process of resize */
const Parser::Resize& res = static_cast<const Parser::Resize&>( action );
struct winsize window_size;
if ( ioctl( host_fd, TIOCGWINSZ, &window_size ) < 0 ) {
perror( "ioctl TIOCGWINSZ" );
network.start_shutdown();
}
window_size.ws_col = res.width;
window_size.ws_row = res.height;
if ( ioctl( host_fd, TIOCSWINSZ, &window_size ) < 0 ) {
perror( "ioctl TIOCSWINSZ" );
network.start_shutdown();
}
}
terminal_to_host += terminal.act( action );
}
if ( !us.empty() ) {
/* register input frame number for future echo ack */
terminal.register_input_frame( last_remote_num, now );
}
/* update client with new state of terminal */
if ( !network.shutdown_in_progress() ) {
network.set_current_state( terminal );
}
#if defined( HAVE_SYSLOG ) || defined( HAVE_UTEMPTER )
#ifdef HAVE_UTEMPTER
if ( !connected_utmp ) {
force_connection_change_evt = true;
} else {
force_connection_change_evt = false;
}
#else
force_connection_change_evt = false;
#endif
/**
* - HAVE_UTEMPTER - update utmp entry if we have become "connected"
* - HAVE_SYSLOG - log connection information to syslog
**/
if ( ( force_connection_change_evt ) || saved_addr_len != network.get_remote_addr_len()
|| memcmp( &saved_addr, &network.get_remote_addr(), saved_addr_len ) != 0 ) {
saved_addr = network.get_remote_addr();
saved_addr_len = network.get_remote_addr_len();
char host[NI_MAXHOST];
int errcode
= getnameinfo( &saved_addr.sa, saved_addr_len, host, sizeof( host ), NULL, 0, NI_NUMERICHOST );
if ( errcode != 0 ) {
throw NetworkException( std::string( "serve: getnameinfo: " ) + gai_strerror( errcode ), 0 );
}
#ifdef HAVE_UTEMPTER
utempter_remove_record( host_fd );
char tmp[64 + NI_MAXHOST];
snprintf( tmp, 64 + NI_MAXHOST, "%s via mosh [%ld]", host, static_cast<long int>( getpid() ) );
utempter_add_record( host_fd, tmp );
connected_utmp = true;
#endif
#ifdef HAVE_SYSLOG
syslog( LOG_INFO, "user %s connected from host: %s", pw->pw_name, host );
#endif
}
#endif
/* Tell child to start login session. */
if ( !child_released ) {
if ( close( pipe_fd ) < 0 ) {
err( 1, "child release" );
}
child_released = true;
}
}
}
if ( ( !network.shutdown_in_progress() ) && sel.read( host_fd ) ) {
/* input from the host needs to be fed to the terminal */
const int buf_size = 16384;
char buf[buf_size];
/* fill buffer if possible */
ssize_t bytes_read = read( host_fd, buf, buf_size );
/* If the pty slave is closed, reading from the master can fail with
EIO (see #264). So we treat errors on read() like EOF. */
if ( bytes_read <= 0 ) {
network.start_shutdown();
} else {
terminal_to_host += terminal.act( std::string( buf, bytes_read ) );
/* update client with new state of terminal */
network.set_current_state( terminal );
}
}
/* write user input and terminal writeback to the host */
if ( swrite( host_fd, terminal_to_host.c_str(), terminal_to_host.length() ) < 0 ) {
network.start_shutdown();
}
bool idle_shutdown = false;
if ( network_timeout_ms && network_timeout_ms <= time_since_remote_state ) {
idle_shutdown = true;
fprintf( stderr,
"Network idle for %llu seconds.\n",
static_cast<unsigned long long>( time_since_remote_state / 1000 ) );
}
if ( sel.signal( SIGUSR1 )
&& ( !network_signaled_timeout_ms || network_signaled_timeout_ms <= time_since_remote_state ) ) {
idle_shutdown = true;
fprintf( stderr,
"Network idle for %llu seconds when SIGUSR1 received\n",
static_cast<unsigned long long>( time_since_remote_state / 1000 ) );
}
if ( sel.any_signal() || idle_shutdown ) {
/* shutdown signal */
if ( network.has_remote_addr() && ( !network.shutdown_in_progress() ) ) {
network.start_shutdown();
} else {
break;
}
}
/* quit if our shutdown has been acknowledged */
if ( network.shutdown_in_progress() && network.shutdown_acknowledged() ) {
break;
}
/* quit after shutdown acknowledgement timeout */
if ( network.shutdown_in_progress() && network.shutdown_ack_timed_out() ) {
break;
}
/* quit if we received and acknowledged a shutdown request */
if ( network.counterparty_shutdown_ack_sent() ) {
break;
}
#ifdef HAVE_UTEMPTER
/* update utmp if has been more than 30 seconds since heard from client */
if ( connected_utmp && time_since_remote_state > 30000 ) {
utempter_remove_record( host_fd );
char tmp[64];
snprintf( tmp, 64, "mosh [%ld]", static_cast<long int>( getpid() ) );
utempter_add_record( host_fd, tmp );
connected_utmp = false;
}
#endif
if ( terminal.set_echo_ack( now ) && !network.shutdown_in_progress() ) {
/* update client with new echo ack */
network.set_current_state( terminal );
}
if ( !network.get_remote_state_num() && time_since_remote_state >= timeout_if_no_client ) {
fprintf( stderr,
"No connection within %llu seconds.\n",
static_cast<unsigned long long>( timeout_if_no_client / 1000 ) );
break;
}
network.tick();
} catch ( const Network::NetworkException& e ) {
fprintf( stderr, "%s\n", e.what() );
spin();
} catch ( const Crypto::CryptoException& e ) {
if ( e.fatal ) {
throw;
} else {
fprintf( stderr, "Crypto exception: %s\n", e.what() );
}
}
}
#ifdef HAVE_SYSLOG
syslog( LOG_INFO, "user %s session end", pw->pw_name );
#endif
}
/* Print the motd from a given file, if available */
static bool print_motd( const char* filename )
{
FILE* motd = fopen( filename, "r" );
if ( !motd ) {
return false;
}
const int BUFSIZE = 256;
char buffer[BUFSIZE];
while ( 1 ) {
size_t bytes_read = fread( buffer, 1, BUFSIZE, motd );
if ( bytes_read == 0 ) {
break; /* don't report error */
}
size_t bytes_written = fwrite( buffer, 1, bytes_read, stdout );
if ( bytes_written == 0 ) {
break;
}
}
fclose( motd );
return true;
}
static void chdir_homedir( void )
{
const char* home = getenv( "HOME" );
if ( home == NULL ) {
struct passwd* pw = getpwuid( getuid() );
if ( pw == NULL ) {
perror( "getpwuid" );
return; /* non-fatal */
}
home = pw->pw_dir;
}
if ( chdir( home ) < 0 ) {
perror( "chdir" );
}
if ( setenv( "PWD", home, 1 ) < 0 ) {
perror( "setenv" );
}
}
static bool motd_hushed( void )
{
/* must be in home directory already */
struct stat buf;
return 0 == lstat( ".hushlogin", &buf );
}
#ifdef HAVE_UTMPX_H
static bool device_exists( const char* ut_line )
{
std::string device_name = std::string( "/dev/" ) + std::string( ut_line );
struct stat buf;
return 0 == lstat( device_name.c_str(), &buf );
}
#endif
static void warn_unattached( const std::string& ignore_entry )
{
#ifdef HAVE_UTMPX_H
/* get username */
const struct passwd* pw = getpwuid( getuid() );
if ( pw == NULL ) {
perror( "getpwuid" );
/* non-fatal */
return;
}
const std::string username( pw->pw_name );
/* look for unattached sessions */
std::vector<std::string> unattached_mosh_servers;
while ( struct utmpx* entry = getutxent() ) {
if ( ( entry->ut_type == USER_PROCESS ) && ( username == std::string( entry->ut_user ) ) ) {
/* does line show unattached mosh session */
std::string text( entry->ut_host );
if ( ( text.size() >= 5 ) && ( text.substr( 0, 5 ) == "mosh " ) && ( text[text.size() - 1] == ']' )
&& ( text != ignore_entry ) && device_exists( entry->ut_line ) ) {
unattached_mosh_servers.push_back( text );
}
}
}
/* print out warning if necessary */
if ( unattached_mosh_servers.empty() ) {
return;
} else if ( unattached_mosh_servers.size() == 1 ) {
printf( "\033[37;44mMosh: You have a detached Mosh session on this server (%s).\033[m\n\n",
unattached_mosh_servers.front().c_str() );
} else {
std::string pid_string;
for ( std::vector<std::string>::const_iterator it = unattached_mosh_servers.begin();
it != unattached_mosh_servers.end();
it++ ) {
pid_string += " - " + *it + "\n";
}
printf( "\033[37;44mMosh: You have %d detached Mosh sessions on this server, with PIDs:\n%s\033[m\n",
(int)unattached_mosh_servers.size(),
pid_string.c_str() );
}
#endif /* HAVE_UTMPX_H */
}
| 33,251
|
C++
|
.cc
| 934
| 29.138116
| 116
| 0.586125
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,568
|
terminaloverlay.cc
|
mobile-shell_mosh/src/frontend/terminaloverlay.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include <algorithm>
#include <climits>
#include <cwchar>
#include <list>
#include <typeinfo>
#include "src/frontend/terminaloverlay.h"
using namespace Overlay;
void ConditionalOverlayCell::apply( Framebuffer& fb, uint64_t confirmed_epoch, int row, bool flag ) const
{
if ( ( !active ) || ( row >= fb.ds.get_height() ) || ( col >= fb.ds.get_width() ) ) {
return;
}
if ( tentative( confirmed_epoch ) ) {
return;
}
if ( replacement.is_blank() && fb.get_cell( row, col )->is_blank() ) {
flag = false;
}
if ( unknown ) {
if ( flag && ( col != fb.ds.get_width() - 1 ) ) {
fb.get_mutable_cell( row, col )->get_renditions().set_attribute( Renditions::underlined, true );
}
return;
}
if ( *fb.get_cell( row, col ) != replacement ) {
*( fb.get_mutable_cell( row, col ) ) = replacement;
if ( flag ) {
fb.get_mutable_cell( row, col )->get_renditions().set_attribute( Renditions::underlined, true );
}
}
}
Validity ConditionalOverlayCell::get_validity( const Framebuffer& fb,
int row,
uint64_t early_ack __attribute__( ( unused ) ),
uint64_t late_ack ) const
{
if ( !active ) {
return Inactive;
}
if ( ( row >= fb.ds.get_height() ) || ( col >= fb.ds.get_width() ) ) {
return IncorrectOrExpired;
}
const Cell& current = *( fb.get_cell( row, col ) );
/* see if it hasn't been updated yet */
if ( late_ack < expiration_frame ) {
return Pending;
}
if ( unknown ) {
return CorrectNoCredit;
}
if ( replacement.is_blank() ) { /* too easy for this to trigger falsely */
return CorrectNoCredit;
}
if ( current.contents_match( replacement ) ) {
std::vector<Cell>::const_iterator it = original_contents.begin();
for ( ; it != original_contents.end(); it++ ) {
if ( it->contents_match( replacement ) )
break;
}
if ( it == original_contents.end() ) {
return Correct;
}
return CorrectNoCredit;
}
return IncorrectOrExpired;
}
Validity ConditionalCursorMove::get_validity( const Framebuffer& fb,
uint64_t early_ack __attribute( ( unused ) ),
uint64_t late_ack ) const
{
if ( !active ) {
return Inactive;
}
if ( ( row >= fb.ds.get_height() ) || ( col >= fb.ds.get_width() ) ) {
// fprintf( stderr, "Crazy cursor (%d,%d)!\n", row, col );
return IncorrectOrExpired;
}
if ( late_ack >= expiration_frame ) {
if ( ( fb.ds.get_cursor_col() == col ) && ( fb.ds.get_cursor_row() == row ) ) {
return Correct;
}
return IncorrectOrExpired;
}
return Pending;
}
void ConditionalCursorMove::apply( Framebuffer& fb, uint64_t confirmed_epoch ) const
{
if ( !active ) {
return;
}
if ( tentative( confirmed_epoch ) ) {
return;
}
assert( row < fb.ds.get_height() );
assert( col < fb.ds.get_width() );
assert( !fb.ds.origin_mode );
fb.ds.move_row( row, false );
fb.ds.move_col( col, false, false );
}
NotificationEngine::NotificationEngine()
: last_word_from_server( timestamp() ), last_acked_state( timestamp() ), escape_key_string(), message(),
message_is_network_error( false ), message_expiration( -1 ), show_quit_keystroke( true )
{}
static std::string human_readable_duration( int num_seconds, const std::string& seconds_abbr )
{
char tmp[128];
if ( num_seconds < 60 ) {
snprintf( tmp, 128, "%d %s", num_seconds, seconds_abbr.c_str() );
} else if ( num_seconds < 3600 ) {
snprintf( tmp, 128, "%d:%02d", num_seconds / 60, num_seconds % 60 );
} else {
snprintf( tmp, 128, "%d:%02d:%02d", num_seconds / 3600, ( num_seconds / 60 ) % 60, num_seconds % 60 );
}
return tmp;
}
void NotificationEngine::apply( Framebuffer& fb ) const
{
uint64_t now = timestamp();
bool time_expired = need_countup( now );
if ( message.empty() && !time_expired ) {
return;
}
assert( fb.ds.get_width() > 0 );
assert( fb.ds.get_height() > 0 );
/* hide cursor if necessary */
if ( fb.ds.get_cursor_row() == 0 ) {
fb.ds.cursor_visible = false;
}
/* draw bar across top of screen */
Cell notification_bar( 0 );
notification_bar.get_renditions().set_foreground_color( 7 );
notification_bar.get_renditions().set_background_color( 4 );
notification_bar.append( 0x20 );
for ( int i = 0; i < fb.ds.get_width(); i++ ) {
*( fb.get_mutable_cell( 0, i ) ) = notification_bar;
}
/* write message */
wchar_t tmp[128];
/* We want to prefer the "last contact" message if we simply haven't
heard from the server in a while, but print the "last reply" message
if the problem is uplink-only. */
double since_heard = (double)( now - last_word_from_server ) / 1000.0;
double since_ack = (double)( now - last_acked_state ) / 1000.0;
const char server_message[] = "contact";
const char reply_message[] = "reply";
double time_elapsed = since_heard;
const char* explanation = server_message;
if ( reply_late( now ) && ( !server_late( now ) ) ) {
time_elapsed = since_ack;
explanation = reply_message;
}
const static char blank[] = "";
const char* keystroke_str = show_quit_keystroke ? escape_key_string.c_str() : blank;
if ( message.empty() && ( !time_expired ) ) {
return;
}
if ( message.empty() && time_expired ) {
swprintf( tmp,
128,
L"mosh: Last %s %s ago.%s",
explanation,
human_readable_duration( static_cast<int>( time_elapsed ), "seconds" ).c_str(),
keystroke_str );
} else if ( ( !message.empty() ) && ( !time_expired ) ) {
swprintf( tmp, 128, L"mosh: %ls%s", message.c_str(), keystroke_str );
} else {
swprintf( tmp,
128,
L"mosh: %ls (%s without %s.)%s",
message.c_str(),
human_readable_duration( static_cast<int>( time_elapsed ), "s" ).c_str(),
explanation,
keystroke_str );
}
std::wstring string_to_draw( tmp );
int overlay_col = 0;
Cell* combining_cell = fb.get_mutable_cell( 0, 0 );
/* We unfortunately duplicate the terminal's logic for how to render a Unicode sequence into graphemes */
for ( std::wstring::const_iterator i = string_to_draw.begin(); i != string_to_draw.end(); i++ ) {
if ( overlay_col >= fb.ds.get_width() ) {
break;
}
wchar_t ch = *i;
int chwidth = ch == L'\0' ? -1 : wcwidth( ch );
Cell* this_cell = 0;
switch ( chwidth ) {
case 1: /* normal character */
case 2: /* wide character */
this_cell = fb.get_mutable_cell( 0, overlay_col );
fb.reset_cell( this_cell );
this_cell->get_renditions().set_attribute( Renditions::bold, true );
this_cell->get_renditions().set_foreground_color( 7 );
this_cell->get_renditions().set_background_color( 4 );
this_cell->append( ch );
this_cell->set_wide( chwidth == 2 );
combining_cell = this_cell;
overlay_col += chwidth;
break;
case 0: /* combining character */
if ( !combining_cell ) {
break;
}
if ( combining_cell->empty() ) {
assert( !combining_cell->get_wide() );
combining_cell->set_fallback( true );
overlay_col++;
}
if ( !combining_cell->full() ) {
combining_cell->append( ch );
}
break;
case -1: /* unprintable character */
break;
default:
assert( !"unexpected character width from wcwidth()" );
}
}
}
void NotificationEngine::adjust_message( void )
{
if ( timestamp() >= message_expiration ) {
message.clear();
}
}
int NotificationEngine::wait_time( void ) const
{
uint64_t next_expiry = INT_MAX;
uint64_t now = timestamp();
next_expiry = std::min( next_expiry, message_expiration - now );
if ( need_countup( now ) ) {
uint64_t countup_interval = 1000;
if ( ( now - last_word_from_server ) > 60000 ) {
/* If we've been disconnected for 60 seconds, save power by updating the
display less often. See #243. */
countup_interval = Network::ACK_INTERVAL;
}
next_expiry = std::min( next_expiry, countup_interval );
}
return next_expiry;
}
void OverlayManager::apply( Framebuffer& fb )
{
predictions.cull( fb );
predictions.apply( fb );
notifications.adjust_message();
notifications.apply( fb );
title.apply( fb );
}
void TitleEngine::set_prefix( const std::wstring& s )
{
prefix = Terminal::Framebuffer::title_type( s.begin(), s.end() );
}
void ConditionalOverlayRow::apply( Framebuffer& fb, uint64_t confirmed_epoch, bool flag ) const
{
for ( overlay_cells_type::const_iterator it = overlay_cells.begin(); it != overlay_cells.end(); it++ ) {
it->apply( fb, confirmed_epoch, row_num, flag );
}
}
void PredictionEngine::apply( Framebuffer& fb ) const
{
if ( ( display_preference == Never )
|| !( srtt_trigger || glitch_trigger || ( display_preference == Always )
|| ( display_preference == Experimental ) ) ) {
return;
}
for ( cursors_type::const_iterator it = cursors.begin(); it != cursors.end(); it++ ) {
it->apply( fb, confirmed_epoch );
}
for ( overlays_type::const_iterator it = overlays.begin(); it != overlays.end(); it++ ) {
it->apply( fb, confirmed_epoch, flagging );
}
}
void PredictionEngine::kill_epoch( uint64_t epoch, const Framebuffer& fb )
{
for ( cursors_type::iterator it = cursors.begin(); it != cursors.end(); ) {
cursors_type::iterator it_next = it;
it_next++;
if ( it->tentative( epoch - 1 ) ) {
cursors.erase( it );
}
it = it_next;
}
cursors.push_back( ConditionalCursorMove(
local_frame_sent + 1, fb.ds.get_cursor_row(), fb.ds.get_cursor_col(), prediction_epoch ) );
cursor().active = true;
for ( overlays_type::iterator i = overlays.begin(); i != overlays.end(); i++ ) {
for ( overlay_cells_type::iterator j = i->overlay_cells.begin(); j != i->overlay_cells.end(); j++ ) {
if ( j->tentative( epoch - 1 ) ) {
j->reset();
}
}
}
become_tentative();
}
void PredictionEngine::reset( void )
{
cursors.clear();
overlays.clear();
become_tentative();
// fprintf( stderr, "RESETTING\n" );
}
void PredictionEngine::init_cursor( const Framebuffer& fb )
{
if ( cursors.empty() ) {
/* initialize new cursor prediction */
cursors.push_back( ConditionalCursorMove(
local_frame_sent + 1, fb.ds.get_cursor_row(), fb.ds.get_cursor_col(), prediction_epoch ) );
cursor().active = true;
} else if ( cursor().tentative_until_epoch != prediction_epoch ) {
cursors.push_back(
ConditionalCursorMove( local_frame_sent + 1, cursor().row, cursor().col, prediction_epoch ) );
cursor().active = true;
}
}
void PredictionEngine::cull( const Framebuffer& fb )
{
if ( display_preference == Never ) {
return;
}
if ( ( last_height != fb.ds.get_height() ) || ( last_width != fb.ds.get_width() ) ) {
last_height = fb.ds.get_height();
last_width = fb.ds.get_width();
reset();
}
uint64_t now = timestamp();
/* control srtt_trigger with hysteresis */
if ( send_interval > SRTT_TRIGGER_HIGH ) {
srtt_trigger = true;
} else if ( srtt_trigger && ( send_interval <= SRTT_TRIGGER_LOW ) /* 20 ms is current minimum value */
&& ( !active() ) ) { /* only turn off when no predictions being shown */
srtt_trigger = false;
}
/* control underlining with hysteresis */
if ( send_interval > FLAG_TRIGGER_HIGH ) {
flagging = true;
} else if ( send_interval <= FLAG_TRIGGER_LOW ) {
flagging = false;
}
/* really big glitches also activate underlining */
if ( glitch_trigger > GLITCH_REPAIR_COUNT ) {
flagging = true;
}
/* go through cell predictions */
overlays_type::iterator i = overlays.begin();
while ( i != overlays.end() ) {
overlays_type::iterator inext = i;
inext++;
if ( ( i->row_num < 0 ) || ( i->row_num >= fb.ds.get_height() ) ) {
overlays.erase( i );
i = inext;
continue;
}
for ( overlay_cells_type::iterator j = i->overlay_cells.begin(); j != i->overlay_cells.end(); j++ ) {
switch ( j->get_validity( fb, i->row_num, local_frame_acked, local_frame_late_acked ) ) {
case IncorrectOrExpired:
if ( j->tentative( confirmed_epoch ) ) {
/*
fprintf( stderr, "Bad tentative prediction in row %d, col %d (think %lc, actually %lc)\n",
i->row_num, j->col,
j->replacement.debug_contents(),
fb.get_cell( i->row_num, j->col )->debug_contents()
);
*/
if ( display_preference == Experimental ) {
j->reset();
} else {
kill_epoch( j->tentative_until_epoch, fb );
}
/*
if ( j->display_time != uint64_t(-1) ) {
fprintf( stderr, "TIMING %ld - %ld (TENT)\n", time(NULL), now - j->display_time );
}
*/
} else {
/*
fprintf( stderr, "[%d=>%d] Killing prediction in row %d, col %d (think %lc, actually %lc)\n",
(int)local_frame_acked, (int)j->expiration_frame,
i->row_num, j->col,
j->replacement.debug_contents(),
fb.get_cell( i->row_num, j->col )->debug_contents() );
*/
/*
if ( j->display_time != uint64_t(-1) ) {
fprintf( stderr, "TIMING %ld - %ld\n", time(NULL), now - j->display_time );
}
*/
if ( display_preference == Experimental ) {
j->reset();
} else {
reset();
return;
}
}
break;
case Correct:
/*
if ( j->display_time != uint64_t(-1) ) {
fprintf( stderr, "TIMING %ld + %ld\n", now, now - j->display_time );
}
*/
if ( j->tentative_until_epoch > confirmed_epoch ) {
confirmed_epoch = j->tentative_until_epoch;
/*
fprintf( stderr, "%lc in (%d,%d) confirms epoch %lu (predicting in epoch %lu)\n",
j->replacement.debug_contents(), i->row_num, j->col,
confirmed_epoch, prediction_epoch );
*/
}
/* When predictions come in quickly, slowly take away the glitch trigger. */
if ( now - j->prediction_time < GLITCH_THRESHOLD
&& ( glitch_trigger > 0 && now - GLITCH_REPAIR_MININTERVAL >= last_quick_confirmation ) ) {
glitch_trigger--;
last_quick_confirmation = now;
}
/* match rest of row to the actual renditions */
{
const Renditions& actual_renditions = fb.get_cell( i->row_num, j->col )->get_renditions();
for ( overlay_cells_type::iterator k = j; k != i->overlay_cells.end(); k++ ) {
k->replacement.get_renditions() = actual_renditions;
}
}
/* fallthrough */
case CorrectNoCredit:
j->reset();
break;
case Pending:
/* When a prediction takes a long time to be confirmed, we
activate the predictions even if SRTT is low */
if ( ( now - j->prediction_time ) >= GLITCH_FLAG_THRESHOLD ) {
glitch_trigger = GLITCH_REPAIR_COUNT * 2; /* display and underline */
} else if ( ( ( now - j->prediction_time ) >= GLITCH_THRESHOLD )
&& ( glitch_trigger < GLITCH_REPAIR_COUNT ) ) {
glitch_trigger = GLITCH_REPAIR_COUNT; /* just display */
}
break;
default:
break;
}
}
i = inext;
}
/* go through cursor predictions */
if ( !cursors.empty()
&& cursor().get_validity( fb, local_frame_acked, local_frame_late_acked ) == IncorrectOrExpired ) {
/*
fprintf( stderr, "Sadly, we're predicting (%d,%d) vs. (%d,%d) [tau: %ld, expiration_time=%ld, now=%ld]\n",
cursor().row, cursor().col,
fb.ds.get_cursor_row(),
fb.ds.get_cursor_col(),
cursor().tentative_until_epoch,
cursor().expiration_time,
now );
*/
if ( display_preference == Experimental ) {
cursors.clear();
} else {
reset();
return;
}
}
/* NB: switching from list to another STL container could break this code.
So we don't use the cursors_type typedef. */
for ( std::list<ConditionalCursorMove>::iterator it = cursors.begin(); it != cursors.end(); ) {
if ( it->get_validity( fb, local_frame_acked, local_frame_late_acked ) != Pending ) {
it = cursors.erase( it );
} else {
it++;
}
}
}
ConditionalOverlayRow& PredictionEngine::get_or_make_row( int row_num, int num_cols )
{
overlays_type::iterator it;
for ( it = overlays.begin(); it != overlays.end(); it++ ) {
if ( it->row_num == row_num ) {
break;
}
}
if ( it != overlays.end() ) {
return *it;
}
/* make row */
ConditionalOverlayRow r( row_num );
r.overlay_cells.reserve( num_cols );
for ( int i = 0; i < num_cols; i++ ) {
r.overlay_cells.push_back( ConditionalOverlayCell( 0, i, prediction_epoch ) );
assert( r.overlay_cells[i].col == i );
}
overlays.push_back( r );
return overlays.back();
}
void PredictionEngine::new_user_byte( char the_byte, const Framebuffer& fb )
{
if ( display_preference == Never ) {
return;
}
if ( display_preference == Experimental ) {
prediction_epoch = confirmed_epoch;
}
cull( fb );
uint64_t now = timestamp();
/* translate application-mode cursor control function to ANSI cursor control sequence */
if ( ( last_byte == 0x1b ) && ( the_byte == 'O' ) ) {
the_byte = '[';
}
last_byte = the_byte;
Parser::Actions actions;
parser.input( the_byte, actions );
for ( Parser::Actions::iterator it = actions.begin(); it != actions.end(); it++ ) {
Parser::Action& act = **it;
/*
fprintf( stderr, "Action: %s (%lc)\n",
act->name().c_str(), act->char_present ? act->ch : L'_' );
*/
const std::type_info& type_act = typeid( act );
if ( type_act == typeid( Parser::Print ) ) {
/* make new prediction */
init_cursor( fb );
assert( act.char_present );
wchar_t ch = act.ch;
/* XXX handle wide characters */
if ( ch == 0x7f ) { /* backspace */
// fprintf( stderr, "Backspace.\n" );
ConditionalOverlayRow& the_row = get_or_make_row( cursor().row, fb.ds.get_width() );
if ( cursor().col > 0 ) {
cursor().col--;
cursor().expire( local_frame_sent + 1, now );
if ( predict_overwrite ) {
ConditionalOverlayCell& cell = the_row.overlay_cells[cursor().col];
cell.reset_with_orig();
cell.active = true;
cell.tentative_until_epoch = prediction_epoch;
cell.expire( local_frame_sent + 1, now );
const Cell orig_cell = *fb.get_cell();
cell.original_contents.push_back( orig_cell );
cell.replacement = orig_cell;
cell.replacement.clear();
cell.replacement.append( ' ' );
} else {
for ( int i = cursor().col; i < fb.ds.get_width(); i++ ) {
ConditionalOverlayCell& cell = the_row.overlay_cells[i];
cell.reset_with_orig();
cell.active = true;
cell.tentative_until_epoch = prediction_epoch;
cell.expire( local_frame_sent + 1, now );
cell.original_contents.push_back( *fb.get_cell( cursor().row, i ) );
if ( i + 2 < fb.ds.get_width() ) {
ConditionalOverlayCell& next_cell = the_row.overlay_cells[i + 1];
const Cell* next_cell_actual = fb.get_cell( cursor().row, i + 1 );
if ( next_cell.active ) {
if ( next_cell.unknown ) {
cell.unknown = true;
} else {
cell.unknown = false;
cell.replacement = next_cell.replacement;
}
} else {
cell.unknown = false;
cell.replacement = *next_cell_actual;
}
} else {
cell.unknown = true;
}
}
}
}
} else if ( ( ch < 0x20 ) || ( wcwidth( ch ) != 1 ) ) {
/* unknown print */
become_tentative();
// fprintf( stderr, "Unknown print 0x%x\n", ch );
} else {
assert( cursor().row >= 0 );
assert( cursor().col >= 0 );
assert( cursor().row < fb.ds.get_height() );
assert( cursor().col < fb.ds.get_width() );
ConditionalOverlayRow& the_row = get_or_make_row( cursor().row, fb.ds.get_width() );
if ( cursor().col + 1 >= fb.ds.get_width() ) {
/* prediction in the last column is tricky */
/* e.g., emacs will show wrap character, shell will just put the character there */
become_tentative();
}
/* do the insert */
int rightmost_column = predict_overwrite ? cursor().col : fb.ds.get_width() - 1;
for ( int i = rightmost_column; i > cursor().col; i-- ) {
ConditionalOverlayCell& cell = the_row.overlay_cells[i];
cell.reset_with_orig();
cell.active = true;
cell.tentative_until_epoch = prediction_epoch;
cell.expire( local_frame_sent + 1, now );
cell.original_contents.push_back( *fb.get_cell( cursor().row, i ) );
ConditionalOverlayCell& prev_cell = the_row.overlay_cells[i - 1];
const Cell* prev_cell_actual = fb.get_cell( cursor().row, i - 1 );
if ( i == fb.ds.get_width() - 1 ) {
cell.unknown = true;
} else if ( prev_cell.active ) {
if ( prev_cell.unknown ) {
cell.unknown = true;
} else {
cell.unknown = false;
cell.replacement = prev_cell.replacement;
}
} else {
cell.unknown = false;
cell.replacement = *prev_cell_actual;
}
}
ConditionalOverlayCell& cell = the_row.overlay_cells[cursor().col];
cell.reset_with_orig();
cell.active = true;
cell.tentative_until_epoch = prediction_epoch;
cell.expire( local_frame_sent + 1, now );
cell.replacement.get_renditions() = fb.ds.get_renditions();
/* heuristic: match renditions of character to the left */
if ( cursor().col > 0 ) {
ConditionalOverlayCell& prev_cell = the_row.overlay_cells[cursor().col - 1];
const Cell* prev_cell_actual = fb.get_cell( cursor().row, cursor().col - 1 );
if ( prev_cell.active && ( !prev_cell.unknown ) ) {
cell.replacement.get_renditions() = prev_cell.replacement.get_renditions();
} else {
cell.replacement.get_renditions() = prev_cell_actual->get_renditions();
}
}
cell.replacement.clear();
cell.replacement.append( ch );
cell.original_contents.push_back( *fb.get_cell( cursor().row, cursor().col ) );
/*
fprintf( stderr, "[%d=>%d] Predicting %lc in row %d, col %d [tue: %lu]\n",
(int)local_frame_acked, (int)cell.expiration_frame,
ch, cursor().row, cursor().col,
cell.tentative_until_epoch );
*/
cursor().expire( local_frame_sent + 1, now );
/* do we need to wrap? */
if ( cursor().col < fb.ds.get_width() - 1 ) {
cursor().col++;
} else {
become_tentative();
newline_carriage_return( fb );
}
}
} else if ( type_act == typeid( Parser::Execute ) ) {
if ( act.char_present && ( act.ch == 0x0d ) /* CR */ ) {
become_tentative();
newline_carriage_return( fb );
} else {
// fprintf( stderr, "Execute 0x%x\n", act.ch );
become_tentative();
}
} else if ( type_act == typeid( Parser::Esc_Dispatch ) ) {
// fprintf( stderr, "Escape sequence\n" );
become_tentative();
} else if ( type_act == typeid( Parser::CSI_Dispatch ) ) {
if ( act.char_present && ( act.ch == L'C' ) ) { /* right arrow */
init_cursor( fb );
if ( cursor().col < fb.ds.get_width() - 1 ) {
cursor().col++;
cursor().expire( local_frame_sent + 1, now );
}
} else if ( act.char_present && ( act.ch == L'D' ) ) { /* left arrow */
init_cursor( fb );
if ( cursor().col > 0 ) {
cursor().col--;
cursor().expire( local_frame_sent + 1, now );
}
} else {
// fprintf( stderr, "CSI sequence %lc\n", act.ch );
become_tentative();
}
}
}
}
void PredictionEngine::newline_carriage_return( const Framebuffer& fb )
{
uint64_t now = timestamp();
init_cursor( fb );
cursor().col = 0;
if ( cursor().row == fb.ds.get_height() - 1 ) {
/* Don't try to predict scroll until we have versioned cell predictions */
/*
for ( overlays_type::iterator i = overlays.begin();
i != overlays.end();
i++ ) {
i->row_num--;
for ( overlay_cells_type::iterator j = i->overlay_cells.begin();
j != i->overlay_cells.end();
j++ ) {
if ( j->active ) {
j->expire( local_frame_sent + 1, now );
}
}
}
*/
/* make blank prediction for last row */
ConditionalOverlayRow& the_row = get_or_make_row( cursor().row, fb.ds.get_width() );
for ( overlay_cells_type::iterator j = the_row.overlay_cells.begin(); j != the_row.overlay_cells.end(); j++ ) {
j->active = true;
j->tentative_until_epoch = prediction_epoch;
j->expire( local_frame_sent + 1, now );
j->replacement.clear();
}
} else {
cursor().row++;
}
}
void PredictionEngine::become_tentative( void )
{
if ( display_preference != Experimental ) {
prediction_epoch++;
}
/*
fprintf( stderr, "Now tentative in epoch %lu (confirmed=%lu)\n",
prediction_epoch, confirmed_epoch );
*/
}
bool PredictionEngine::active( void ) const
{
if ( !cursors.empty() ) {
return true;
}
for ( overlays_type::const_iterator i = overlays.begin(); i != overlays.end(); i++ ) {
for ( overlay_cells_type::const_iterator j = i->overlay_cells.begin(); j != i->overlay_cells.end(); j++ ) {
if ( j->active ) {
return true;
}
}
}
return false;
}
| 28,310
|
C++
|
.cc
| 754
| 30.253316
| 115
| 0.574623
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,569
|
mosh-client.cc
|
mobile-shell_mosh/src/frontend/mosh-client.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include "src/include/config.h"
#include "src/include/version.h"
#include <cstdlib>
#include <unistd.h>
#include "src/crypto/crypto.h"
#include "src/util/fatal_assert.h"
#include "src/util/locale_utils.h"
#include "stmclient.h"
/* These need to be included last because of conflicting defines. */
/*
* stmclient.h includes termios.h, and that will break termio/termios pull in on Solaris.
* The solution is to include termio.h also.
* But Mac OS X doesn't have termio.h, so this needs a guard.
*/
#ifdef HAVE_TERMIO_H
#include <termio.h>
#endif
#if defined HAVE_NCURSESW_CURSES_H
#include <ncursesw/curses.h>
#include <ncursesw/term.h>
#elif defined HAVE_NCURSESW_H
#include <ncursesw.h>
#include <term.h>
#elif defined HAVE_NCURSES_CURSES_H
#include <ncurses/curses.h>
#include <ncurses/term.h>
#elif defined HAVE_NCURSES_H
#include <ncurses.h>
#include <term.h>
#elif defined HAVE_CURSES_H
#include <curses.h>
#include <term.h>
#else
#error "SysV or X/Open-compatible Curses header file required"
#endif
static void print_version( FILE* file )
{
fputs( "mosh-client (" PACKAGE_STRING ") [build " BUILD_VERSION "]\n"
"Copyright 2012 Keith Winstein <mosh-devel@mit.edu>\n"
"License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n"
"This is free software: you are free to change and redistribute it.\n"
"There is NO WARRANTY, to the extent permitted by law.\n",
file );
}
static void print_usage( FILE* file, const char* argv0 )
{
print_version( file );
fprintf( file,
"\nUsage: %s [-# 'ARGS'] IP PORT\n"
" %s -c\n",
argv0,
argv0 );
}
static void print_colorcount( void )
{
/* check colors */
setupterm( (char*)0, 1, (int*)0 );
char colors_name[] = "colors";
int color_val = tigetnum( colors_name );
if ( color_val == -2 ) {
fprintf( stderr, "Invalid terminfo numeric capability: %s\n", colors_name );
}
printf( "%d\n", color_val );
}
#ifdef NACL
int mosh_main( int argc, char* argv[] )
#else
int main( int argc, char* argv[] )
#endif
{
unsigned int verbose = 0;
/* For security, make sure we don't dump core */
Crypto::disable_dumping_core();
/* Detect edge case */
fatal_assert( argc > 0 );
/* Get arguments */
for ( int i = 1; i < argc; i++ ) {
if ( 0 == strcmp( argv[i], "--help" ) ) {
print_usage( stdout, argv[0] );
exit( 0 );
}
if ( 0 == strcmp( argv[i], "--version" ) ) {
print_version( stdout );
exit( 0 );
}
}
int opt;
while ( ( opt = getopt( argc, argv, "#:cv" ) ) != -1 ) {
switch ( opt ) {
case '#':
// Ignore the original arguments to mosh wrapper
break;
case 'c':
print_colorcount();
exit( 0 );
break;
case 'v':
verbose++;
break;
default:
print_usage( stderr, argv[0] );
exit( 1 );
break;
}
}
char *ip, *desired_port;
if ( argc - optind != 2 ) {
print_usage( stderr, argv[0] );
exit( 1 );
}
ip = argv[optind];
desired_port = argv[optind + 1];
/* Sanity-check arguments */
if ( desired_port && ( strspn( desired_port, "0123456789" ) != strlen( desired_port ) ) ) {
fprintf( stderr, "%s: Bad UDP port (%s)\n\n", argv[0], desired_port );
print_usage( stderr, argv[0] );
exit( 1 );
}
/* Read key from environment */
char* env_key = getenv( "MOSH_KEY" );
if ( env_key == NULL ) {
fputs( "MOSH_KEY environment variable not found.\n", stderr );
exit( 1 );
}
/* Read prediction preference */
char* predict_mode = getenv( "MOSH_PREDICTION_DISPLAY" );
/* can be NULL */
/* Read prediction insertion preference */
char* predict_overwrite = getenv( "MOSH_PREDICTION_OVERWRITE" );
/* can be NULL */
std::string key( env_key );
if ( unsetenv( "MOSH_KEY" ) < 0 ) {
perror( "unsetenv" );
exit( 1 );
}
/* Adopt native locale */
set_native_locale();
bool success = false;
try {
STMClient client( ip, desired_port, key.c_str(), predict_mode, verbose, predict_overwrite );
client.init();
try {
success = client.main();
} catch ( ... ) {
client.shutdown();
throw;
}
client.shutdown();
} catch ( const Network::NetworkException& e ) {
fprintf( stderr, "Network exception: %s\r\n", e.what() );
success = false;
} catch ( const Crypto::CryptoException& e ) {
fprintf( stderr, "Crypto exception: %s\r\n", e.what() );
success = false;
} catch ( const std::exception& e ) {
fprintf( stderr, "Error: %s\r\n", e.what() );
success = false;
}
printf( "[mosh is exiting.]\n" );
return !success;
}
| 6,164
|
C++
|
.cc
| 187
| 28.828877
| 96
| 0.653315
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,570
|
terminaldisplay.cc
|
mobile-shell_mosh/src/terminal/terminaldisplay.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include <cstdio>
#include "src/terminal/terminalframebuffer.h"
#include "terminaldisplay.h"
using namespace Terminal;
/* Print a new "frame" to the terminal, using ANSI/ECMA-48 escape codes. */
static const Renditions& initial_rendition( void )
{
const static Renditions blank = Renditions( 0 );
return blank;
}
std::string Display::open() const
{
return std::string( smcup ? smcup : "" ) + std::string( "\033[?1h" );
}
std::string Display::close() const
{
return std::string( "\033[?1l\033[0m\033[?25h"
"\033[?1003l\033[?1002l\033[?1001l\033[?1000l"
"\033[?1015l\033[?1006l\033[?1005l" )
+ std::string( rmcup ? rmcup : "" );
}
std::string Display::new_frame( bool initialized, const Framebuffer& last, const Framebuffer& f ) const
{
FrameState frame( last );
char tmp[64];
/* has bell been rung? */
if ( f.get_bell_count() != frame.last_frame.get_bell_count() ) {
frame.append( '\007' );
}
using title_type = Terminal::Framebuffer::title_type;
/* has icon name or window title changed? */
if ( has_title && f.is_title_initialized()
&& ( ( !initialized ) || ( f.get_icon_name() != frame.last_frame.get_icon_name() )
|| ( f.get_window_title() != frame.last_frame.get_window_title() ) ) ) {
/* set icon name and window title */
if ( f.get_icon_name() == f.get_window_title() ) {
/* write combined Icon Name and Window Title */
frame.append( "\033]0;" );
const title_type& window_title( f.get_window_title() );
for ( title_type::const_iterator i = window_title.begin(); i != window_title.end(); i++ ) {
frame.append( *i );
}
frame.append( '\007' );
/* ST is more correct, but BEL more widely supported */
} else {
/* write Icon Name */
frame.append( "\033]1;" );
const title_type& icon_name( f.get_icon_name() );
for ( title_type::const_iterator i = icon_name.begin(); i != icon_name.end(); i++ ) {
frame.append( *i );
}
frame.append( '\007' );
frame.append( "\033]2;" );
const title_type& window_title( f.get_window_title() );
for ( title_type::const_iterator i = window_title.begin(); i != window_title.end(); i++ ) {
frame.append( *i );
}
frame.append( '\007' );
}
}
/* has clipboard changed? */
if ( f.get_clipboard() != frame.last_frame.get_clipboard() ) {
frame.append( "\033]52;c;" );
const title_type& clipboard( f.get_clipboard() );
for ( title_type::const_iterator i = clipboard.begin(); i != clipboard.end(); i++ ) {
frame.append( *i );
}
frame.append( '\007' );
}
/* has reverse video state changed? */
if ( ( !initialized ) || ( f.ds.reverse_video != frame.last_frame.ds.reverse_video ) ) {
/* set reverse video */
snprintf( tmp, 64, "\033[?5%c", ( f.ds.reverse_video ? 'h' : 'l' ) );
frame.append( tmp );
}
/* has size changed? */
if ( ( !initialized ) || ( f.ds.get_width() != frame.last_frame.ds.get_width() )
|| ( f.ds.get_height() != frame.last_frame.ds.get_height() ) ) {
/* reset scrolling region */
frame.append( "\033[r" );
/* clear screen */
frame.append( "\033[0m\033[H\033[2J" );
initialized = false;
frame.cursor_x = frame.cursor_y = 0;
frame.current_rendition = initial_rendition();
} else {
frame.cursor_x = frame.last_frame.ds.get_cursor_col();
frame.cursor_y = frame.last_frame.ds.get_cursor_row();
frame.current_rendition = frame.last_frame.ds.get_renditions();
}
/* is cursor visibility initialized? */
if ( !initialized ) {
frame.cursor_visible = false;
frame.append( "\033[?25l" );
}
int frame_y = 0;
Framebuffer::row_pointer blank_row;
Framebuffer::rows_type rows( frame.last_frame.get_rows() );
/* Extend rows if we've gotten a resize and new is wider than old */
if ( frame.last_frame.ds.get_width() < f.ds.get_width() ) {
for ( Framebuffer::rows_type::iterator p = rows.begin(); p != rows.end(); p++ ) {
*p = std::make_shared<Row>( **p );
( *p )->cells.resize( f.ds.get_width(), Cell( f.ds.get_background_rendition() ) );
}
}
/* Add rows if we've gotten a resize and new is taller than old */
if ( static_cast<int>( rows.size() ) < f.ds.get_height() ) {
// get a proper blank row
const size_t w = f.ds.get_width();
const color_type c = 0;
blank_row = std::make_shared<Row>( w, c );
rows.resize( f.ds.get_height(), blank_row );
}
/* shortcut -- has display moved up by a certain number of lines? */
if ( initialized ) {
int lines_scrolled = 0;
int scroll_height = 0;
for ( int row = 0; row < f.ds.get_height(); row++ ) {
const Row* new_row = f.get_row( 0 );
const Row* old_row = &*rows.at( row );
if ( !( new_row == old_row || *new_row == *old_row ) ) {
continue;
}
/* if row 0, we're looking at ourselves and probably didn't scroll */
if ( row == 0 ) {
break;
}
/* found a scroll */
lines_scrolled = row;
scroll_height = 1;
/* how big is the region that was scrolled? */
for ( int region_height = 1; lines_scrolled + region_height < f.ds.get_height(); region_height++ ) {
if ( *f.get_row( region_height ) == *rows.at( lines_scrolled + region_height ) ) {
scroll_height = region_height + 1;
} else {
break;
}
}
break;
}
if ( scroll_height ) {
frame_y = scroll_height;
if ( lines_scrolled ) {
/* Now we need a proper blank row. */
if ( blank_row.get() == NULL ) {
const size_t w = f.ds.get_width();
const color_type c = 0;
blank_row = std::make_shared<Row>( w, c );
}
frame.update_rendition( initial_rendition(), true );
int top_margin = 0;
int bottom_margin = top_margin + lines_scrolled + scroll_height - 1;
assert( bottom_margin < f.ds.get_height() );
/* Common case: if we're already on the bottom line and we're scrolling the whole
* screen, just do a CR and LFs.
*/
if ( scroll_height + lines_scrolled == f.ds.get_height() && frame.cursor_y + 1 == f.ds.get_height() ) {
frame.append( '\r' );
frame.append( lines_scrolled, '\n' );
frame.cursor_x = 0;
} else {
/* set scrolling region */
snprintf( tmp, 64, "\033[%d;%dr", top_margin + 1, bottom_margin + 1 );
frame.append( tmp );
/* go to bottom of scrolling region */
frame.cursor_x = frame.cursor_y = -1;
frame.append_silent_move( bottom_margin, 0 );
/* scroll */
frame.append( lines_scrolled, '\n' );
/* reset scrolling region */
frame.append( "\033[r" );
/* invalidate cursor position after unsetting scrolling region */
frame.cursor_x = frame.cursor_y = -1;
}
/* do the move in our local index */
for ( int i = top_margin; i <= bottom_margin; i++ ) {
if ( i + lines_scrolled <= bottom_margin ) {
rows.at( i ) = rows.at( i + lines_scrolled );
} else {
rows.at( i ) = blank_row;
}
}
}
}
}
/* Now update the display, row by row */
bool wrap = false;
for ( ; frame_y < f.ds.get_height(); frame_y++ ) {
wrap = put_row( initialized, frame, f, frame_y, *rows.at( frame_y ), wrap );
}
/* has cursor location changed? */
if ( ( !initialized ) || ( f.ds.get_cursor_row() != frame.cursor_y )
|| ( f.ds.get_cursor_col() != frame.cursor_x ) ) {
frame.append_move( f.ds.get_cursor_row(), f.ds.get_cursor_col() );
}
/* has cursor visibility changed? */
if ( ( !initialized ) || ( f.ds.cursor_visible != frame.cursor_visible ) ) {
if ( f.ds.cursor_visible ) {
frame.append( "\033[?25h" );
} else {
frame.append( "\033[?25l" );
}
}
/* have renditions changed? */
frame.update_rendition( f.ds.get_renditions(), !initialized );
/* has bracketed paste mode changed? */
if ( ( !initialized ) || ( f.ds.bracketed_paste != frame.last_frame.ds.bracketed_paste ) ) {
frame.append( f.ds.bracketed_paste ? "\033[?2004h" : "\033[?2004l" );
}
/* has mouse reporting mode changed? */
if ( ( !initialized ) || ( f.ds.mouse_reporting_mode != frame.last_frame.ds.mouse_reporting_mode ) ) {
if ( f.ds.mouse_reporting_mode == DrawState::MOUSE_REPORTING_NONE ) {
frame.append( "\033[?1003l" );
frame.append( "\033[?1002l" );
frame.append( "\033[?1001l" );
frame.append( "\033[?1000l" );
} else {
if ( frame.last_frame.ds.mouse_reporting_mode != DrawState::MOUSE_REPORTING_NONE ) {
snprintf( tmp, sizeof( tmp ), "\033[?%dl", frame.last_frame.ds.mouse_reporting_mode );
frame.append( tmp );
}
snprintf( tmp, sizeof( tmp ), "\033[?%dh", f.ds.mouse_reporting_mode );
frame.append( tmp );
}
}
/* has mouse focus mode changed? */
if ( ( !initialized ) || ( f.ds.mouse_focus_event != frame.last_frame.ds.mouse_focus_event ) ) {
frame.append( f.ds.mouse_focus_event ? "\033[?1004h" : "\033[?1004l" );
}
/* has mouse encoding mode changed? */
if ( ( !initialized ) || ( f.ds.mouse_encoding_mode != frame.last_frame.ds.mouse_encoding_mode ) ) {
if ( f.ds.mouse_encoding_mode == DrawState::MOUSE_ENCODING_DEFAULT ) {
frame.append( "\033[?1015l" );
frame.append( "\033[?1006l" );
frame.append( "\033[?1005l" );
} else {
if ( frame.last_frame.ds.mouse_encoding_mode != DrawState::MOUSE_ENCODING_DEFAULT ) {
snprintf( tmp, sizeof( tmp ), "\033[?%dl", frame.last_frame.ds.mouse_encoding_mode );
frame.append( tmp );
}
snprintf( tmp, sizeof( tmp ), "\033[?%dh", f.ds.mouse_encoding_mode );
frame.append( tmp );
}
}
return frame.str;
}
bool Display::put_row( bool initialized,
FrameState& frame,
const Framebuffer& f,
int frame_y,
const Row& old_row,
bool wrap ) const
{
char tmp[64];
int frame_x = 0;
const Row& row = *f.get_row( frame_y );
const Row::cells_type& cells = row.cells;
const Row::cells_type& old_cells = old_row.cells;
/* If we're forced to write the first column because of wrap, go ahead and do so. */
if ( wrap ) {
const Cell& cell = cells.at( 0 );
frame.update_rendition( cell.get_renditions() );
frame.append_cell( cell );
frame_x += cell.get_width();
frame.cursor_x += cell.get_width();
}
/* If rows are the same object, we don't need to do anything at all. */
if ( initialized && &row == &old_row ) {
return false;
}
const bool wrap_this = row.get_wrap();
const int row_width = f.ds.get_width();
int clear_count = 0;
bool wrote_last_cell = false;
Renditions blank_renditions = initial_rendition();
/* iterate for every cell */
while ( frame_x < row_width ) {
const Cell& cell = cells.at( frame_x );
/* Does cell need to be drawn? Skip all this. */
if ( initialized && !clear_count && ( cell == old_cells.at( frame_x ) ) ) {
frame_x += cell.get_width();
continue;
}
/* Slurp up all the empty cells */
if ( cell.empty() ) {
if ( !clear_count ) {
blank_renditions = cell.get_renditions();
}
if ( cell.get_renditions() == blank_renditions ) {
/* Remember run of blank cells */
clear_count++;
frame_x++;
continue;
}
}
/* Clear or write cells within the row (not to end). */
if ( clear_count ) {
/* Move to the right position. */
frame.append_silent_move( frame_y, frame_x - clear_count );
frame.update_rendition( blank_renditions );
bool can_use_erase = has_bce || ( frame.current_rendition == initial_rendition() );
if ( can_use_erase && has_ech && clear_count > 4 ) {
snprintf( tmp, 64, "\033[%dX", clear_count );
frame.append( tmp );
} else {
frame.append( clear_count, ' ' );
frame.cursor_x = frame_x;
}
clear_count = 0;
// If the current character is *another* empty cell in a different rendition,
// we restart counting and continue here
if ( cell.empty() ) {
blank_renditions = cell.get_renditions();
clear_count = 1;
frame_x++;
continue;
}
}
/* Now draw a character cell. */
/* Move to the right position. */
const int cell_width = cell.get_width();
/* If we are about to print the last character in a wrapping row,
trash the cursor position to force explicit positioning. We do
this because our input terminal state may have the cursor on
the autowrap column ("column 81"), but our output terminal
states always snap the cursor to the true last column ("column
80"), and we want to be able to apply the diff to either, for
verification. */
if ( wrap_this && frame_x + cell_width >= row_width ) {
frame.cursor_x = frame.cursor_y = -1;
}
frame.append_silent_move( frame_y, frame_x );
frame.update_rendition( cell.get_renditions() );
frame.append_cell( cell );
frame_x += cell_width;
frame.cursor_x += cell_width;
if ( frame_x >= row_width ) {
wrote_last_cell = true;
}
}
/* End of line. */
/* Clear or write empty cells at EOL. */
if ( clear_count ) {
/* Move to the right position. */
frame.append_silent_move( frame_y, frame_x - clear_count );
frame.update_rendition( blank_renditions );
bool can_use_erase = has_bce || ( frame.current_rendition == initial_rendition() );
if ( can_use_erase && !wrap_this ) {
frame.append( "\033[K" );
} else {
frame.append( clear_count, ' ' );
frame.cursor_x = frame_x;
wrote_last_cell = true;
}
}
if ( !( wrote_last_cell && ( frame_y < f.ds.get_height() - 1 ) ) ) {
return false;
}
/* To hint that a word-select should group the end of one line
with the beginning of the next, we let the real cursor
actually wrap around in cases where it wrapped around for us. */
if ( wrap_this ) {
/* Update our cursor, and ask for wrap on the next row. */
frame.cursor_x = 0;
frame.cursor_y++;
return true;
}
/* Resort to CR/LF and update our cursor. */
frame.append( "\r\n" );
frame.cursor_x = 0;
frame.cursor_y++;
return false;
}
FrameState::FrameState( const Framebuffer& s_last )
: str(), cursor_x( 0 ), cursor_y( 0 ), current_rendition( 0 ), cursor_visible( s_last.ds.cursor_visible ),
last_frame( s_last )
{
/* Preallocate for better performance. Make a guess-- doesn't matter for correctness */
str.reserve( last_frame.ds.get_width() * last_frame.ds.get_height() * 4 );
}
void FrameState::append_silent_move( int y, int x )
{
if ( cursor_x == x && cursor_y == y )
return;
/* turn off cursor if necessary before moving cursor */
if ( cursor_visible ) {
append( "\033[?25l" );
cursor_visible = false;
}
append_move( y, x );
}
void FrameState::append_move( int y, int x )
{
const int last_x = cursor_x;
const int last_y = cursor_y;
cursor_x = x;
cursor_y = y;
// Only optimize if cursor pos is known
if ( last_x != -1 && last_y != -1 ) {
// Can we use CR and/or LF? They're cheap and easier to trace.
if ( x == 0 && y - last_y >= 0 && y - last_y < 5 ) {
if ( last_x != 0 ) {
append( '\r' );
}
append( y - last_y, '\n' );
return;
}
// Backspaces are good too.
if ( y == last_y && x - last_x < 0 && x - last_x > -5 ) {
append( last_x - x, '\b' );
return;
}
// More optimizations are possible.
}
char tmp[64];
snprintf( tmp, 64, "\033[%d;%dH", y + 1, x + 1 );
append( tmp );
}
void FrameState::update_rendition( const Renditions& r, bool force )
{
if ( force || !( current_rendition == r ) ) {
/* print renditions */
append_string( r.sgr() );
current_rendition = r;
}
}
| 17,603
|
C++
|
.cc
| 452
| 33.141593
| 111
| 0.599696
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,571
|
terminaluserinput.cc
|
mobile-shell_mosh/src/terminal/terminaluserinput.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include <cassert>
#include "terminaluserinput.h"
using namespace Terminal;
std::string UserInput::input( const Parser::UserByte* act, bool application_mode_cursor_keys )
{
/* The user will always be in application mode. If stm is not in
application mode, convert user's cursor control function to an
ANSI cursor control sequence */
/* We need to look ahead one byte in the SS3 state to see if
the next byte will be A, B, C, or D (cursor control keys). */
/* This doesn't handle the 8-bit SS3 C1 control, which would be
two octets in UTF-8. Fortunately nobody seems to send this. */
switch ( state ) {
case Ground:
if ( act->c == 0x1b ) { /* ESC */
state = ESC;
}
return std::string( &act->c, 1 );
case ESC:
if ( act->c == 'O' ) { /* ESC O = 7-bit SS3 */
state = SS3;
return std::string();
}
state = Ground;
return std::string( &act->c, 1 );
case SS3:
state = Ground;
if ( ( !application_mode_cursor_keys ) && ( act->c >= 'A' ) && ( act->c <= 'D' ) ) {
char translated_cursor[2] = { '[', act->c };
return std::string( translated_cursor, 2 );
} else {
char original_cursor[2] = { 'O', act->c };
return std::string( original_cursor, 2 );
}
default:
assert( !"unexpected state" );
state = Ground;
return std::string();
}
}
| 2,885
|
C++
|
.cc
| 66
| 38.212121
| 94
| 0.676177
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
10,572
|
terminaldispatcher.cc
|
mobile-shell_mosh/src/terminal/terminaldispatcher.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include <cassert>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "src/terminal/parseraction.h"
#include "src/terminal/terminalframebuffer.h"
#include "terminaldispatcher.h"
using namespace Terminal;
static const size_t MAXIMUM_CLIPBOARD_SIZE = 16 * 1024;
Dispatcher::Dispatcher()
: params(), parsed_params(), parsed( false ), dispatch_chars(), OSC_string(), terminal_to_host()
{}
void Dispatcher::newparamchar( const Parser::Param* act )
{
assert( act->char_present );
assert( ( act->ch == ';' ) || ( ( act->ch >= '0' ) && ( act->ch <= '9' ) ) );
if ( params.length() < 100 ) {
/* enough for 16 five-char params plus 15 semicolons */
params.push_back( act->ch );
}
parsed = false;
}
void Dispatcher::collect( const Parser::Collect* act )
{
assert( act->char_present );
if ( ( dispatch_chars.length() < 8 ) /* never should need more than 2 */
&& ( act->ch <= 255 ) ) { /* ignore non-8-bit */
dispatch_chars.push_back( act->ch );
}
}
void Dispatcher::clear( const Parser::Clear* act __attribute( ( unused ) ) )
{
params.clear();
dispatch_chars.clear();
parsed = false;
}
void Dispatcher::parse_params( void )
{
if ( parsed ) {
return;
}
parsed_params.clear();
const char* str = params.c_str();
const char* segment_begin = str;
while ( 1 ) {
const char* segment_end = strchr( segment_begin, ';' );
if ( segment_end == NULL ) {
break;
}
errno = 0;
char* endptr;
long val = strtol( segment_begin, &endptr, 10 );
if ( endptr == segment_begin ) {
val = -1;
}
if ( val > PARAM_MAX || errno == ERANGE ) {
val = -1;
errno = 0;
}
if ( errno == 0 || segment_begin == endptr ) {
parsed_params.push_back( val );
}
segment_begin = segment_end + 1;
}
/* get last param */
errno = 0;
char* endptr;
long val = strtol( segment_begin, &endptr, 10 );
if ( endptr == segment_begin ) {
val = -1;
}
if ( val > PARAM_MAX || errno == ERANGE ) {
val = -1;
errno = 0;
}
if ( errno == 0 || segment_begin == endptr ) {
parsed_params.push_back( val );
}
parsed = true;
}
int Dispatcher::getparam( size_t N, int defaultval )
{
int ret = defaultval;
if ( !parsed ) {
parse_params();
}
if ( parsed_params.size() > N ) {
ret = parsed_params[N];
}
if ( ret < 1 )
ret = defaultval;
return ret;
}
int Dispatcher::param_count( void )
{
if ( !parsed ) {
parse_params();
}
return parsed_params.size();
}
std::string Dispatcher::str( void )
{
char assum[64];
snprintf( assum, 64, "[dispatch=\"%s\" params=\"%s\"]", dispatch_chars.c_str(), params.c_str() );
return std::string( assum );
}
/* construct on first use to avoid static initialization order crash */
DispatchRegistry& Terminal::get_global_dispatch_registry( void )
{
static DispatchRegistry global_dispatch_registry;
return global_dispatch_registry;
}
static void register_function( Function_Type type, const std::string& dispatch_chars, Function f )
{
switch ( type ) {
case ESCAPE:
get_global_dispatch_registry().escape.insert( dispatch_map_t::value_type( dispatch_chars, f ) );
break;
case CSI:
get_global_dispatch_registry().CSI.insert( dispatch_map_t::value_type( dispatch_chars, f ) );
break;
case CONTROL:
get_global_dispatch_registry().control.insert( dispatch_map_t::value_type( dispatch_chars, f ) );
break;
}
}
Function::Function( Function_Type type,
const std::string& dispatch_chars,
void ( *s_function )( Framebuffer*, Dispatcher* ),
bool s_clears_wrap_state )
: function( s_function ), clears_wrap_state( s_clears_wrap_state )
{
register_function( type, dispatch_chars, *this );
}
void Dispatcher::dispatch( Function_Type type, const Parser::Action* act, Framebuffer* fb )
{
/* add final char to dispatch key */
if ( ( type == ESCAPE ) || ( type == CSI ) ) {
assert( act->char_present );
Parser::Collect act2;
act2.char_present = true;
act2.ch = act->ch;
collect( &act2 );
}
dispatch_map_t* map = NULL;
switch ( type ) {
case ESCAPE:
map = &get_global_dispatch_registry().escape;
break;
case CSI:
map = &get_global_dispatch_registry().CSI;
break;
case CONTROL:
map = &get_global_dispatch_registry().control;
break;
}
std::string key = dispatch_chars;
if ( type == CONTROL ) {
assert( act->ch <= 255 );
char ctrlstr[2] = { (char)act->ch, 0 };
key = std::string( ctrlstr, 1 );
}
dispatch_map_t::const_iterator i = map->find( key );
if ( i == map->end() ) {
/* unknown function */
fb->ds.next_print_will_wrap = false;
return;
}
if ( i->second.clears_wrap_state ) {
fb->ds.next_print_will_wrap = false;
}
i->second.function( fb, this );
}
void Dispatcher::OSC_put( const Parser::OSC_Put* act )
{
assert( act->char_present );
if ( OSC_string.size() < MAXIMUM_CLIPBOARD_SIZE ) {
OSC_string.push_back( act->ch );
}
}
void Dispatcher::OSC_start( const Parser::OSC_Start* act __attribute( ( unused ) ) )
{
OSC_string.clear();
}
bool Dispatcher::operator==( const Dispatcher& x ) const
{
return ( params == x.params ) && ( parsed_params == x.parsed_params ) && ( parsed == x.parsed )
&& ( dispatch_chars == x.dispatch_chars ) && ( OSC_string == x.OSC_string )
&& ( terminal_to_host == x.terminal_to_host );
}
| 6,981
|
C++
|
.cc
| 217
| 28.230415
| 103
| 0.652685
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,573
|
terminal.cc
|
mobile-shell_mosh/src/terminal/terminal.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <typeinfo>
#include <unistd.h>
#include "src/terminal/terminal.h"
using namespace Terminal;
Emulator::Emulator( size_t s_width, size_t s_height ) : fb( s_width, s_height ), dispatch(), user() {}
std::string Emulator::read_octets_to_host( void )
{
std::string ret = dispatch.terminal_to_host;
dispatch.terminal_to_host.clear();
return ret;
}
void Emulator::execute( const Parser::Execute* act )
{
dispatch.dispatch( CONTROL, act, &fb );
}
void Emulator::print( const Parser::Print* act )
{
assert( act->char_present );
const wchar_t ch = act->ch;
/*
* Check for printing ISO 8859-1 first, it's a cheap way to detect
* some common narrow characters.
*/
const int chwidth = ch == L'\0' ? -1 : ( Cell::isprint_iso8859_1( ch ) ? 1 : wcwidth( ch ) );
Cell* this_cell = fb.get_mutable_cell();
switch ( chwidth ) {
case 1: /* normal character */
case 2: /* wide character */
if ( fb.ds.auto_wrap_mode && fb.ds.next_print_will_wrap ) {
fb.get_mutable_row( -1 )->set_wrap( true );
fb.ds.move_col( 0 );
fb.move_rows_autoscroll( 1 );
this_cell = NULL;
} else if ( fb.ds.auto_wrap_mode && ( chwidth == 2 )
&& ( fb.ds.get_cursor_col() == fb.ds.get_width() - 1 ) ) {
/* wrap 2-cell chars if no room, even without will-wrap flag */
fb.reset_cell( this_cell );
fb.get_mutable_row( -1 )->set_wrap( false );
/* There doesn't seem to be a consistent way to get the
downstream terminal emulator to set the wrap-around
copy-and-paste flag on a row that ends with an empty cell
because a wide char was wrapped to the next line. */
fb.ds.move_col( 0 );
fb.move_rows_autoscroll( 1 );
this_cell = NULL;
}
if ( fb.ds.insert_mode ) {
for ( int i = 0; i < chwidth; i++ ) {
fb.insert_cell( fb.ds.get_cursor_row(), fb.ds.get_cursor_col() );
}
this_cell = NULL;
}
if ( !this_cell ) {
this_cell = fb.get_mutable_cell();
}
fb.reset_cell( this_cell );
this_cell->append( ch );
this_cell->set_wide( chwidth == 2 ); /* chwidth had better be 1 or 2 here */
fb.apply_renditions_to_cell( this_cell );
if ( chwidth == 2 && fb.ds.get_cursor_col() + 1 < fb.ds.get_width() ) { /* erase overlapped cell */
fb.reset_cell( fb.get_mutable_cell( fb.ds.get_cursor_row(), fb.ds.get_cursor_col() + 1 ) );
}
fb.ds.move_col( chwidth, true, true );
break;
case 0: /* combining character */
{
Cell* combining_cell = fb.get_combining_cell(); /* can be null if we were resized */
if ( combining_cell == NULL ) { /* character is now offscreen */
break;
}
if ( combining_cell->empty() ) {
/* cell starts with combining character */
/* ... but isn't necessarily the target for a new
base character [e.g. start of line], if the
combining character has been cleared with
a sequence like ED ("J") or EL ("K") */
assert( !combining_cell->get_wide() );
combining_cell->set_fallback( true );
fb.ds.move_col( 1, true, true );
}
if ( !combining_cell->full() ) {
combining_cell->append( ch );
}
} break;
case -1: /* unprintable character */
break;
default:
assert( !"unexpected character width from wcwidth()" );
break;
}
}
void Emulator::CSI_dispatch( const Parser::CSI_Dispatch* act )
{
dispatch.dispatch( CSI, act, &fb );
}
void Emulator::OSC_end( const Parser::OSC_End* act )
{
dispatch.OSC_dispatch( act, &fb );
}
void Emulator::Esc_dispatch( const Parser::Esc_Dispatch* act )
{
/* handle 7-bit ESC-encoding of C1 control characters */
if ( ( dispatch.get_dispatch_chars().size() == 0 ) && ( 0x40 <= act->ch ) && ( act->ch <= 0x5F ) ) {
Parser::Esc_Dispatch act2 = *act;
act2.ch += 0x40;
dispatch.dispatch( CONTROL, &act2, &fb );
} else {
dispatch.dispatch( ESCAPE, act, &fb );
}
}
void Emulator::resize( size_t s_width, size_t s_height )
{
fb.resize( s_width, s_height );
}
bool Emulator::operator==( Emulator const& x ) const
{
/* dispatcher and user are irrelevant for us */
return fb == x.fb;
}
| 5,830
|
C++
|
.cc
| 148
| 34.027027
| 105
| 0.639483
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,574
|
parseraction.cc
|
mobile-shell_mosh/src/terminal/parseraction.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include <cstdio>
#include <cwctype>
#include "src/terminal/parseraction.h"
#include "src/terminal/terminal.h"
using namespace Parser;
void Print::act_on_terminal( Terminal::Emulator* emu ) const
{
emu->print( this );
}
void Execute::act_on_terminal( Terminal::Emulator* emu ) const
{
emu->execute( this );
}
void Clear::act_on_terminal( Terminal::Emulator* emu ) const
{
emu->dispatch.clear( this );
}
void Param::act_on_terminal( Terminal::Emulator* emu ) const
{
emu->dispatch.newparamchar( this );
}
void Collect::act_on_terminal( Terminal::Emulator* emu ) const
{
emu->dispatch.collect( this );
}
void CSI_Dispatch::act_on_terminal( Terminal::Emulator* emu ) const
{
emu->CSI_dispatch( this );
}
void Esc_Dispatch::act_on_terminal( Terminal::Emulator* emu ) const
{
emu->Esc_dispatch( this );
}
void OSC_Put::act_on_terminal( Terminal::Emulator* emu ) const
{
emu->dispatch.OSC_put( this );
}
void OSC_Start::act_on_terminal( Terminal::Emulator* emu ) const
{
emu->dispatch.OSC_start( this );
}
void OSC_End::act_on_terminal( Terminal::Emulator* emu ) const
{
emu->OSC_end( this );
}
void UserByte::act_on_terminal( Terminal::Emulator* emu ) const
{
emu->dispatch.terminal_to_host.append( emu->user.input( this, emu->fb.ds.application_mode_cursor_keys ) );
}
void Resize::act_on_terminal( Terminal::Emulator* emu ) const
{
emu->resize( width, height );
}
| 2,868
|
C++
|
.cc
| 79
| 33.531646
| 108
| 0.744673
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,575
|
parserstate.cc
|
mobile-shell_mosh/src/terminal/parserstate.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include <memory>
#include "parserstate.h"
#include "parserstatefamily.h"
using namespace Parser;
Transition State::anywhere_rule( wchar_t ch ) const
{
if ( ( ch == 0x18 ) || ( ch == 0x1A ) || ( ( 0x80 <= ch ) && ( ch <= 0x8F ) )
|| ( ( 0x91 <= ch ) && ( ch <= 0x97 ) ) || ( ch == 0x99 ) || ( ch == 0x9A ) ) {
return Transition( std::make_shared<Execute>(), &family->s_Ground );
} else if ( ch == 0x9C ) {
return Transition( &family->s_Ground );
} else if ( ch == 0x1B ) {
return Transition( &family->s_Escape );
} else if ( ( ch == 0x98 ) || ( ch == 0x9E ) || ( ch == 0x9F ) ) {
return Transition( &family->s_SOS_PM_APC_String );
} else if ( ch == 0x90 ) {
return Transition( &family->s_DCS_Entry );
} else if ( ch == 0x9D ) {
return Transition( &family->s_OSC_String );
} else if ( ch == 0x9B ) {
return Transition( &family->s_CSI_Entry );
}
return Transition( (State*)NULL, ActionPointer() ); /* don't allocate an Ignore action */
}
Transition State::input( wchar_t ch ) const
{
/* Check for immediate transitions. */
Transition anywhere = anywhere_rule( ch );
if ( anywhere.next_state ) {
anywhere.action->char_present = true;
anywhere.action->ch = ch;
return anywhere;
}
/* Normal X.364 state machine. */
/* Parse high Unicode codepoints like 'A'. */
Transition ret = this->input_state_rule( ch >= 0xA0 ? 0x41 : ch );
ret.action->char_present = true;
ret.action->ch = ch;
return ret;
}
static bool C0_prime( wchar_t ch )
{
return ( ch <= 0x17 ) || ( ch == 0x19 ) || ( ( 0x1C <= ch ) && ( ch <= 0x1F ) );
}
static bool GLGR( wchar_t ch )
{
return ( ( 0x20 <= ch ) && ( ch <= 0x7F ) ) /* GL area */
|| ( ( 0xA0 <= ch ) && ( ch <= 0xFF ) ); /* GR area */
}
Transition Ground::input_state_rule( wchar_t ch ) const
{
if ( C0_prime( ch ) ) {
return Transition( std::make_shared<Execute>() );
}
if ( GLGR( ch ) ) {
return Transition( std::make_shared<Print>() );
}
return Transition();
}
ActionPointer Escape::enter( void ) const
{
return std::make_shared<Clear>();
}
Transition Escape::input_state_rule( wchar_t ch ) const
{
if ( C0_prime( ch ) ) {
return Transition( std::make_shared<Execute>() );
}
if ( ( 0x20 <= ch ) && ( ch <= 0x2F ) ) {
return Transition( std::make_shared<Collect>(), &family->s_Escape_Intermediate );
}
if ( ( ( 0x30 <= ch ) && ( ch <= 0x4F ) ) || ( ( 0x51 <= ch ) && ( ch <= 0x57 ) ) || ( ch == 0x59 )
|| ( ch == 0x5A ) || ( ch == 0x5C ) || ( ( 0x60 <= ch ) && ( ch <= 0x7E ) ) ) {
return Transition( std::make_shared<Esc_Dispatch>(), &family->s_Ground );
}
if ( ch == 0x5B ) {
return Transition( &family->s_CSI_Entry );
}
if ( ch == 0x5D ) {
return Transition( &family->s_OSC_String );
}
if ( ch == 0x50 ) {
return Transition( &family->s_DCS_Entry );
}
if ( ( ch == 0x58 ) || ( ch == 0x5E ) || ( ch == 0x5F ) ) {
return Transition( &family->s_SOS_PM_APC_String );
}
return Transition();
}
Transition Escape_Intermediate::input_state_rule( wchar_t ch ) const
{
if ( C0_prime( ch ) ) {
return Transition( std::make_shared<Execute>() );
}
if ( ( 0x20 <= ch ) && ( ch <= 0x2F ) ) {
return Transition( std::make_shared<Collect>() );
}
if ( ( 0x30 <= ch ) && ( ch <= 0x7E ) ) {
return Transition( std::make_shared<Esc_Dispatch>(), &family->s_Ground );
}
return Transition();
}
ActionPointer CSI_Entry::enter( void ) const
{
return std::make_shared<Clear>();
}
Transition CSI_Entry::input_state_rule( wchar_t ch ) const
{
if ( C0_prime( ch ) ) {
return Transition( std::make_shared<Execute>() );
}
if ( ( 0x40 <= ch ) && ( ch <= 0x7E ) ) {
return Transition( std::make_shared<CSI_Dispatch>(), &family->s_Ground );
}
if ( ( ( 0x30 <= ch ) && ( ch <= 0x39 ) ) || ( ch == 0x3B ) ) {
return Transition( std::make_shared<Param>(), &family->s_CSI_Param );
}
if ( ( 0x3C <= ch ) && ( ch <= 0x3F ) ) {
return Transition( std::make_shared<Collect>(), &family->s_CSI_Param );
}
if ( ch == 0x3A ) {
return Transition( &family->s_CSI_Ignore );
}
if ( ( 0x20 <= ch ) && ( ch <= 0x2F ) ) {
return Transition( std::make_shared<Collect>(), &family->s_CSI_Intermediate );
}
return Transition();
}
Transition CSI_Param::input_state_rule( wchar_t ch ) const
{
if ( C0_prime( ch ) ) {
return Transition( std::make_shared<Execute>() );
}
if ( ( ( 0x30 <= ch ) && ( ch <= 0x39 ) ) || ( ch == 0x3B ) ) {
return Transition( std::make_shared<Param>() );
}
if ( ( ch == 0x3A ) || ( ( 0x3C <= ch ) && ( ch <= 0x3F ) ) ) {
return Transition( &family->s_CSI_Ignore );
}
if ( ( 0x20 <= ch ) && ( ch <= 0x2F ) ) {
return Transition( std::make_shared<Collect>(), &family->s_CSI_Intermediate );
}
if ( ( 0x40 <= ch ) && ( ch <= 0x7E ) ) {
return Transition( std::make_shared<CSI_Dispatch>(), &family->s_Ground );
}
return Transition();
}
Transition CSI_Intermediate::input_state_rule( wchar_t ch ) const
{
if ( C0_prime( ch ) ) {
return Transition( std::make_shared<Execute>() );
}
if ( ( 0x20 <= ch ) && ( ch <= 0x2F ) ) {
return Transition( std::make_shared<Collect>() );
}
if ( ( 0x40 <= ch ) && ( ch <= 0x7E ) ) {
return Transition( std::make_shared<CSI_Dispatch>(), &family->s_Ground );
}
if ( ( 0x30 <= ch ) && ( ch <= 0x3F ) ) {
return Transition( &family->s_CSI_Ignore );
}
return Transition();
}
Transition CSI_Ignore::input_state_rule( wchar_t ch ) const
{
if ( C0_prime( ch ) ) {
return Transition( std::make_shared<Execute>() );
}
if ( ( 0x40 <= ch ) && ( ch <= 0x7E ) ) {
return Transition( &family->s_Ground );
}
return Transition();
}
ActionPointer DCS_Entry::enter( void ) const
{
return std::make_shared<Clear>();
}
Transition DCS_Entry::input_state_rule( wchar_t ch ) const
{
if ( ( 0x20 <= ch ) && ( ch <= 0x2F ) ) {
return Transition( std::make_shared<Collect>(), &family->s_DCS_Intermediate );
}
if ( ch == 0x3A ) {
return Transition( &family->s_DCS_Ignore );
}
if ( ( ( 0x30 <= ch ) && ( ch <= 0x39 ) ) || ( ch == 0x3B ) ) {
return Transition( std::make_shared<Param>(), &family->s_DCS_Param );
}
if ( ( 0x3C <= ch ) && ( ch <= 0x3F ) ) {
return Transition( std::make_shared<Collect>(), &family->s_DCS_Param );
}
if ( ( 0x40 <= ch ) && ( ch <= 0x7E ) ) {
return Transition( &family->s_DCS_Passthrough );
}
return Transition();
}
Transition DCS_Param::input_state_rule( wchar_t ch ) const
{
if ( ( ( 0x30 <= ch ) && ( ch <= 0x39 ) ) || ( ch == 0x3B ) ) {
return Transition( std::make_shared<Param>() );
}
if ( ( ch == 0x3A ) || ( ( 0x3C <= ch ) && ( ch <= 0x3F ) ) ) {
return Transition( &family->s_DCS_Ignore );
}
if ( ( 0x20 <= ch ) && ( ch <= 0x2F ) ) {
return Transition( std::make_shared<Collect>(), &family->s_DCS_Intermediate );
}
if ( ( 0x40 <= ch ) && ( ch <= 0x7E ) ) {
return Transition( &family->s_DCS_Passthrough );
}
return Transition();
}
Transition DCS_Intermediate::input_state_rule( wchar_t ch ) const
{
if ( ( 0x20 <= ch ) && ( ch <= 0x2F ) ) {
return Transition( std::make_shared<Collect>() );
}
if ( ( 0x40 <= ch ) && ( ch <= 0x7E ) ) {
return Transition( &family->s_DCS_Passthrough );
}
if ( ( 0x30 <= ch ) && ( ch <= 0x3F ) ) {
return Transition( &family->s_DCS_Ignore );
}
return Transition();
}
ActionPointer DCS_Passthrough::enter( void ) const
{
return std::make_shared<Hook>();
}
ActionPointer DCS_Passthrough::exit( void ) const
{
return std::make_shared<Unhook>();
}
Transition DCS_Passthrough::input_state_rule( wchar_t ch ) const
{
if ( C0_prime( ch ) || ( ( 0x20 <= ch ) && ( ch <= 0x7E ) ) ) {
return Transition( std::make_shared<Put>() );
}
if ( ch == 0x9C ) {
return Transition( &family->s_Ground );
}
return Transition();
}
Transition DCS_Ignore::input_state_rule( wchar_t ch ) const
{
if ( ch == 0x9C ) {
return Transition( &family->s_Ground );
}
return Transition();
}
ActionPointer OSC_String::enter( void ) const
{
return std::make_shared<OSC_Start>();
}
ActionPointer OSC_String::exit( void ) const
{
return std::make_shared<OSC_End>();
}
Transition OSC_String::input_state_rule( wchar_t ch ) const
{
if ( ( 0x20 <= ch ) && ( ch <= 0x7F ) ) {
return Transition( std::make_shared<OSC_Put>() );
}
if ( ( ch == 0x9C ) || ( ch == 0x07 ) ) { /* 0x07 is xterm non-ANSI variant */
return Transition( &family->s_Ground );
}
return Transition();
}
Transition SOS_PM_APC_String::input_state_rule( wchar_t ch ) const
{
if ( ch == 0x9C ) {
return Transition( &family->s_Ground );
}
return Transition();
}
| 10,213
|
C++
|
.cc
| 301
| 30.604651
| 101
| 0.606551
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,576
|
parser.cc
|
mobile-shell_mosh/src/terminal/parser.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include <cassert>
#include <cerrno>
#include <cstdint>
#include <cwchar>
#include <typeinfo>
#include "src/terminal/parser.h"
const Parser::StateFamily Parser::family;
static void append_or_delete( Parser::ActionPointer act, Parser::Actions& vec )
{
assert( act );
if ( !act->ignore() ) {
vec.push_back( act );
}
}
void Parser::Parser::input( wchar_t ch, Actions& ret )
{
Transition tx = state->input( ch );
if ( tx.next_state != NULL ) {
append_or_delete( state->exit(), ret );
}
append_or_delete( tx.action, ret );
if ( tx.next_state != NULL ) {
append_or_delete( tx.next_state->enter(), ret );
state = tx.next_state;
}
}
Parser::UTF8Parser::UTF8Parser() : parser(), buf_len( 0 )
{
assert( BUF_SIZE >= (size_t)MB_CUR_MAX );
buf[0] = '\0';
}
void Parser::UTF8Parser::input( char c, Actions& ret )
{
assert( buf_len < BUF_SIZE );
/* 1-byte UTF-8 character, aka ASCII? Cheat. */
if ( buf_len == 0 && static_cast<unsigned char>( c ) <= 0x7f ) {
parser.input( static_cast<wchar_t>( c ), ret );
return;
}
buf[buf_len++] = c;
/* This function will only work in a UTF-8 locale. */
wchar_t pwc;
mbstate_t ps = mbstate_t();
size_t total_bytes_parsed = 0;
size_t orig_buf_len = buf_len;
/* this routine is somewhat complicated in order to comply with
Unicode 6.0, section 3.9, "Best Practices for using U+FFFD" */
while ( total_bytes_parsed != orig_buf_len ) {
assert( total_bytes_parsed < orig_buf_len );
assert( buf_len > 0 );
size_t bytes_parsed = mbrtowc( &pwc, buf, buf_len, &ps );
/* this returns 0 when n = 0! */
if ( bytes_parsed == 0 ) {
/* character was NUL, accept and clear buffer */
assert( buf_len == 1 );
buf_len = 0;
pwc = L'\0';
bytes_parsed = 1;
} else if ( bytes_parsed == (size_t)-1 ) {
/* invalid sequence, use replacement character and try again with last char */
assert( errno == EILSEQ );
if ( buf_len > 1 ) {
buf[0] = buf[buf_len - 1];
bytes_parsed = buf_len - 1;
buf_len = 1;
} else {
buf_len = 0;
bytes_parsed = 1;
}
pwc = (wchar_t)0xFFFD;
} else if ( bytes_parsed == (size_t)-2 ) {
/* can't parse incomplete multibyte character */
total_bytes_parsed += buf_len;
continue;
} else {
/* parsed into pwc, accept */
assert( bytes_parsed <= buf_len );
memmove( buf, buf + bytes_parsed, buf_len - bytes_parsed );
buf_len = buf_len - bytes_parsed;
}
/* Cast to unsigned for checks, because some
platforms (e.g. ARM) use uint32_t as wchar_t,
causing compiler warning on "pwc > 0" check. */
const uint32_t pwcheck = pwc;
if ( pwcheck > 0x10FFFF ) { /* outside Unicode range */
pwc = (wchar_t)0xFFFD;
}
if ( ( pwcheck >= 0xD800 ) && ( pwcheck <= 0xDFFF ) ) { /* surrogate code point */
/*
OS X unfortunately allows these sequences without EILSEQ, but
they are ill-formed UTF-8 and we shouldn't repeat them to the
user's terminal.
*/
pwc = (wchar_t)0xFFFD;
}
parser.input( pwc, ret );
total_bytes_parsed += bytes_parsed;
}
}
Parser::Parser::Parser( const Parser& other ) : state( other.state ) {}
Parser::Parser& Parser::Parser::operator=( const Parser& other )
{
state = other.state;
return *this;
}
| 4,864
|
C++
|
.cc
| 131
| 32.419847
| 86
| 0.653977
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,577
|
terminalframebuffer.cc
|
mobile-shell_mosh/src/terminal/terminalframebuffer.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include "src/terminal/terminalframebuffer.h"
using namespace Terminal;
Cell::Cell( color_type background_color )
: contents(), renditions( background_color ), wide( false ), fallback( false ), wrap( false )
{}
void Cell::reset( color_type background_color )
{
contents.clear();
renditions = Renditions( background_color );
wide = false;
fallback = false;
wrap = false;
}
void DrawState::reinitialize_tabs( unsigned int start )
{
assert( default_tabs );
for ( unsigned int i = start; i < tabs.size(); i++ ) {
tabs[i] = ( ( i % 8 ) == 0 );
}
}
DrawState::DrawState( int s_width, int s_height )
: width( s_width ), height( s_height ), cursor_col( 0 ), cursor_row( 0 ), combining_char_col( 0 ),
combining_char_row( 0 ), default_tabs( true ), tabs( s_width ), scrolling_region_top_row( 0 ),
scrolling_region_bottom_row( height - 1 ), renditions( 0 ), save(), next_print_will_wrap( false ),
origin_mode( false ), auto_wrap_mode( true ), insert_mode( false ), cursor_visible( true ),
reverse_video( false ), bracketed_paste( false ), mouse_reporting_mode( MOUSE_REPORTING_NONE ),
mouse_focus_event( false ), mouse_alternate_scroll( false ), mouse_encoding_mode( MOUSE_ENCODING_DEFAULT ),
application_mode_cursor_keys( false )
{
reinitialize_tabs( 0 );
}
Framebuffer::Framebuffer( int s_width, int s_height )
: rows(), icon_name(), window_title(), clipboard(), bell_count( 0 ), title_initialized( false ),
ds( s_width, s_height )
{
assert( s_height > 0 );
assert( s_width > 0 );
const size_t w = s_width;
const color_type c = 0;
rows = rows_type( s_height, row_pointer( std::make_shared<Row>( w, c ) ) );
}
Framebuffer::Framebuffer( const Framebuffer& other )
: rows( other.rows ), icon_name( other.icon_name ), window_title( other.window_title ),
clipboard( other.clipboard ), bell_count( other.bell_count ), title_initialized( other.title_initialized ),
ds( other.ds )
{}
Framebuffer& Framebuffer::operator=( const Framebuffer& other )
{
if ( this != &other ) {
rows = other.rows;
icon_name = other.icon_name;
window_title = other.window_title;
clipboard = other.clipboard;
bell_count = other.bell_count;
title_initialized = other.title_initialized;
ds = other.ds;
}
return *this;
}
void Framebuffer::scroll( int N )
{
if ( N >= 0 ) {
delete_line( ds.get_scrolling_region_top_row(), N );
} else {
insert_line( ds.get_scrolling_region_top_row(), -N );
}
}
void DrawState::new_grapheme( void )
{
combining_char_col = cursor_col;
combining_char_row = cursor_row;
}
void DrawState::snap_cursor_to_border( void )
{
if ( cursor_row < limit_top() )
cursor_row = limit_top();
if ( cursor_row > limit_bottom() )
cursor_row = limit_bottom();
if ( cursor_col < 0 )
cursor_col = 0;
if ( cursor_col >= width )
cursor_col = width - 1;
}
void DrawState::move_row( int N, bool relative )
{
if ( relative ) {
cursor_row += N;
} else {
cursor_row = N + limit_top();
}
snap_cursor_to_border();
new_grapheme();
next_print_will_wrap = false;
}
void DrawState::move_col( int N, bool relative, bool implicit )
{
if ( implicit ) {
new_grapheme();
}
if ( relative ) {
cursor_col += N;
} else {
cursor_col = N;
}
if ( implicit ) {
next_print_will_wrap = ( cursor_col >= width );
}
snap_cursor_to_border();
if ( !implicit ) {
new_grapheme();
next_print_will_wrap = false;
}
}
void Framebuffer::move_rows_autoscroll( int rows )
{
/* don't scroll if outside the scrolling region */
if ( ( ds.get_cursor_row() < ds.get_scrolling_region_top_row() )
|| ( ds.get_cursor_row() > ds.get_scrolling_region_bottom_row() ) ) {
ds.move_row( rows, true );
return;
}
if ( ds.get_cursor_row() + rows > ds.get_scrolling_region_bottom_row() ) {
int N = ds.get_cursor_row() + rows - ds.get_scrolling_region_bottom_row();
scroll( N );
ds.move_row( -N, true );
} else if ( ds.get_cursor_row() + rows < ds.get_scrolling_region_top_row() ) {
int N = ds.get_cursor_row() + rows - ds.get_scrolling_region_top_row();
scroll( N );
ds.move_row( -N, true );
}
ds.move_row( rows, true );
}
Cell* Framebuffer::get_combining_cell( void )
{
if ( ( ds.get_combining_char_col() < 0 ) || ( ds.get_combining_char_row() < 0 )
|| ( ds.get_combining_char_col() >= ds.get_width() )
|| ( ds.get_combining_char_row() >= ds.get_height() ) ) {
return NULL;
} /* can happen if a resize came in between */
return get_mutable_cell( ds.get_combining_char_row(), ds.get_combining_char_col() );
}
void DrawState::set_tab( void )
{
tabs[cursor_col] = true;
}
void DrawState::clear_tab( int col )
{
tabs[col] = false;
}
int DrawState::get_next_tab( int count ) const
{
if ( count >= 0 ) {
for ( int i = cursor_col + 1; i < width; i++ ) {
if ( tabs[i] && --count == 0 ) {
return i;
}
}
return -1;
}
for ( int i = cursor_col - 1; i > 0; i-- ) {
if ( tabs[i] && ++count == 0 ) {
return i;
}
}
return 0;
}
void DrawState::set_scrolling_region( int top, int bottom )
{
if ( height < 1 ) {
return;
}
scrolling_region_top_row = top;
scrolling_region_bottom_row = bottom;
if ( scrolling_region_top_row < 0 )
scrolling_region_top_row = 0;
if ( scrolling_region_bottom_row >= height )
scrolling_region_bottom_row = height - 1;
if ( scrolling_region_bottom_row < scrolling_region_top_row )
scrolling_region_bottom_row = scrolling_region_top_row;
/* real rule requires TWO-line scrolling region */
if ( origin_mode ) {
snap_cursor_to_border();
new_grapheme();
}
}
int DrawState::limit_top( void ) const
{
return origin_mode ? scrolling_region_top_row : 0;
}
int DrawState::limit_bottom( void ) const
{
return origin_mode ? scrolling_region_bottom_row : height - 1;
}
void Framebuffer::apply_renditions_to_cell( Cell* cell )
{
if ( !cell ) {
cell = get_mutable_cell();
}
cell->set_renditions( ds.get_renditions() );
}
SavedCursor::SavedCursor()
: cursor_col( 0 ), cursor_row( 0 ), renditions( 0 ), auto_wrap_mode( true ), origin_mode( false )
{}
void DrawState::save_cursor( void )
{
save.cursor_col = cursor_col;
save.cursor_row = cursor_row;
save.renditions = renditions;
save.auto_wrap_mode = auto_wrap_mode;
save.origin_mode = origin_mode;
}
void DrawState::restore_cursor( void )
{
cursor_col = save.cursor_col;
cursor_row = save.cursor_row;
renditions = save.renditions;
auto_wrap_mode = save.auto_wrap_mode;
origin_mode = save.origin_mode;
snap_cursor_to_border(); /* we could have resized in between */
new_grapheme();
}
void Framebuffer::insert_line( int before_row, int count )
{
if ( ( before_row < ds.get_scrolling_region_top_row() )
|| ( before_row > ds.get_scrolling_region_bottom_row() + 1 ) ) {
return;
}
int scroll = ds.get_scrolling_region_bottom_row() + 1 - before_row;
if ( count < scroll ) {
scroll = count;
}
if ( scroll == 0 ) {
return;
}
// delete old rows
rows_type::iterator start = rows.begin() + ds.get_scrolling_region_bottom_row() + 1 - scroll;
rows.erase( start, start + scroll );
// insert new rows
start = rows.begin() + before_row;
rows.insert( start, scroll, newrow() );
}
void Framebuffer::delete_line( int row, int count )
{
if ( ( row < ds.get_scrolling_region_top_row() ) || ( row > ds.get_scrolling_region_bottom_row() ) ) {
return;
}
int scroll = ds.get_scrolling_region_bottom_row() + 1 - row;
if ( count < scroll ) {
scroll = count;
}
if ( scroll == 0 ) {
return;
}
// delete old rows
rows_type::iterator start = rows.begin() + row;
rows.erase( start, start + scroll );
// insert a block of dummy rows
start = rows.begin() + ds.get_scrolling_region_bottom_row() + 1 - scroll;
rows.insert( start, scroll, newrow() );
}
Row::Row( const size_t s_width, const color_type background_color )
: cells( s_width, Cell( background_color ) ), gen( get_gen() )
{}
uint64_t Row::get_gen() const
{
static uint64_t gen_counter = 0;
return gen_counter++;
}
void Row::insert_cell( int col, color_type background_color )
{
cells.insert( cells.begin() + col, Cell( background_color ) );
cells.pop_back();
}
void Row::delete_cell( int col, color_type background_color )
{
cells.push_back( Cell( background_color ) );
cells.erase( cells.begin() + col );
}
void Framebuffer::insert_cell( int row, int col )
{
get_mutable_row( row )->insert_cell( col, ds.get_background_rendition() );
}
void Framebuffer::delete_cell( int row, int col )
{
get_mutable_row( row )->delete_cell( col, ds.get_background_rendition() );
}
void Framebuffer::reset( void )
{
int width = ds.get_width(), height = ds.get_height();
ds = DrawState( width, height );
rows = rows_type( height, newrow() );
window_title.clear();
clipboard.clear();
/* do not reset bell_count */
}
void Framebuffer::soft_reset( void )
{
ds.insert_mode = false;
ds.origin_mode = false;
ds.cursor_visible = true; /* per xterm and gnome-terminal */
ds.application_mode_cursor_keys = false;
ds.set_scrolling_region( 0, ds.get_height() - 1 );
ds.add_rendition( 0 );
ds.clear_saved_cursor();
}
void Framebuffer::resize( int s_width, int s_height )
{
assert( s_width > 0 );
assert( s_height > 0 );
int oldheight = ds.get_height();
int oldwidth = ds.get_width();
ds.resize( s_width, s_height );
row_pointer blankrow( newrow() );
if ( oldheight != s_height ) {
rows.resize( s_height, blankrow );
}
if ( oldwidth == s_width ) {
return;
}
for ( rows_type::iterator i = rows.begin(); i != rows.end() && *i != blankrow; i++ ) {
*i = std::make_shared<Row>( **i );
( *i )->set_wrap( false );
( *i )->cells.resize( s_width, Cell( ds.get_background_rendition() ) );
}
}
void DrawState::resize( int s_width, int s_height )
{
if ( ( width != s_width ) || ( height != s_height ) ) {
/* reset entire scrolling region on any resize */
/* xterm and rxvt-unicode do this. gnome-terminal only
resets scrolling region if it has to become smaller in resize */
scrolling_region_top_row = 0;
scrolling_region_bottom_row = s_height - 1;
}
tabs.resize( s_width );
if ( default_tabs ) {
reinitialize_tabs( width );
}
width = s_width;
height = s_height;
snap_cursor_to_border();
/* saved cursor will be snapped to border on restore */
/* invalidate combining char cell if necessary */
if ( ( combining_char_col >= width ) || ( combining_char_row >= height ) ) {
combining_char_col = combining_char_row = -1;
}
}
Renditions::Renditions( color_type s_background )
: foreground_color( 0 ), background_color( s_background ), attributes( 0 )
{}
/* This routine cannot be used to set a color beyond the 16-color set. */
void Renditions::set_rendition( color_type num )
{
if ( num == 0 ) {
clear_attributes();
foreground_color = background_color = 0;
return;
}
if ( num == 39 ) {
foreground_color = 0;
return;
} else if ( num == 49 ) {
background_color = 0;
return;
}
if ( ( 30 <= num ) && ( num <= 37 ) ) { /* foreground color in 8-color set */
foreground_color = num;
return;
} else if ( ( 40 <= num ) && ( num <= 47 ) ) { /* background color in 8-color set */
background_color = num;
return;
} else if ( ( 90 <= num ) && ( num <= 97 ) ) { /* foreground color in 16-color set */
foreground_color = num - 90 + 38;
return;
} else if ( ( 100 <= num ) && ( num <= 107 ) ) { /* background color in 16-color set */
background_color = num - 100 + 48;
return;
}
bool value = num < 9;
switch ( num ) {
case 1:
case 22:
set_attribute( bold, value );
break;
case 3:
case 23:
set_attribute( italic, value );
break;
case 4:
case 24:
set_attribute( underlined, value );
break;
case 5:
case 25:
set_attribute( blink, value );
break;
case 7:
case 27:
set_attribute( inverse, value );
break;
case 8:
case 28:
set_attribute( invisible, value );
break;
default:
break; /* ignore unknown rendition */
}
}
void Renditions::set_foreground_color( int num )
{
if ( ( 0 <= num ) && ( num <= 255 ) ) {
foreground_color = 30 + num;
} else if ( is_true_color( num ) ) {
foreground_color = num;
}
}
void Renditions::set_background_color( int num )
{
if ( ( 0 <= num ) && ( num <= 255 ) ) {
background_color = 40 + num;
} else if ( is_true_color( num ) ) {
background_color = num;
}
}
std::string Renditions::sgr( void ) const
{
std::string ret;
char col[64];
ret.append( "\033[0" );
if ( get_attribute( bold ) )
ret.append( ";1" );
if ( get_attribute( italic ) )
ret.append( ";3" );
if ( get_attribute( underlined ) )
ret.append( ";4" );
if ( get_attribute( blink ) )
ret.append( ";5" );
if ( get_attribute( inverse ) )
ret.append( ";7" );
if ( get_attribute( invisible ) )
ret.append( ";8" );
if ( foreground_color ) {
// Since foreground_color is a 25-bit field, it is promoted to an int when
// manipulated. (See [conv.prom] in various C++ standards, e.g.,
// https://timsong-cpp.github.io/cppwp/n4659/conv.prom#5.) The correct
// printf format specifier is thus %d.
if ( is_true_color( foreground_color ) ) {
snprintf( col,
sizeof( col ),
";38;2;%d;%d;%d",
( foreground_color >> 16 ) & 0xff,
( foreground_color >> 8 ) & 0xff,
foreground_color & 0xff );
} else if ( foreground_color > 37 ) { /* use 256-color set */
snprintf( col, sizeof( col ), ";38;5;%d", foreground_color - 30 );
} else { /* ANSI foreground color */
// Unfortunately, some versions of GCC (notably including GCC 9.3) give
// -Wformat warnings when relying on [conv.prom] to promote
// foreground_color in calls to printf. Explicitly promote it to silence
// the warning.
int fg = foreground_color;
snprintf( col, sizeof( col ), ";%d", fg );
}
ret.append( col );
}
if ( background_color ) {
// See comment above about bit-field promotion; it applies here as well.
if ( is_true_color( background_color ) ) {
snprintf( col,
sizeof( col ),
";48;2;%d;%d;%d",
( background_color >> 16 ) & 0xff,
( background_color >> 8 ) & 0xff,
background_color & 0xff );
} else if ( background_color > 47 ) { /* use 256-color set */
snprintf( col, sizeof( col ), ";48;5;%d", background_color - 40 );
} else { /* ANSI background color */
// See comment above about explicit promotion; it applies here as well.
int bg = background_color;
snprintf( col, sizeof( col ), ";%d", bg );
}
ret.append( col );
}
ret.append( "m" );
return ret;
}
void Row::reset( color_type background_color )
{
gen = get_gen();
for ( cells_type::iterator i = cells.begin(); i != cells.end(); i++ ) {
i->reset( background_color );
}
}
void Framebuffer::prefix_window_title( const title_type& s )
{
if ( icon_name == window_title ) {
/* preserve equivalence */
icon_name.insert( icon_name.begin(), s.begin(), s.end() );
}
window_title.insert( window_title.begin(), s.begin(), s.end() );
}
std::string Cell::debug_contents( void ) const
{
if ( contents.empty() ) {
return "'_' ()";
}
std::string chars( 1, '\'' );
print_grapheme( chars );
chars.append( "' [" );
const char* lazycomma = "";
char buf[64];
for ( content_type::const_iterator i = contents.begin(); i < contents.end(); i++ ) {
snprintf( buf, sizeof buf, "%s0x%02x", lazycomma, static_cast<uint8_t>( *i ) );
chars.append( buf );
lazycomma = ", ";
}
chars.append( "]" );
return chars;
}
bool Cell::compare( const Cell& other ) const
{
bool ret = false;
std::string grapheme, other_grapheme;
print_grapheme( grapheme );
other.print_grapheme( other_grapheme );
if ( grapheme != other_grapheme ) {
ret = true;
fprintf( stderr, "Graphemes: '%s' vs. '%s'\n", grapheme.c_str(), other_grapheme.c_str() );
}
if ( !contents_match( other ) ) {
// ret = true;
fprintf( stderr,
"Contents: %s (%ld) vs. %s (%ld)\n",
debug_contents().c_str(),
static_cast<long int>( contents.size() ),
other.debug_contents().c_str(),
static_cast<long int>( other.contents.size() ) );
}
if ( fallback != other.fallback ) {
// ret = true;
// Since fallback is a 1-bit field, it is promoted to an int when
// manipulated. (See [conv.prom] in various C++ standards, e.g.,
// https://timsong-cpp.github.io/cppwp/n4659/conv.prom#5.) The correct
// printf format specifier is thus %d.
fprintf( stderr, "fallback: %d vs. %d\n", fallback, other.fallback );
}
if ( wide != other.wide ) {
ret = true;
// See comment above about bit-field promotion; it applies here as well.
fprintf( stderr, "width: %d vs. %d\n", wide, other.wide );
}
if ( !( renditions == other.renditions ) ) {
ret = true;
fprintf( stderr, "renditions differ\n" );
}
if ( wrap != other.wrap ) {
ret = true;
// See comment above about bit-field promotion; it applies here as well.
fprintf( stderr, "wrap: %d vs. %d\n", wrap, other.wrap );
}
return ret;
}
| 19,076
|
C++
|
.cc
| 591
| 28.428088
| 111
| 0.633843
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,578
|
terminaldisplayinit.cc
|
mobile-shell_mosh/src/terminal/terminaldisplayinit.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
/* This is in its own file because otherwise the ncurses #defines
alias our own variable names. */
#include "src/include/config.h"
#include "terminaldisplay.h"
#include <stdexcept>
#include <string>
#if defined HAVE_NCURSESW_CURSES_H
#include <ncursesw/curses.h>
#include <ncursesw/term.h>
#elif defined HAVE_NCURSESW_H
#include <ncursesw.h>
#include <term.h>
#elif defined HAVE_NCURSES_CURSES_H
#include <ncurses/curses.h>
#include <ncurses/term.h>
#elif defined HAVE_NCURSES_H
#include <ncurses.h>
#include <term.h>
#elif defined HAVE_CURSES_H
#include <curses.h>
#include <term.h>
#else
#error "SysV or X/Open-compatible Curses header file required"
#endif
#include <cstdlib>
#include <cstring>
using namespace Terminal;
static bool ti_flag( const char* capname )
{
int val = tigetflag( const_cast<char*>( capname ) );
if ( val == -1 ) {
throw std::invalid_argument( std::string( "Invalid terminfo boolean capability " ) + capname );
}
return val;
}
static const char* ti_str( const char* capname )
{
const char* val = tigetstr( const_cast<char*>( capname ) );
if ( val == (const char*)-1 ) {
throw std::invalid_argument( std::string( "Invalid terminfo string capability " ) + capname );
}
return val;
}
Display::Display( bool use_environment )
: has_ech( true ), has_bce( true ), has_title( true ), smcup( NULL ), rmcup( NULL )
{
if ( use_environment ) {
int errret = -2;
int ret = setupterm( (char*)0, 1, &errret );
if ( ret != OK ) {
switch ( errret ) {
case 1:
throw std::runtime_error( "Terminal is hardcopy and cannot be used by curses applications." );
break;
case 0:
throw std::runtime_error( "Unknown terminal type." );
break;
case -1:
throw std::runtime_error( "Terminfo database could not be found." );
break;
default:
throw std::runtime_error( "Unknown terminfo error." );
break;
}
}
/* check for ECH */
has_ech = ti_str( "ech" );
/* check for BCE */
has_bce = ti_flag( "bce" );
/* Check if we can set the window title and icon name. terminfo does not
have reliable information on this, so we hardcode a whitelist of
terminal type prefixes. */
static const char* const title_term_types[]
= { "xterm", "rxvt", "kterm", "Eterm", "alacritty", "screen", "tmux" };
has_title = false;
const char* term_type = getenv( "TERM" );
if ( term_type ) {
for ( size_t i = 0; i < sizeof( title_term_types ) / sizeof( const char* ); i++ ) {
if ( 0 == strncmp( term_type, title_term_types[i], strlen( title_term_types[i] ) ) ) {
has_title = true;
break;
}
}
}
if ( !getenv( "MOSH_NO_TERM_INIT" ) ) {
smcup = ti_str( "smcup" );
rmcup = ti_str( "rmcup" );
}
}
}
| 4,342
|
C++
|
.cc
| 116
| 32.844828
| 104
| 0.673877
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,579
|
terminalfunctions.cc
|
mobile-shell_mosh/src/terminal/terminalfunctions.cc
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include <algorithm>
#include <cstdio>
#include <string>
#include <unistd.h>
#include "src/terminal/parseraction.h"
#include "src/terminal/terminalframebuffer.h"
#include "terminaldispatcher.h"
using namespace Terminal;
/* Terminal functions -- routines activated by CSI, escape or a control char */
static void clearline( Framebuffer* fb, int row, int start, int end )
{
for ( int col = start; col <= end; col++ ) {
fb->reset_cell( fb->get_mutable_cell( row, col ) );
}
}
/* erase in line */
static void CSI_EL( Framebuffer* fb, Dispatcher* dispatch )
{
switch ( dispatch->getparam( 0, 0 ) ) {
case 0: /* default: active position to end of line, inclusive */
clearline( fb, -1, fb->ds.get_cursor_col(), fb->ds.get_width() - 1 );
break;
case 1: /* start of screen to active position, inclusive */
clearline( fb, -1, 0, fb->ds.get_cursor_col() );
break;
case 2: /* all of line */
fb->reset_row( fb->get_mutable_row( -1 ) );
break;
default:
break;
}
}
static Function func_CSI_EL( CSI, "K", CSI_EL );
/* erase in display */
static void CSI_ED( Framebuffer* fb, Dispatcher* dispatch )
{
switch ( dispatch->getparam( 0, 0 ) ) {
case 0: /* active position to end of screen, inclusive */
clearline( fb, -1, fb->ds.get_cursor_col(), fb->ds.get_width() - 1 );
for ( int y = fb->ds.get_cursor_row() + 1; y < fb->ds.get_height(); y++ ) {
fb->reset_row( fb->get_mutable_row( y ) );
}
break;
case 1: /* start of screen to active position, inclusive */
for ( int y = 0; y < fb->ds.get_cursor_row(); y++ ) {
fb->reset_row( fb->get_mutable_row( y ) );
}
clearline( fb, -1, 0, fb->ds.get_cursor_col() );
break;
case 2: /* entire screen */
for ( int y = 0; y < fb->ds.get_height(); y++ ) {
fb->reset_row( fb->get_mutable_row( y ) );
}
break;
default:
break;
}
}
static Function func_CSI_ED( CSI, "J", CSI_ED );
/* cursor movement -- relative and absolute */
static void CSI_cursormove( Framebuffer* fb, Dispatcher* dispatch )
{
int num = dispatch->getparam( 0, 1 );
switch ( dispatch->get_dispatch_chars()[0] ) {
case 'A':
fb->ds.move_row( -num, true );
break;
case 'B':
fb->ds.move_row( num, true );
break;
case 'C':
fb->ds.move_col( num, true );
break;
case 'D':
fb->ds.move_col( -num, true );
break;
case 'H':
case 'f':
fb->ds.move_row( dispatch->getparam( 0, 1 ) - 1 );
fb->ds.move_col( dispatch->getparam( 1, 1 ) - 1 );
break;
default:
break;
}
}
static Function func_CSI_cursormove_A( CSI, "A", CSI_cursormove );
static Function func_CSI_cursormove_B( CSI, "B", CSI_cursormove );
static Function func_CSI_cursormove_C( CSI, "C", CSI_cursormove );
static Function func_CSI_cursormove_D( CSI, "D", CSI_cursormove );
static Function func_CSI_cursormove_H( CSI, "H", CSI_cursormove );
static Function func_CSI_cursormove_f( CSI, "f", CSI_cursormove );
/* device attributes */
static void CSI_DA( Framebuffer* fb __attribute( ( unused ) ), Dispatcher* dispatch )
{
dispatch->terminal_to_host.append( "\033[?62c" ); /* plain vt220 */
}
static Function func_CSI_DA( CSI, "c", CSI_DA );
/* secondary device attributes */
static void CSI_SDA( Framebuffer* fb __attribute( ( unused ) ), Dispatcher* dispatch )
{
dispatch->terminal_to_host.append( "\033[>1;10;0c" ); /* plain vt220 */
}
static Function func_CSI_SDA( CSI, ">c", CSI_SDA );
/* screen alignment diagnostic */
static void Esc_DECALN( Framebuffer* fb, Dispatcher* dispatch __attribute( ( unused ) ) )
{
for ( int y = 0; y < fb->ds.get_height(); y++ ) {
for ( int x = 0; x < fb->ds.get_width(); x++ ) {
fb->reset_cell( fb->get_mutable_cell( y, x ) );
fb->get_mutable_cell( y, x )->append( 'E' );
}
}
}
static Function func_Esc_DECALN( ESCAPE, "#8", Esc_DECALN );
/* line feed */
static void Ctrl_LF( Framebuffer* fb, Dispatcher* dispatch __attribute( ( unused ) ) )
{
fb->move_rows_autoscroll( 1 );
}
/* same procedure for index, vertical tab, and form feed control codes */
static Function func_Ctrl_LF( CONTROL, "\x0a", Ctrl_LF );
static Function func_Ctrl_IND( CONTROL, "\x84", Ctrl_LF );
static Function func_Ctrl_VT( CONTROL, "\x0b", Ctrl_LF );
static Function func_Ctrl_FF( CONTROL, "\x0c", Ctrl_LF );
/* carriage return */
static void Ctrl_CR( Framebuffer* fb, Dispatcher* dispatch __attribute( ( unused ) ) )
{
fb->ds.move_col( 0 );
}
static Function func_Ctrl_CR( CONTROL, "\x0d", Ctrl_CR );
/* backspace */
static void Ctrl_BS( Framebuffer* fb, Dispatcher* dispatch __attribute( ( unused ) ) )
{
fb->ds.move_col( -1, true );
}
static Function func_Ctrl_BS( CONTROL, "\x08", Ctrl_BS );
/* reverse index -- like a backwards line feed */
static void Ctrl_RI( Framebuffer* fb, Dispatcher* dispatch __attribute( ( unused ) ) )
{
fb->move_rows_autoscroll( -1 );
}
static Function func_Ctrl_RI( CONTROL, "\x8D", Ctrl_RI );
/* newline */
static void Ctrl_NEL( Framebuffer* fb, Dispatcher* dispatch __attribute( ( unused ) ) )
{
fb->ds.move_col( 0 );
fb->move_rows_autoscroll( 1 );
}
static Function func_Ctrl_NEL( CONTROL, "\x85", Ctrl_NEL );
/* horizontal tab */
static void HT_n( Framebuffer* fb, size_t count )
{
int col = fb->ds.get_next_tab( count );
if ( col == -1 ) { /* no tabs, go to end of line */
col = fb->ds.get_width() - 1;
}
/* A horizontal tab is the only operation that preserves but
does not set the wrap state. It also starts a new grapheme. */
bool wrap_state_save = fb->ds.next_print_will_wrap;
fb->ds.move_col( col, false );
fb->ds.next_print_will_wrap = wrap_state_save;
}
static void Ctrl_HT( Framebuffer* fb, Dispatcher* dispatch __attribute( ( unused ) ) )
{
HT_n( fb, 1 );
}
static Function func_Ctrl_HT( CONTROL, "\x09", Ctrl_HT, false );
static void CSI_CxT( Framebuffer* fb, Dispatcher* dispatch )
{
int param = dispatch->getparam( 0, 1 );
if ( dispatch->get_dispatch_chars()[0] == 'Z' ) {
param = -param;
}
if ( param == 0 ) {
return;
}
HT_n( fb, param );
}
static Function func_CSI_CHT( CSI, "I", CSI_CxT, false );
static Function func_CSI_CBT( CSI, "Z", CSI_CxT, false );
/* horizontal tab set */
static void Ctrl_HTS( Framebuffer* fb, Dispatcher* dispatch __attribute( ( unused ) ) )
{
fb->ds.set_tab();
}
static Function func_Ctrl_HTS( CONTROL, "\x88", Ctrl_HTS );
/* tabulation clear */
static void CSI_TBC( Framebuffer* fb, Dispatcher* dispatch )
{
int param = dispatch->getparam( 0, 0 );
switch ( param ) {
case 0: /* clear this tab stop */
fb->ds.clear_tab( fb->ds.get_cursor_col() );
break;
case 3: /* clear all tab stops */
fb->ds.clear_default_tabs();
for ( int x = 0; x < fb->ds.get_width(); x++ ) {
fb->ds.clear_tab( x );
}
break;
default:
break;
}
}
/* TBC preserves wrap state */
static Function func_CSI_TBC( CSI, "g", CSI_TBC, false );
static bool* get_DEC_mode( int param, Framebuffer* fb )
{
switch ( param ) {
case 1: /* cursor key mode */
return &( fb->ds.application_mode_cursor_keys );
case 3: /* 80/132. Ignore but clear screen. */
/* clear screen */
fb->ds.move_row( 0 );
fb->ds.move_col( 0 );
for ( int y = 0; y < fb->ds.get_height(); y++ ) {
fb->reset_row( fb->get_mutable_row( y ) );
}
return NULL;
case 5: /* reverse video */
return &( fb->ds.reverse_video );
case 6: /* origin */
fb->ds.move_row( 0 );
fb->ds.move_col( 0 );
return &( fb->ds.origin_mode );
case 7: /* auto wrap */
return &( fb->ds.auto_wrap_mode );
case 25:
return &( fb->ds.cursor_visible );
case 1004: /* xterm mouse focus event */
return &( fb->ds.mouse_focus_event );
case 1007: /* xterm mouse alternate scroll */
return &( fb->ds.mouse_alternate_scroll );
case 2004: /* bracketed paste */
return &( fb->ds.bracketed_paste );
default:
break;
}
return NULL;
}
/* helper for CSI_DECSM and CSI_DECRM */
static void set_if_available( bool* mode, bool value )
{
if ( mode ) {
*mode = value;
}
}
/* set private mode */
static void CSI_DECSM( Framebuffer* fb, Dispatcher* dispatch )
{
for ( int i = 0; i < dispatch->param_count(); i++ ) {
int param = dispatch->getparam( i, 0 );
if ( param == 9 || ( param >= 1000 && param <= 1003 ) ) {
fb->ds.mouse_reporting_mode = (Terminal::DrawState::MouseReportingMode)param;
} else if ( param == 1005 || param == 1006 || param == 1015 ) {
fb->ds.mouse_encoding_mode = (Terminal::DrawState::MouseEncodingMode)param;
} else {
set_if_available( get_DEC_mode( param, fb ), true );
}
}
}
/* clear private mode */
static void CSI_DECRM( Framebuffer* fb, Dispatcher* dispatch )
{
for ( int i = 0; i < dispatch->param_count(); i++ ) {
int param = dispatch->getparam( i, 0 );
if ( param == 9 || ( param >= 1000 && param <= 1003 ) ) {
fb->ds.mouse_reporting_mode = Terminal::DrawState::MOUSE_REPORTING_NONE;
} else if ( param == 1005 || param == 1006 || param == 1015 ) {
fb->ds.mouse_encoding_mode = Terminal::DrawState::MOUSE_ENCODING_DEFAULT;
} else {
set_if_available( get_DEC_mode( param, fb ), false );
}
}
}
/* These functions don't clear wrap state. */
static Function func_CSI_DECSM( CSI, "?h", CSI_DECSM, false );
static Function func_CSI_DECRM( CSI, "?l", CSI_DECRM, false );
static bool* get_ANSI_mode( int param, Framebuffer* fb )
{
if ( param == 4 ) { /* insert/replace mode */
return &( fb->ds.insert_mode );
}
return NULL;
}
/* set mode */
static void CSI_SM( Framebuffer* fb, Dispatcher* dispatch )
{
for ( int i = 0; i < dispatch->param_count(); i++ ) {
bool* mode = get_ANSI_mode( dispatch->getparam( i, 0 ), fb );
if ( mode ) {
*mode = true;
}
}
}
/* clear mode */
static void CSI_RM( Framebuffer* fb, Dispatcher* dispatch )
{
for ( int i = 0; i < dispatch->param_count(); i++ ) {
bool* mode = get_ANSI_mode( dispatch->getparam( i, 0 ), fb );
if ( mode ) {
*mode = false;
}
}
}
static Function func_CSI_SM( CSI, "h", CSI_SM );
static Function func_CSI_RM( CSI, "l", CSI_RM );
/* set top and bottom margins */
static void CSI_DECSTBM( Framebuffer* fb, Dispatcher* dispatch )
{
int top = dispatch->getparam( 0, 1 );
int bottom = dispatch->getparam( 1, fb->ds.get_height() );
if ( ( bottom <= top ) || ( top > fb->ds.get_height() ) || ( top == 0 && bottom == 1 ) ) {
return; /* invalid, xterm ignores */
}
fb->ds.set_scrolling_region( top - 1, bottom - 1 );
fb->ds.move_row( 0 );
fb->ds.move_col( 0 );
}
static Function func_CSI_DECSTMB( CSI, "r", CSI_DECSTBM );
/* terminal bell */
static void Ctrl_BEL( Framebuffer* fb, Dispatcher* dispatch __attribute( ( unused ) ) )
{
fb->ring_bell();
}
static Function func_Ctrl_BEL( CONTROL, "\x07", Ctrl_BEL );
/* select graphics rendition -- e.g., bold, blinking, etc. */
static void CSI_SGR( Framebuffer* fb, Dispatcher* dispatch )
{
for ( int i = 0; i < dispatch->param_count(); i++ ) {
int rendition = dispatch->getparam( i, 0 );
/* We need to special-case the handling of [34]8 ; 5 ; Ps,
because Ps of 0 in that case does not mean reset to default, even
though it means that otherwise (as usually renditions are applied
in order). */
if ( ( rendition == 38 || rendition == 48 ) && ( dispatch->param_count() - i >= 3 )
&& ( dispatch->getparam( i + 1, -1 ) == 5 ) ) {
( rendition == 38 ) ? fb->ds.set_foreground_color( dispatch->getparam( i + 2, 0 ) )
: fb->ds.set_background_color( dispatch->getparam( i + 2, 0 ) );
i += 2;
continue;
}
/* True color support: ESC[ ... [34]8;2;<r>;<g>;<b> ... m */
if ( ( rendition == 38 || rendition == 48 ) && ( dispatch->param_count() - i >= 5 )
&& ( dispatch->getparam( i + 1, -1 ) == 2 ) ) {
unsigned int red = dispatch->getparam( i + 2, 0 );
unsigned int green = dispatch->getparam( i + 3, 0 );
unsigned int blue = dispatch->getparam( i + 4, 0 );
unsigned int color;
color = Renditions::make_true_color( red, green, blue );
if ( rendition == 38 ) {
fb->ds.set_foreground_color( color );
} else {
fb->ds.set_background_color( color );
}
i += 4;
continue;
}
fb->ds.add_rendition( rendition );
}
}
static Function func_CSI_SGR( CSI, "m", CSI_SGR, false ); /* changing renditions doesn't clear wrap flag */
/* save and restore cursor */
static void Esc_DECSC( Framebuffer* fb, Dispatcher* dispatch __attribute( ( unused ) ) )
{
fb->ds.save_cursor();
}
static void Esc_DECRC( Framebuffer* fb, Dispatcher* dispatch __attribute( ( unused ) ) )
{
fb->ds.restore_cursor();
}
static Function func_Esc_DECSC( ESCAPE, "7", Esc_DECSC );
static Function func_Esc_DECRC( ESCAPE, "8", Esc_DECRC );
/* device status report -- e.g., cursor position (used by resize) */
static void CSI_DSR( Framebuffer* fb, Dispatcher* dispatch )
{
int param = dispatch->getparam( 0, 0 );
switch ( param ) {
case 5: /* device status report requested */
dispatch->terminal_to_host.append( "\033[0n" );
break;
case 6: /* report of active position requested */
char cpr[32];
snprintf( cpr, 32, "\033[%d;%dR", fb->ds.get_cursor_row() + 1, fb->ds.get_cursor_col() + 1 );
dispatch->terminal_to_host.append( cpr );
break;
default:
break;
}
}
static Function func_CSI_DSR( CSI, "n", CSI_DSR );
/* insert line */
static void CSI_IL( Framebuffer* fb, Dispatcher* dispatch )
{
int lines = dispatch->getparam( 0, 1 );
fb->insert_line( fb->ds.get_cursor_row(), lines );
/* vt220 manual and Ecma-48 say to move to first column */
/* but xterm and gnome-terminal don't */
fb->ds.move_col( 0 );
}
static Function func_CSI_IL( CSI, "L", CSI_IL );
/* delete line */
static void CSI_DL( Framebuffer* fb, Dispatcher* dispatch )
{
int lines = dispatch->getparam( 0, 1 );
fb->delete_line( fb->ds.get_cursor_row(), lines );
/* same story -- xterm and gnome-terminal don't
move to first column */
fb->ds.move_col( 0 );
}
static Function func_CSI_DL( CSI, "M", CSI_DL );
/* insert characters */
static void CSI_ICH( Framebuffer* fb, Dispatcher* dispatch )
{
int cells = dispatch->getparam( 0, 1 );
for ( int i = 0; i < cells; i++ ) {
fb->insert_cell( fb->ds.get_cursor_row(), fb->ds.get_cursor_col() );
}
}
static Function func_CSI_ICH( CSI, "@", CSI_ICH );
/* delete character */
static void CSI_DCH( Framebuffer* fb, Dispatcher* dispatch )
{
int cells = dispatch->getparam( 0, 1 );
for ( int i = 0; i < cells; i++ ) {
fb->delete_cell( fb->ds.get_cursor_row(), fb->ds.get_cursor_col() );
}
}
static Function func_CSI_DCH( CSI, "P", CSI_DCH );
/* line position absolute */
static void CSI_VPA( Framebuffer* fb, Dispatcher* dispatch )
{
int row = dispatch->getparam( 0, 1 );
fb->ds.move_row( row - 1 );
}
static Function func_CSI_VPA( CSI, "d", CSI_VPA );
/* character position absolute */
static void CSI_HPA( Framebuffer* fb, Dispatcher* dispatch )
{
int col = dispatch->getparam( 0, 1 );
fb->ds.move_col( col - 1 );
}
static Function func_CSI_CHA( CSI, "G", CSI_HPA ); /* ECMA-48 name: CHA */
static Function func_CSI_HPA( CSI, "\x60", CSI_HPA ); /* ECMA-48 name: HPA */
/* erase character */
static void CSI_ECH( Framebuffer* fb, Dispatcher* dispatch )
{
int num = dispatch->getparam( 0, 1 );
int limit = fb->ds.get_cursor_col() + num - 1;
if ( limit >= fb->ds.get_width() ) {
limit = fb->ds.get_width() - 1;
}
clearline( fb, -1, fb->ds.get_cursor_col(), limit );
}
static Function func_CSI_ECH( CSI, "X", CSI_ECH );
/* reset to initial state */
static void Esc_RIS( Framebuffer* fb, Dispatcher* dispatch __attribute( ( unused ) ) )
{
fb->reset();
}
static Function func_Esc_RIS( ESCAPE, "c", Esc_RIS );
/* soft reset */
static void CSI_DECSTR( Framebuffer* fb, Dispatcher* dispatch __attribute( ( unused ) ) )
{
fb->soft_reset();
}
static Function func_CSI_DECSTR( CSI, "!p", CSI_DECSTR );
/* xterm uses an Operating System Command to set the window title */
void Dispatcher::OSC_dispatch( const Parser::OSC_End* act __attribute( ( unused ) ), Framebuffer* fb )
{
/* handle osc copy clipboard sequence 52;c; */
if ( OSC_string.size() >= 5 && OSC_string[0] == L'5' && OSC_string[1] == L'2' && OSC_string[2] == L';'
&& OSC_string[3] == L'c' && OSC_string[4] == L';' ) {
Terminal::Framebuffer::title_type clipboard( OSC_string.begin() + 5, OSC_string.end() );
fb->set_clipboard( clipboard );
/* handle osc terminal title sequence */
} else if ( OSC_string.size() >= 1 ) {
long cmd_num = -1;
int offset = 0;
if ( OSC_string[0] == L';' ) {
/* OSC of the form "\033];<title>\007" */
cmd_num = 0; /* treat it as as a zero */
offset = 1;
} else if ( ( OSC_string.size() >= 2 ) && ( OSC_string[1] == L';' ) ) {
/* OSC of the form "\033]X;<title>\007" where X can be:
* 0: set icon name and window title
* 1: set icon name
* 2: set window title */
cmd_num = OSC_string[0] - L'0';
offset = 2;
}
bool set_icon = cmd_num == 0 || cmd_num == 1;
bool set_title = cmd_num == 0 || cmd_num == 2;
if ( set_icon || set_title ) {
fb->set_title_initialized();
int title_length = std::min( OSC_string.size(), (size_t)256 );
Terminal::Framebuffer::title_type newtitle( OSC_string.begin() + offset, OSC_string.begin() + title_length );
if ( set_icon ) {
fb->set_icon_name( newtitle );
}
if ( set_title ) {
fb->set_window_title( newtitle );
}
}
}
}
/* scroll down or terminfo indn */
static void CSI_SD( Framebuffer* fb, Dispatcher* dispatch )
{
fb->scroll( dispatch->getparam( 0, 1 ) );
}
static Function func_CSI_SD( CSI, "S", CSI_SD );
/* scroll up or terminfo rin */
static void CSI_SU( Framebuffer* fb, Dispatcher* dispatch )
{
fb->scroll( -dispatch->getparam( 0, 1 ) );
}
static Function func_CSI_SU( CSI, "T", CSI_SU );
| 19,686
|
C++
|
.cc
| 544
| 32.474265
| 115
| 0.627278
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,581
|
fatal_assert.h
|
mobile-shell_mosh/src/util/fatal_assert.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef FATAL_ASSERT_HPP
#define FATAL_ASSERT_HPP
#include <cstdio>
#include <cstdlib>
static void fatal_error( const char* expression, const char* file, int line, const char* function )
{
fprintf( stderr,
"Fatal assertion failure in function %s at %s:%d\nFailed test: %s\n",
function,
file,
line,
expression );
abort();
}
#define fatal_assert( expr ) ( ( expr ) ? (void)0 : fatal_error( #expr, __FILE__, __LINE__, __func__ ) )
#endif
| 1,968
|
C++
|
.h
| 42
| 41.928571
| 104
| 0.72547
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,582
|
dos_assert.h
|
mobile-shell_mosh/src/util/dos_assert.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef DOS_ASSERT_HPP
#define DOS_ASSERT_HPP
#include <cstdio>
#include <cstdlib>
#include "src/crypto/crypto.h"
static void dos_detected( const char* expression, const char* file, int line, const char* function )
{
char buffer[2048];
snprintf( buffer,
2048,
"Illegal counterparty input (possible denial of service) in function %s at %s:%d, failed test: %s\n",
function,
file,
line,
expression );
throw Crypto::CryptoException( buffer );
}
#define dos_assert( expr ) ( ( expr ) ? (void)0 : dos_detected( #expr, __FILE__, __LINE__, __func__ ) )
#endif
| 2,105
|
C++
|
.h
| 45
| 41.666667
| 113
| 0.722304
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,583
|
pty_compat.h
|
mobile-shell_mosh/src/util/pty_compat.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef PTY_COMPAT_HPP
#define PTY_COMPAT_HPP
#include "src/include/config.h"
#ifndef HAVE_FORKPTY
#define forkpty my_forkpty
#endif
#ifndef HAVE_CFMAKERAW
#define cfmakeraw my_cfmakeraw
#endif
pid_t my_forkpty( int* amaster, char* name, const struct termios* termp, const struct winsize* winp );
void my_cfmakeraw( struct termios* termios_p );
#endif
| 1,827
|
C++
|
.h
| 38
| 44.263158
| 102
| 0.767154
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,585
|
locale_utils.h
|
mobile-shell_mosh/src/util/locale_utils.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef LOCALE_UTILS_HPP
#define LOCALE_UTILS_HPP
#include <string>
class LocaleVar
{
public:
const std::string name, value;
LocaleVar( const char* s_name, const char* s_value ) : name( s_name ), value( s_value ) {}
const std::string str( void ) const;
};
const LocaleVar get_ctype( void );
const char* locale_charset( void );
bool is_utf8_locale( void );
void set_native_locale( void );
void clear_locale_variables( void );
#endif
| 1,912
|
C++
|
.h
| 42
| 41.857143
| 92
| 0.753226
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,586
|
timestamp.h
|
mobile-shell_mosh/src/util/timestamp.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef TIMESTAMP_HPP
#define TIMESTAMP_HPP
#include <cstdint>
void freeze_timestamp( void );
uint64_t frozen_timestamp( void );
#endif
| 1,609
|
C++
|
.h
| 32
| 46
| 73
| 0.763393
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,587
|
crypto.h
|
mobile-shell_mosh/src/crypto/crypto.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef CRYPTO_HPP
#define CRYPTO_HPP
#include "src/crypto/ae.h"
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <string>
long int myatoi( const char* str );
class PRNG;
namespace Crypto {
class CryptoException : public std::exception
{
public:
std::string text;
bool fatal;
CryptoException( std::string s_text, bool s_fatal = false ) : text( s_text ), fatal( s_fatal ) {};
const char* what() const throw() { return text.c_str(); }
~CryptoException() throw() {}
};
/*
* OCB (and other algorithms) require a source of nonce/sequence
* numbers that never repeats its output. Enforce that with this
* function.
*/
uint64_t unique( void );
/* 16-byte-aligned buffer, with length. */
class AlignedBuffer
{
private:
size_t m_len;
void* m_allocated;
char* m_data;
public:
AlignedBuffer( size_t len, const char* data = NULL );
~AlignedBuffer() { free( m_allocated ); }
char* data( void ) const { return m_data; }
size_t len( void ) const { return m_len; }
private:
/* Not implemented */
AlignedBuffer( const AlignedBuffer& );
AlignedBuffer& operator=( const AlignedBuffer& );
};
class Base64Key
{
private:
unsigned char key[16];
public:
Base64Key(); /* random key */
Base64Key( PRNG& prng );
Base64Key( std::string printable_key );
std::string printable_key( void ) const;
unsigned char* data( void ) { return key; }
};
class Nonce
{
public:
static const int NONCE_LEN = 12;
private:
char bytes[NONCE_LEN];
public:
Nonce( uint64_t val );
Nonce( const char* s_bytes, size_t len );
std::string cc_str( void ) const { return std::string( bytes + 4, 8 ); }
const char* data( void ) const { return bytes; }
uint64_t val( void ) const;
};
class Message
{
public:
const Nonce nonce;
const std::string text;
Message( const char* nonce_bytes, size_t nonce_len, const char* text_bytes, size_t text_len )
: nonce( nonce_bytes, nonce_len ), text( text_bytes, text_len )
{}
Message( const Nonce& s_nonce, const std::string& s_text ) : nonce( s_nonce ), text( s_text ) {}
};
class Session
{
private:
Base64Key key;
AlignedBuffer ctx_buf;
ae_ctx* ctx;
uint64_t blocks_encrypted;
AlignedBuffer plaintext_buffer;
AlignedBuffer ciphertext_buffer;
AlignedBuffer nonce_buffer;
public:
static const int RECEIVE_MTU = 2048;
/* Overhead (not counting the nonce, which is handled by network transport) */
static const int ADDED_BYTES = 16 /* final OCB block */;
Session( Base64Key s_key );
~Session();
const std::string encrypt( const Message& plaintext );
const Message decrypt( const char* str, size_t len );
const Message decrypt( const std::string& ciphertext ) { return decrypt( ciphertext.data(), ciphertext.size() ); }
Session( const Session& );
Session& operator=( const Session& );
};
void disable_dumping_core( void );
void reenable_dumping_core( void );
}
#endif
| 4,388
|
C++
|
.h
| 129
| 31.170543
| 116
| 0.726627
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,588
|
byteorder.h
|
mobile-shell_mosh/src/crypto/byteorder.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef BYTEORDER_HPP
#define BYTEORDER_HPP
#include "src/include/config.h"
#if HAVE_DECL_BE64TOH || HAVE_DECL_BETOH64
#if defined( HAVE_ENDIAN_H )
#include <endian.h>
#elif defined( HAVE_SYS_ENDIAN_H )
#include <sys/endian.h>
#include <sys/types.h>
#endif
#if !HAVE_DECL_BE64TOH && HAVE_DECL_BETOH64
#define be64toh betoh64
#define be16toh betoh16
#endif
#elif HAVE_OSX_SWAP
#include <libkern/OSByteOrder.h>
#define htobe64 OSSwapHostToBigInt64
#define be64toh OSSwapBigToHostInt64
#define htobe16 OSSwapHostToBigInt16
#define be16toh OSSwapBigToHostInt16
#else
/* Use our fallback implementation, which is correct for any endianness. */
#include <cstdint>
/* Make sure they aren't macros */
#undef htobe64
#undef be64toh
#undef htobe16
#undef be16toh
/* Use unions rather than casts, to comply with strict aliasing rules. */
inline uint64_t htobe64( uint64_t x )
{
uint8_t xs[8] = { static_cast<uint8_t>( ( x >> 56 ) & 0xFF ),
static_cast<uint8_t>( ( x >> 48 ) & 0xFF ),
static_cast<uint8_t>( ( x >> 40 ) & 0xFF ),
static_cast<uint8_t>( ( x >> 32 ) & 0xFF ),
static_cast<uint8_t>( ( x >> 24 ) & 0xFF ),
static_cast<uint8_t>( ( x >> 16 ) & 0xFF ),
static_cast<uint8_t>( ( x >> 8 ) & 0xFF ),
static_cast<uint8_t>( (x)&0xFF ) };
union {
const uint8_t* p8;
const uint64_t* p64;
} u;
u.p8 = xs;
return *u.p64;
}
inline uint64_t be64toh( uint64_t x )
{
union {
const uint8_t* p8;
const uint64_t* p64;
} u;
u.p64 = &x;
return ( uint64_t( u.p8[0] ) << 56 ) | ( uint64_t( u.p8[1] ) << 48 ) | ( uint64_t( u.p8[2] ) << 40 )
| ( uint64_t( u.p8[3] ) << 32 ) | ( uint64_t( u.p8[4] ) << 24 ) | ( uint64_t( u.p8[5] ) << 16 )
| ( uint64_t( u.p8[6] ) << 8 ) | ( uint64_t( u.p8[7] ) );
}
inline uint16_t htobe16( uint16_t x )
{
uint8_t xs[2] = { static_cast<uint8_t>( ( x >> 8 ) & 0xFF ), static_cast<uint8_t>( (x)&0xFF ) };
union {
const uint8_t* p8;
const uint16_t* p16;
} u;
u.p8 = xs;
return *u.p16;
}
inline uint16_t be16toh( uint16_t x )
{
union {
const uint8_t* p8;
const uint16_t* p16;
} u;
u.p16 = &x;
return ( uint16_t( u.p8[0] ) << 8 ) | ( uint16_t( u.p8[1] ) );
}
#endif
#endif
| 3,785
|
C++
|
.h
| 104
| 32.086538
| 104
| 0.65865
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,589
|
prng.h
|
mobile-shell_mosh/src/crypto/prng.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef PRNG_HPP
#define PRNG_HPP
#include <cstdint>
#include <fstream>
#include <string>
#include "src/crypto/crypto.h"
/* Read random bytes from /dev/urandom.
We rely on stdio buffering for efficiency. */
static const char rdev[] = "/dev/urandom";
using namespace Crypto;
class PRNG
{
private:
std::ifstream randfile;
/* unimplemented to satisfy -Weffc++ */
PRNG( const PRNG& );
PRNG& operator=( const PRNG& );
public:
PRNG() : randfile( rdev, std::ifstream::in | std::ifstream::binary ) {}
void fill( void* dest, size_t size )
{
if ( 0 == size ) {
return;
}
randfile.read( static_cast<char*>( dest ), size );
if ( !randfile ) {
throw CryptoException( "Could not read from " + std::string( rdev ) );
}
}
uint8_t uint8()
{
uint8_t x;
fill( &x, 1 );
return x;
}
uint32_t uint32()
{
uint32_t x;
fill( &x, 4 );
return x;
}
uint64_t uint64()
{
uint64_t x;
fill( &x, 8 );
return x;
}
};
#endif
| 2,480
|
C++
|
.h
| 75
| 29.106667
| 76
| 0.704279
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,590
|
base64.h
|
mobile-shell_mosh/src/crypto/base64.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#include <cstdint>
bool base64_decode( const char* b64, const size_t b64_len, uint8_t* raw, size_t* raw_len );
void base64_encode( const uint8_t* raw, const size_t raw_len, char* b64, const size_t b64_len );
| 1,680
|
C++
|
.h
| 29
| 53.344828
| 96
| 0.754717
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,592
|
base64_vector.h
|
mobile-shell_mosh/src/tests/base64_vector.h
|
struct base64_test_row
{
const unsigned char native[17];
const char encoded[25];
};
typedef base64_test_row* base64_test_vector;
extern base64_test_row static_base64_vector[];
| 180
|
C++
|
.h
| 7
| 24.142857
| 46
| 0.780347
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,593
|
test_utils.h
|
mobile-shell_mosh/src/tests/test_utils.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef TEST_UTILS_HPP
#define TEST_UTILS_HPP
#include <string>
#include "src/crypto/crypto.h"
#define DUMP_NAME_FMT "%-10s "
void hexdump( const void* buf, size_t len, const char* name );
void hexdump( const Crypto::AlignedBuffer& buf, const char* name );
void hexdump( const std::string& buf, const char* name );
#endif
| 1,797
|
C++
|
.h
| 35
| 47.285714
| 73
| 0.757282
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,594
|
completeterminal.h
|
mobile-shell_mosh/src/statesync/completeterminal.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef COMPLETE_TERMINAL_HPP
#define COMPLETE_TERMINAL_HPP
#include <cstdint>
#include <list>
#include "src/terminal/parser.h"
#include "src/terminal/terminal.h"
/* This class represents the complete terminal -- a UTF8Parser feeding Actions to an Emulator. */
namespace Terminal {
class Complete
{
private:
Parser::UTF8Parser parser;
Terminal::Emulator terminal;
Terminal::Display display;
// Only used locally by act(), but kept here as a performance optimization,
// to avoid construction/destruction. It must always be empty
// outside calls to act() to keep horrible things from happening.
Parser::Actions actions;
using input_history_type = std::list<std::pair<uint64_t, uint64_t>>;
input_history_type input_history;
uint64_t echo_ack;
static const int ECHO_TIMEOUT = 50; /* for late ack */
public:
Complete( size_t width, size_t height )
: parser(), terminal( width, height ), display( false ), actions(), input_history(), echo_ack( 0 )
{}
std::string act( const std::string& str );
std::string act( const Parser::Action& act );
const Framebuffer& get_fb( void ) const { return terminal.get_fb(); }
void reset_input( void ) { parser.reset_input(); }
uint64_t get_echo_ack( void ) const { return echo_ack; }
bool set_echo_ack( uint64_t now );
void register_input_frame( uint64_t n, uint64_t now );
int wait_time( uint64_t now ) const;
/* interface for Network::Transport */
void subtract( const Complete* ) const {}
std::string diff_from( const Complete& existing ) const;
std::string init_diff( void ) const;
void apply_string( const std::string& diff );
bool operator==( const Complete& x ) const;
bool compare( const Complete& other ) const;
};
}
#endif
| 3,207
|
C++
|
.h
| 70
| 42.314286
| 102
| 0.739577
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,595
|
user.h
|
mobile-shell_mosh/src/statesync/user.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef USER_HPP
#define USER_HPP
#include <cassert>
#include <deque>
#include <list>
#include <string>
#include "src/terminal/parseraction.h"
namespace Network {
enum UserEventType
{
UserByteType = 0,
ResizeType = 1
};
class UserEvent
{
public:
UserEventType type;
Parser::UserByte userbyte;
Parser::Resize resize;
UserEvent( const Parser::UserByte& s_userbyte ) : type( UserByteType ), userbyte( s_userbyte ), resize( -1, -1 )
{}
UserEvent( const Parser::Resize& s_resize ) : type( ResizeType ), userbyte( 0 ), resize( s_resize ) {}
private:
UserEvent();
public:
bool operator==( const UserEvent& x ) const
{
return ( type == x.type ) && ( userbyte == x.userbyte ) && ( resize == x.resize );
}
};
class UserStream
{
private:
std::deque<UserEvent> actions;
public:
UserStream() : actions() {}
void push_back( const Parser::UserByte& s_userbyte ) { actions.push_back( UserEvent( s_userbyte ) ); }
void push_back( const Parser::Resize& s_resize ) { actions.push_back( UserEvent( s_resize ) ); }
bool empty( void ) const { return actions.empty(); }
size_t size( void ) const { return actions.size(); }
const Parser::Action& get_action( unsigned int i ) const;
/* interface for Network::Transport */
void subtract( const UserStream* prefix );
std::string diff_from( const UserStream& existing ) const;
std::string init_diff( void ) const { return diff_from( UserStream() ); };
void apply_string( const std::string& diff );
bool operator==( const UserStream& x ) const { return actions == x.actions; }
bool compare( const UserStream& ) { return false; }
};
}
#endif
| 3,102
|
C++
|
.h
| 77
| 37.051948
| 114
| 0.72812
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,596
|
networktransport.h
|
mobile-shell_mosh/src/network/networktransport.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef NETWORK_TRANSPORT_HPP
#define NETWORK_TRANSPORT_HPP
#include <csignal>
#include <ctime>
#include <list>
#include <string>
#include <vector>
#include "src/network/network.h"
#include "src/network/transportsender.h"
#include "transportfragment.h"
namespace Network {
template<class MyState, class RemoteState>
class Transport
{
private:
/* the underlying, encrypted network connection */
Connection connection;
/* sender side */
TransportSender<MyState> sender;
/* helper methods for recv() */
void process_throwaway_until( uint64_t throwaway_num );
/* simple receiver */
std::list<TimestampedState<RemoteState>> received_states;
uint64_t receiver_quench_timer;
RemoteState last_receiver_state; /* the state we were in when user last queried state */
FragmentAssembly fragments;
unsigned int verbose;
public:
Transport( MyState& initial_state,
RemoteState& initial_remote,
const char* desired_ip,
const char* desired_port );
Transport( MyState& initial_state,
RemoteState& initial_remote,
const char* key_str,
const char* ip,
const char* port );
/* Send data or an ack if necessary. */
void tick( void ) { sender.tick(); }
/* Returns the number of ms to wait until next possible event. */
int wait_time( void ) { return sender.wait_time(); }
/* Blocks waiting for a packet. */
void recv( void );
/* Find diff between last receiver state and current remote state, then rationalize states. */
std::string get_remote_diff( void );
/* Shut down other side of connection. */
/* Illegal to change current_state after this. */
void start_shutdown( void ) { sender.start_shutdown(); }
bool shutdown_in_progress( void ) const { return sender.get_shutdown_in_progress(); }
bool shutdown_acknowledged( void ) const { return sender.get_shutdown_acknowledged(); }
bool shutdown_ack_timed_out( void ) const { return sender.shutdown_ack_timed_out(); }
bool has_remote_addr( void ) const { return connection.get_has_remote_addr(); }
/* Other side has requested shutdown and we have sent one ACK */
bool counterparty_shutdown_ack_sent( void ) const { return sender.get_counterparty_shutdown_acknowledged(); }
std::string port( void ) const { return connection.port(); }
std::string get_key( void ) const { return connection.get_key(); }
MyState& get_current_state( void ) { return sender.get_current_state(); }
void set_current_state( const MyState& x ) { sender.set_current_state( x ); }
uint64_t get_remote_state_num( void ) const { return received_states.back().num; }
const TimestampedState<RemoteState>& get_latest_remote_state( void ) const { return received_states.back(); }
const std::vector<int> fds( void ) const { return connection.fds(); }
void set_verbose( unsigned int s_verbose )
{
sender.set_verbose( s_verbose );
verbose = s_verbose;
}
void set_send_delay( int new_delay ) { sender.set_send_delay( new_delay ); }
uint64_t get_sent_state_acked_timestamp( void ) const { return sender.get_sent_state_acked_timestamp(); }
uint64_t get_sent_state_acked( void ) const { return sender.get_sent_state_acked(); }
uint64_t get_sent_state_last( void ) const { return sender.get_sent_state_last(); }
unsigned int send_interval( void ) const { return sender.send_interval(); }
const Addr& get_remote_addr( void ) const { return connection.get_remote_addr(); }
socklen_t get_remote_addr_len( void ) const { return connection.get_remote_addr_len(); }
std::string& get_send_error( void ) { return connection.get_send_error(); }
};
}
#endif
| 5,123
|
C++
|
.h
| 103
| 45.592233
| 111
| 0.725997
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,597
|
networktransport-impl.h
|
mobile-shell_mosh/src/network/networktransport-impl.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef NETWORK_TRANSPORT_IMPL_HPP
#define NETWORK_TRANSPORT_IMPL_HPP
#include "src/network/networktransport.h"
#include "transportsender-impl.h"
using namespace Network;
template<class MyState, class RemoteState>
Transport<MyState, RemoteState>::Transport( MyState& initial_state,
RemoteState& initial_remote,
const char* desired_ip,
const char* desired_port )
: connection( desired_ip, desired_port ), sender( &connection, initial_state ),
received_states( 1, TimestampedState<RemoteState>( timestamp(), 0, initial_remote ) ),
receiver_quench_timer( 0 ), last_receiver_state( initial_remote ), fragments(), verbose( 0 )
{
/* server */
}
template<class MyState, class RemoteState>
Transport<MyState, RemoteState>::Transport( MyState& initial_state,
RemoteState& initial_remote,
const char* key_str,
const char* ip,
const char* port )
: connection( key_str, ip, port ), sender( &connection, initial_state ),
received_states( 1, TimestampedState<RemoteState>( timestamp(), 0, initial_remote ) ),
receiver_quench_timer( 0 ), last_receiver_state( initial_remote ), fragments(), verbose( 0 )
{
/* client */
}
template<class MyState, class RemoteState>
void Transport<MyState, RemoteState>::recv( void )
{
std::string s( connection.recv() );
Fragment frag( s );
if ( fragments.add_fragment( frag ) ) { /* complete packet */
Instruction inst = fragments.get_assembly();
if ( inst.protocol_version() != MOSH_PROTOCOL_VERSION ) {
throw NetworkException( "mosh protocol version mismatch", 0 );
}
sender.process_acknowledgment_through( inst.ack_num() );
/* inform network layer of roundtrip (end-to-end-to-end) connectivity */
connection.set_last_roundtrip_success( sender.get_sent_state_acked_timestamp() );
/* first, make sure we don't already have the new state */
for ( typename std::list<TimestampedState<RemoteState>>::iterator i = received_states.begin();
i != received_states.end();
i++ ) {
if ( inst.new_num() == i->num ) {
return;
}
}
/* now, make sure we do have the old state */
bool found = 0;
typename std::list<TimestampedState<RemoteState>>::iterator reference_state = received_states.begin();
while ( reference_state != received_states.end() ) {
if ( inst.old_num() == reference_state->num ) {
found = true;
break;
}
reference_state++;
}
if ( !found ) {
// fprintf( stderr, "Ignoring out-of-order packet. Reference state %d has been discarded or hasn't yet been
// received.\n", int(inst.old_num) );
return; /* this is security-sensitive and part of how we enforce idempotency */
}
/* Do not accept state if our queue is full */
/* This is better than dropping states from the middle of the
queue (as sender does), because we don't want to ACK a state
and then discard it later. */
process_throwaway_until( inst.throwaway_num() );
if ( received_states.size() > 1024 ) { /* limit on state queue */
uint64_t now = timestamp();
if ( now < receiver_quench_timer ) { /* deny letting state grow further */
if ( verbose ) {
fprintf(
stderr,
"[%u] Receiver queue full, discarding %d (malicious sender or long-unidirectional connectivity?)\n",
(unsigned int)( timestamp() % 100000 ),
(int)inst.new_num() );
}
return;
} else {
receiver_quench_timer = now + 15000;
}
}
/* apply diff to reference state */
TimestampedState<RemoteState> new_state = *reference_state;
new_state.timestamp = timestamp();
new_state.num = inst.new_num();
if ( !inst.diff().empty() ) {
new_state.state.apply_string( inst.diff() );
}
/* Insert new state in sorted place */
for ( typename std::list<TimestampedState<RemoteState>>::iterator i = received_states.begin();
i != received_states.end();
i++ ) {
if ( i->num > new_state.num ) {
received_states.insert( i, new_state );
if ( verbose ) {
fprintf( stderr,
"[%u] Received OUT-OF-ORDER state %d [ack %d]\n",
(unsigned int)( timestamp() % 100000 ),
(int)new_state.num,
(int)inst.ack_num() );
}
return;
}
}
if ( verbose ) {
fprintf( stderr,
"[%u] Received state %d [coming from %d, ack %d]\n",
(unsigned int)( timestamp() % 100000 ),
(int)new_state.num,
(int)inst.old_num(),
(int)inst.ack_num() );
}
received_states.push_back( new_state );
sender.set_ack_num( received_states.back().num );
sender.remote_heard( new_state.timestamp );
if ( !inst.diff().empty() ) {
sender.set_data_ack();
}
}
}
/* The sender uses throwaway_num to tell us the earliest received state that we need to keep around */
template<class MyState, class RemoteState>
void Transport<MyState, RemoteState>::process_throwaway_until( uint64_t throwaway_num )
{
typename std::list<TimestampedState<RemoteState>>::iterator i = received_states.begin();
while ( i != received_states.end() ) {
typename std::list<TimestampedState<RemoteState>>::iterator inext = i;
inext++;
if ( i->num < throwaway_num ) {
received_states.erase( i );
}
i = inext;
}
fatal_assert( received_states.size() > 0 );
}
template<class MyState, class RemoteState>
std::string Transport<MyState, RemoteState>::get_remote_diff( void )
{
/* find diff between last receiver state and current remote state, then rationalize states */
std::string ret( received_states.back().state.diff_from( last_receiver_state ) );
const RemoteState* oldest_receiver_state = &received_states.front().state;
for ( typename std::list<TimestampedState<RemoteState>>::reverse_iterator i = received_states.rbegin();
i != received_states.rend();
i++ ) {
i->state.subtract( oldest_receiver_state );
}
last_receiver_state = received_states.back().state;
return ret;
}
#endif
| 7,934
|
C++
|
.h
| 179
| 36.865922
| 116
| 0.64158
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
10,598
|
compressor.h
|
mobile-shell_mosh/src/network/compressor.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef COMPRESSOR_H
#define COMPRESSOR_H
#include <string>
namespace Network {
class Compressor
{
private:
static const int BUFFER_SIZE = 2048 * 2048; /* effective limit on terminal size */
unsigned char buffer[BUFFER_SIZE];
public:
Compressor() : buffer() {}
~Compressor() {}
std::string compress_str( const std::string& input );
std::string uncompress_str( const std::string& input );
/* unused */
Compressor( const Compressor& );
Compressor& operator=( const Compressor& );
};
Compressor& get_compressor( void );
}
#endif
| 2,022
|
C++
|
.h
| 47
| 39.297872
| 84
| 0.751657
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,599
|
transportsender.h
|
mobile-shell_mosh/src/network/transportsender.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef TRANSPORT_SENDER_HPP
#define TRANSPORT_SENDER_HPP
#include <list>
#include <string>
#include "src/crypto/prng.h"
#include "src/network/network.h"
#include "src/protobufs/transportinstruction.pb.h"
#include "transportfragment.h"
#include "transportstate.h"
namespace Network {
using namespace TransportBuffers;
/* timing parameters */
const int SEND_INTERVAL_MIN = 20; /* ms between frames */
const int SEND_INTERVAL_MAX = 250; /* ms between frames */
const int ACK_INTERVAL = 3000; /* ms between empty acks */
const int ACK_DELAY = 100; /* ms before delayed ack */
const int SHUTDOWN_RETRIES = 16; /* number of shutdown packets to send before giving up */
const int ACTIVE_RETRY_TIMEOUT = 10000; /* attempt to resend at frame rate */
template<class MyState>
class TransportSender
{
private:
/* helper methods for tick() */
void update_assumed_receiver_state( void );
void attempt_prospective_resend_optimization( std::string& proposed_diff );
void rationalize_states( void );
void send_to_receiver( const std::string& diff );
void send_empty_ack( void );
void send_in_fragments( const std::string& diff, uint64_t new_num );
void add_sent_state( uint64_t the_timestamp, uint64_t num, MyState& state );
/* state of sender */
Connection* connection;
MyState current_state;
using sent_states_type = std::list<TimestampedState<MyState>>;
sent_states_type sent_states;
/* first element: known, acknowledged receiver state */
/* last element: last sent state */
/* somewhere in the middle: the assumed state of the receiver */
typename sent_states_type::iterator assumed_receiver_state;
/* for fragment creation */
Fragmenter fragmenter;
/* timing state */
uint64_t next_ack_time;
uint64_t next_send_time;
void calculate_timers( void );
unsigned int verbose;
bool shutdown_in_progress;
int shutdown_tries;
uint64_t shutdown_start;
/* information about receiver state */
uint64_t ack_num;
bool pending_data_ack;
unsigned int SEND_MINDELAY; /* ms to collect all input */
uint64_t last_heard; /* last time received new state */
/* chaff to disguise instruction length */
PRNG prng;
const std::string make_chaff( void );
uint64_t mindelay_clock; /* time of first pending change to current state */
public:
/* constructor */
TransportSender( Connection* s_connection, MyState& initial_state );
/* Send data or an ack if necessary */
void tick( void );
/* Returns the number of ms to wait until next possible event. */
int wait_time( void );
/* Executed upon receipt of ack */
void process_acknowledgment_through( uint64_t ack_num );
/* Executed upon entry to new receiver state */
void set_ack_num( uint64_t s_ack_num );
/* Accelerate reply ack */
void set_data_ack( void ) { pending_data_ack = true; }
/* Received something */
void remote_heard( uint64_t ts ) { last_heard = ts; }
/* Starts shutdown sequence */
void start_shutdown( void )
{
if ( !shutdown_in_progress ) {
shutdown_start = timestamp();
shutdown_in_progress = true;
}
}
/* Misc. getters and setters */
/* Cannot modify current_state while shutdown in progress */
MyState& get_current_state( void )
{
assert( !shutdown_in_progress );
return current_state;
}
void set_current_state( const MyState& x )
{
assert( !shutdown_in_progress );
current_state = x;
current_state.reset_input();
}
void set_verbose( unsigned int s_verbose ) { verbose = s_verbose; }
bool get_shutdown_in_progress( void ) const { return shutdown_in_progress; }
bool get_shutdown_acknowledged( void ) const { return sent_states.front().num == uint64_t( -1 ); }
bool get_counterparty_shutdown_acknowledged( void ) const { return fragmenter.last_ack_sent() == uint64_t( -1 ); }
uint64_t get_sent_state_acked_timestamp( void ) const { return sent_states.front().timestamp; }
uint64_t get_sent_state_acked( void ) const { return sent_states.front().num; }
uint64_t get_sent_state_last( void ) const { return sent_states.back().num; }
bool shutdown_ack_timed_out( void ) const;
void set_send_delay( int new_delay ) { SEND_MINDELAY = new_delay; }
unsigned int send_interval( void ) const;
/* nonexistent methods to satisfy -Weffc++ */
TransportSender( const TransportSender& x );
TransportSender& operator=( const TransportSender& x );
};
}
#endif
| 5,906
|
C++
|
.h
| 136
| 40.036765
| 116
| 0.724306
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,600
|
transportsender-impl.h
|
mobile-shell_mosh/src/network/transportsender-impl.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef TRANSPORT_SENDER_IMPL_HPP
#define TRANSPORT_SENDER_IMPL_HPP
#include <algorithm>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <list>
#include "src/network/transportfragment.h"
#include "src/network/transportsender.h"
#include "src/util/fatal_assert.h"
using namespace Network;
template<class MyState>
TransportSender<MyState>::TransportSender( Connection* s_connection, MyState& initial_state )
: connection( s_connection ), current_state( initial_state ),
sent_states( 1, TimestampedState<MyState>( timestamp(), 0, initial_state ) ),
assumed_receiver_state( sent_states.begin() ), fragmenter(), next_ack_time( timestamp() ),
next_send_time( timestamp() ), verbose( 0 ), shutdown_in_progress( false ), shutdown_tries( 0 ),
shutdown_start( -1 ), ack_num( 0 ), pending_data_ack( false ), SEND_MINDELAY( 8 ), last_heard( 0 ), prng(),
mindelay_clock( -1 )
{}
/* Try to send roughly two frames per RTT, bounded by limits on frame rate */
template<class MyState>
unsigned int TransportSender<MyState>::send_interval( void ) const
{
int SEND_INTERVAL = lrint( ceil( connection->get_SRTT() / 2.0 ) );
if ( SEND_INTERVAL < SEND_INTERVAL_MIN ) {
SEND_INTERVAL = SEND_INTERVAL_MIN;
} else if ( SEND_INTERVAL > SEND_INTERVAL_MAX ) {
SEND_INTERVAL = SEND_INTERVAL_MAX;
}
return SEND_INTERVAL;
}
/* Housekeeping routine to calculate next send and ack times */
template<class MyState>
void TransportSender<MyState>::calculate_timers( void )
{
uint64_t now = timestamp();
/* Update assumed receiver state */
update_assumed_receiver_state();
/* Cut out common prefix of all states */
rationalize_states();
if ( pending_data_ack && ( next_ack_time > now + ACK_DELAY ) ) {
next_ack_time = now + ACK_DELAY;
}
if ( !( current_state == sent_states.back().state ) ) {
if ( mindelay_clock == uint64_t( -1 ) ) {
mindelay_clock = now;
}
next_send_time = std::max( mindelay_clock + SEND_MINDELAY, sent_states.back().timestamp + send_interval() );
} else if ( !( current_state == assumed_receiver_state->state ) && ( last_heard + ACTIVE_RETRY_TIMEOUT > now ) ) {
next_send_time = sent_states.back().timestamp + send_interval();
if ( mindelay_clock != uint64_t( -1 ) ) {
next_send_time = std::max( next_send_time, mindelay_clock + SEND_MINDELAY );
}
} else if ( !( current_state == sent_states.front().state ) && ( last_heard + ACTIVE_RETRY_TIMEOUT > now ) ) {
next_send_time = sent_states.back().timestamp + connection->timeout() + ACK_DELAY;
} else {
next_send_time = uint64_t( -1 );
}
/* speed up shutdown sequence */
if ( shutdown_in_progress || ( ack_num == uint64_t( -1 ) ) ) {
next_ack_time = sent_states.back().timestamp + send_interval();
}
}
/* How many ms to wait until next event */
template<class MyState>
int TransportSender<MyState>::wait_time( void )
{
calculate_timers();
uint64_t next_wakeup = next_ack_time;
if ( next_send_time < next_wakeup ) {
next_wakeup = next_send_time;
}
uint64_t now = timestamp();
if ( !connection->get_has_remote_addr() ) {
return INT_MAX;
}
if ( next_wakeup > now ) {
return next_wakeup - now;
} else {
return 0;
}
}
/* Send data or an empty ack if necessary */
template<class MyState>
void TransportSender<MyState>::tick( void )
{
calculate_timers(); /* updates assumed receiver state and rationalizes */
if ( !connection->get_has_remote_addr() ) {
return;
}
uint64_t now = timestamp();
if ( ( now < next_ack_time ) && ( now < next_send_time ) ) {
return;
}
/* Determine if a new diff or empty ack needs to be sent */
std::string diff = current_state.diff_from( assumed_receiver_state->state );
attempt_prospective_resend_optimization( diff );
if ( verbose ) {
/* verify diff has round-trip identity (modulo Unicode fallback rendering) */
MyState newstate( assumed_receiver_state->state );
newstate.apply_string( diff );
if ( current_state.compare( newstate ) ) {
fprintf( stderr, "Warning, round-trip Instruction verification failed!\n" );
}
/* Also verify that both the original frame and generated frame have the same initial diff. */
std::string current_diff( current_state.init_diff() );
std::string new_diff( newstate.init_diff() );
if ( current_diff != new_diff ) {
fprintf( stderr, "Warning, target state Instruction verification failed!\n" );
}
}
if ( diff.empty() ) {
if ( ( now >= next_ack_time ) ) {
send_empty_ack();
mindelay_clock = uint64_t( -1 );
}
if ( ( now >= next_send_time ) ) {
next_send_time = uint64_t( -1 );
mindelay_clock = uint64_t( -1 );
}
} else if ( ( now >= next_send_time ) || ( now >= next_ack_time ) ) {
/* Send diffs or ack */
send_to_receiver( diff );
mindelay_clock = uint64_t( -1 );
}
}
template<class MyState>
void TransportSender<MyState>::send_empty_ack( void )
{
uint64_t now = timestamp();
assert( now >= next_ack_time );
uint64_t new_num = sent_states.back().num + 1;
/* special case for shutdown sequence */
if ( shutdown_in_progress ) {
new_num = uint64_t( -1 );
}
// sent_states.push_back( TimestampedState<MyState>( sent_states.back().timestamp, new_num, current_state ) );
add_sent_state( now, new_num, current_state );
send_in_fragments( "", new_num );
next_ack_time = now + ACK_INTERVAL;
next_send_time = uint64_t( -1 );
}
template<class MyState>
void TransportSender<MyState>::add_sent_state( uint64_t the_timestamp, uint64_t num, MyState& state )
{
sent_states.push_back( TimestampedState<MyState>( the_timestamp, num, state ) );
if ( sent_states.size() > 32 ) { /* limit on state queue */
typename sent_states_type::iterator last = sent_states.end();
for ( int i = 0; i < 16; i++ ) {
last--;
}
sent_states.erase( last ); /* erase state from middle of queue */
}
}
template<class MyState>
void TransportSender<MyState>::send_to_receiver( const std::string& diff )
{
uint64_t new_num;
if ( current_state == sent_states.back().state ) { /* previously sent */
new_num = sent_states.back().num;
} else { /* new state */
new_num = sent_states.back().num + 1;
}
/* special case for shutdown sequence */
if ( shutdown_in_progress ) {
new_num = uint64_t( -1 );
}
if ( new_num == sent_states.back().num ) {
sent_states.back().timestamp = timestamp();
} else {
add_sent_state( timestamp(), new_num, current_state );
}
send_in_fragments( diff, new_num ); // Can throw NetworkException
/* successfully sent, probably */
/* ("probably" because the FIRST size-exceeded datagram doesn't get an error) */
assumed_receiver_state = sent_states.end();
assumed_receiver_state--;
next_ack_time = timestamp() + ACK_INTERVAL;
next_send_time = uint64_t( -1 );
}
template<class MyState>
void TransportSender<MyState>::update_assumed_receiver_state( void )
{
uint64_t now = timestamp();
/* start from what is known and give benefit of the doubt to unacknowledged states
transmitted recently enough ago */
assumed_receiver_state = sent_states.begin();
typename std::list<TimestampedState<MyState>>::iterator i = sent_states.begin();
i++;
while ( i != sent_states.end() ) {
assert( now >= i->timestamp );
if ( uint64_t( now - i->timestamp ) < connection->timeout() + ACK_DELAY ) {
assumed_receiver_state = i;
} else {
return;
}
i++;
}
}
template<class MyState>
void TransportSender<MyState>::rationalize_states( void )
{
const MyState* known_receiver_state = &sent_states.front().state;
current_state.subtract( known_receiver_state );
for ( typename std::list<TimestampedState<MyState>>::reverse_iterator i = sent_states.rbegin();
i != sent_states.rend();
i++ ) {
i->state.subtract( known_receiver_state );
}
}
template<class MyState>
const std::string TransportSender<MyState>::make_chaff( void )
{
const size_t CHAFF_MAX = 16;
const size_t chaff_len = prng.uint8() % ( CHAFF_MAX + 1 );
char chaff[CHAFF_MAX];
prng.fill( chaff, chaff_len );
return std::string( chaff, chaff_len );
}
template<class MyState>
void TransportSender<MyState>::send_in_fragments( const std::string& diff, uint64_t new_num )
{
Instruction inst;
inst.set_protocol_version( MOSH_PROTOCOL_VERSION );
inst.set_old_num( assumed_receiver_state->num );
inst.set_new_num( new_num );
inst.set_ack_num( ack_num );
inst.set_throwaway_num( sent_states.front().num );
inst.set_diff( diff );
inst.set_chaff( make_chaff() );
if ( new_num == uint64_t( -1 ) ) {
shutdown_tries++;
}
std::vector<Fragment> fragments = fragmenter.make_fragments(
inst, connection->get_MTU() - Network::Connection::ADDED_BYTES - Crypto::Session::ADDED_BYTES );
for ( std::vector<Fragment>::iterator i = fragments.begin(); i != fragments.end(); i++ ) {
connection->send( i->tostring() );
if ( verbose ) {
fprintf(
stderr,
"[%u] Sent [%d=>%d] id %d, frag %d ack=%d, throwaway=%d, len=%d, frame rate=%.2f, timeout=%d, srtt=%.1f\n",
(unsigned int)( timestamp() % 100000 ),
(int)inst.old_num(),
(int)inst.new_num(),
(int)i->id,
(int)i->fragment_num,
(int)inst.ack_num(),
(int)inst.throwaway_num(),
(int)i->contents.size(),
1000.0 / (double)send_interval(),
(int)connection->timeout(),
connection->get_SRTT() );
}
}
pending_data_ack = false;
}
template<class MyState>
void TransportSender<MyState>::process_acknowledgment_through( uint64_t ack_num )
{
/* Ignore ack if we have culled the state it's acknowledging */
typename sent_states_type::iterator i;
for ( i = sent_states.begin(); i != sent_states.end(); i++ ) {
if ( i->num == ack_num ) {
break;
}
}
if ( i != sent_states.end() ) {
for ( i = sent_states.begin(); i != sent_states.end(); ) {
typename sent_states_type::iterator i_next = i;
i_next++;
if ( i->num < ack_num ) {
sent_states.erase( i );
}
i = i_next;
}
}
assert( !sent_states.empty() );
}
/* give up on getting acknowledgement for shutdown */
template<class MyState>
bool TransportSender<MyState>::shutdown_ack_timed_out( void ) const
{
if ( shutdown_in_progress ) {
if ( shutdown_tries >= SHUTDOWN_RETRIES ) {
return true;
} else if ( timestamp() - shutdown_start >= uint64_t( ACTIVE_RETRY_TIMEOUT ) ) {
return true;
}
}
return false;
}
/* Executed upon entry to new receiver state */
template<class MyState>
void TransportSender<MyState>::set_ack_num( uint64_t s_ack_num )
{
ack_num = s_ack_num;
}
/* Investigate diff against known receiver state instead */
/* Mutates proposed_diff */
template<class MyState>
void TransportSender<MyState>::attempt_prospective_resend_optimization( std::string& proposed_diff )
{
if ( assumed_receiver_state == sent_states.begin() ) {
return;
}
std::string resend_diff = current_state.diff_from( sent_states.front().state );
/* We do a prophylactic resend if it would make the diff shorter,
or if it would lengthen it by no more than 100 bytes and still be
less than 1000 bytes. */
if ( ( resend_diff.size() <= proposed_diff.size() )
|| ( ( resend_diff.size() < 1000 ) && ( resend_diff.size() - proposed_diff.size() < 100 ) ) ) {
assumed_receiver_state = sent_states.begin();
proposed_diff = resend_diff;
}
}
#endif
| 13,028
|
C++
|
.h
| 344
| 34.055233
| 116
| 0.671874
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
10,601
|
transportfragment.h
|
mobile-shell_mosh/src/network/transportfragment.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef TRANSPORT_FRAGMENT_HPP
#define TRANSPORT_FRAGMENT_HPP
#include <cstdint>
#include <string>
#include <vector>
#include "src/protobufs/transportinstruction.pb.h"
namespace Network {
using namespace TransportBuffers;
class Fragment
{
public:
static const size_t frag_header_len = sizeof( uint64_t ) + sizeof( uint16_t );
uint64_t id;
uint16_t fragment_num;
bool final;
bool initialized;
std::string contents;
Fragment() : id( -1 ), fragment_num( -1 ), final( false ), initialized( false ), contents() {}
Fragment( uint64_t s_id, uint16_t s_fragment_num, bool s_final, const std::string& s_contents )
: id( s_id ), fragment_num( s_fragment_num ), final( s_final ), initialized( true ), contents( s_contents )
{}
Fragment( const std::string& x );
std::string tostring( void );
bool operator==( const Fragment& x ) const;
};
class FragmentAssembly
{
private:
std::vector<Fragment> fragments;
uint64_t current_id;
int fragments_arrived, fragments_total;
public:
FragmentAssembly() : fragments(), current_id( -1 ), fragments_arrived( 0 ), fragments_total( -1 ) {}
bool add_fragment( Fragment& inst );
Instruction get_assembly( void );
};
class Fragmenter
{
private:
uint64_t next_instruction_id;
Instruction last_instruction;
size_t last_MTU;
public:
Fragmenter() : next_instruction_id( 0 ), last_instruction(), last_MTU( -1 )
{
last_instruction.set_old_num( -1 );
last_instruction.set_new_num( -1 );
}
std::vector<Fragment> make_fragments( const Instruction& inst, size_t MTU );
uint64_t last_ack_sent( void ) const { return last_instruction.ack_num(); }
};
}
#endif
| 3,120
|
C++
|
.h
| 79
| 36.164557
| 111
| 0.737488
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,602
|
network.h
|
mobile-shell_mosh/src/network/network.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef NETWORK_HPP
#define NETWORK_HPP
#include <cassert>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <deque>
#include <exception>
#include <string>
#include <vector>
#include <netinet/in.h>
#include <sys/socket.h>
#include "src/crypto/crypto.h"
using namespace Crypto;
namespace Network {
static const unsigned int MOSH_PROTOCOL_VERSION = 2; /* bumped for echo-ack */
uint64_t timestamp( void );
uint16_t timestamp16( void );
uint16_t timestamp_diff( uint16_t tsnew, uint16_t tsold );
class NetworkException : public std::exception
{
public:
std::string function;
int the_errno;
private:
std::string my_what;
public:
NetworkException( std::string s_function = "<none>", int s_errno = 0 )
: function( s_function ), the_errno( s_errno ), my_what( function + ": " + strerror( the_errno ) )
{}
const char* what() const throw() { return my_what.c_str(); }
~NetworkException() throw() {}
};
enum Direction
{
TO_SERVER = 0,
TO_CLIENT = 1
};
class Packet
{
public:
const uint64_t seq;
Direction direction;
uint16_t timestamp, timestamp_reply;
std::string payload;
Packet( Direction s_direction, uint16_t s_timestamp, uint16_t s_timestamp_reply, const std::string& s_payload )
: seq( Crypto::unique() ), direction( s_direction ), timestamp( s_timestamp ),
timestamp_reply( s_timestamp_reply ), payload( s_payload )
{}
Packet( const Message& message );
Message toMessage( void );
};
union Addr {
struct sockaddr sa;
struct sockaddr_in sin;
struct sockaddr_in6 sin6;
struct sockaddr_storage ss;
};
class Connection
{
private:
/*
* For IPv4, guess the typical (minimum) header length;
* fragmentation is not dangerous, just inefficient.
*/
static const int IPV4_HEADER_LEN = 20 /* base IP header */
+ 8 /* UDP */;
/*
* For IPv6, we don't want to ever have MTU issues, so make a
* conservative guess about header size.
*/
static const int IPV6_HEADER_LEN = 40 /* base IPv6 header */
+ 16 /* 2 minimum-sized extension headers */
+ 8 /* UDP */;
/* Application datagram MTU. For constructors and fallback. */
static const int DEFAULT_SEND_MTU = 500;
/*
* IPv4 MTU. Don't use full Ethernet-derived MTU,
* mobile networks have high tunneling overhead.
*
* As of July 2016, VPN traffic over Amtrak Acela wifi seems to be
* dropped if tunnelled packets are 1320 bytes or larger. Use a
* 1280-byte IPv4 MTU for now.
*
* We may have to implement ICMP-less PMTUD (RFC 4821) eventually.
*/
static const int DEFAULT_IPV4_MTU = 1280;
/* IPv6 MTU. Use the guaranteed minimum to avoid fragmentation. */
static const int DEFAULT_IPV6_MTU = 1280;
static const uint64_t MIN_RTO = 50; /* ms */
static const uint64_t MAX_RTO = 1000; /* ms */
static const int PORT_RANGE_LOW = 60001;
static const int PORT_RANGE_HIGH = 60999;
static const unsigned int SERVER_ASSOCIATION_TIMEOUT = 40000;
static const unsigned int PORT_HOP_INTERVAL = 10000;
static const unsigned int MAX_PORTS_OPEN = 10;
static const unsigned int MAX_OLD_SOCKET_AGE = 60000;
static const int CONGESTION_TIMESTAMP_PENALTY = 500; /* ms */
bool try_bind( const char* addr, int port_low, int port_high );
class Socket
{
private:
int _fd;
public:
int fd( void ) const { return _fd; }
Socket( int family );
~Socket();
Socket( const Socket& other );
Socket& operator=( const Socket& other );
};
std::deque<Socket> socks;
bool has_remote_addr;
Addr remote_addr;
socklen_t remote_addr_len;
bool server;
int MTU; /* application datagram MTU */
Base64Key key;
Session session;
void setup( void );
Direction direction;
uint16_t saved_timestamp;
uint64_t saved_timestamp_received_at;
uint64_t expected_receiver_seq;
uint64_t last_heard;
uint64_t last_port_choice;
uint64_t last_roundtrip_success; /* transport layer needs to tell us this */
bool RTT_hit;
double SRTT;
double RTTVAR;
/* Error from send()/sendto(). */
std::string send_error;
Packet new_packet( const std::string& s_payload );
void hop_port( void );
int sock( void ) const
{
assert( !socks.empty() );
return socks.back().fd();
}
void prune_sockets( void );
std::string recv_one( int sock_to_recv );
void set_MTU( int family );
public:
/* Network transport overhead. */
static const int ADDED_BYTES = 8 /* seqno/nonce */ + 4 /* timestamps */;
Connection( const char* desired_ip, const char* desired_port ); /* server */
Connection( const char* key_str, const char* ip, const char* port ); /* client */
void send( const std::string& s );
std::string recv( void );
const std::vector<int> fds( void ) const;
int get_MTU( void ) const { return MTU; }
std::string port( void ) const;
std::string get_key( void ) const { return key.printable_key(); }
bool get_has_remote_addr( void ) const { return has_remote_addr; }
uint64_t timeout( void ) const;
double get_SRTT( void ) const { return SRTT; }
const Addr& get_remote_addr( void ) const { return remote_addr; }
socklen_t get_remote_addr_len( void ) const { return remote_addr_len; }
std::string& get_send_error( void ) { return send_error; }
void set_last_roundtrip_success( uint64_t s_success ) { last_roundtrip_success = s_success; }
static bool parse_portrange( const char* desired_port_range, int& desired_port_low, int& desired_port_high );
};
}
#endif
| 7,028
|
C++
|
.h
| 189
| 33.328042
| 113
| 0.701165
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,603
|
transportstate.h
|
mobile-shell_mosh/src/network/transportstate.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef TRANSPORT_STATE_HPP
#define TRANSPORT_STATE_HPP
namespace Network {
template<class State>
class TimestampedState
{
public:
uint64_t timestamp;
uint64_t num;
State state;
TimestampedState( uint64_t s_timestamp, uint64_t s_num, const State& s_state )
: timestamp( s_timestamp ), num( s_num ), state( s_state )
{}
};
}
#endif
| 1,818
|
C++
|
.h
| 42
| 39.452381
| 80
| 0.757216
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,604
|
stmclient.h
|
mobile-shell_mosh/src/frontend/stmclient.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef STM_CLIENT_HPP
#define STM_CLIENT_HPP
#include <memory>
#include <string>
#include <sys/ioctl.h>
#include <termios.h>
#include "src/frontend/terminaloverlay.h"
#include "src/network/networktransport.h"
#include "src/statesync/completeterminal.h"
#include "src/statesync/user.h"
class STMClient
{
private:
std::string ip;
std::string port;
std::string key;
int escape_key;
int escape_pass_key;
int escape_pass_key2;
bool escape_requires_lf;
std::wstring escape_key_help;
struct termios saved_termios, raw_termios;
struct winsize window_size;
Terminal::Framebuffer local_framebuffer, new_state;
Overlay::OverlayManager overlays;
using NetworkType = Network::Transport<Network::UserStream, Terminal::Complete>;
using NetworkPointer = std::shared_ptr<NetworkType>;
NetworkPointer network;
Terminal::Display display;
std::wstring connecting_notification;
bool repaint_requested, lf_entered, quit_sequence_started;
bool clean_shutdown;
unsigned int verbose;
void main_init( void );
void process_network_input( void );
bool process_user_input( int fd );
bool process_resize( void );
void output_new_frame( void );
bool still_connecting( void ) const
{
/* Initially, network == NULL */
return network && ( network->get_remote_state_num() == 0 );
}
void resume( void ); /* restore state after SIGCONT */
public:
STMClient( const char* s_ip,
const char* s_port,
const char* s_key,
const char* predict_mode,
unsigned int s_verbose,
const char* predict_overwrite )
: ip( s_ip ? s_ip : "" ), port( s_port ? s_port : "" ), key( s_key ? s_key : "" ), escape_key( 0x1E ),
escape_pass_key( '^' ), escape_pass_key2( '^' ), escape_requires_lf( false ), escape_key_help( L"?" ),
saved_termios(), raw_termios(), window_size(), local_framebuffer( 1, 1 ), new_state( 1, 1 ), overlays(),
network(), display( true ) /* use TERM environment var to initialize display */, connecting_notification(),
repaint_requested( false ), lf_entered( false ), quit_sequence_started( false ), clean_shutdown( false ),
verbose( s_verbose )
{
if ( predict_mode ) {
if ( !strcmp( predict_mode, "always" ) ) {
overlays.get_prediction_engine().set_display_preference( Overlay::PredictionEngine::Always );
} else if ( !strcmp( predict_mode, "never" ) ) {
overlays.get_prediction_engine().set_display_preference( Overlay::PredictionEngine::Never );
} else if ( !strcmp( predict_mode, "adaptive" ) ) {
overlays.get_prediction_engine().set_display_preference( Overlay::PredictionEngine::Adaptive );
} else if ( !strcmp( predict_mode, "experimental" ) ) {
overlays.get_prediction_engine().set_display_preference( Overlay::PredictionEngine::Experimental );
} else {
fprintf( stderr, "Unknown prediction mode %s.\n", predict_mode );
exit( 1 );
}
}
if ( predict_overwrite && !strcmp( predict_overwrite, "yes" ) ) {
overlays.get_prediction_engine().set_predict_overwrite( true );
}
}
void init( void );
void shutdown( void );
bool main( void );
/* unused */
STMClient( const STMClient& );
STMClient& operator=( const STMClient& );
};
#endif
| 4,771
|
C++
|
.h
| 110
| 38.663636
| 113
| 0.701164
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,605
|
terminaloverlay.h
|
mobile-shell_mosh/src/frontend/terminaloverlay.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef TERMINAL_OVERLAY_HPP
#define TERMINAL_OVERLAY_HPP
#include "src/network/network.h"
#include "src/network/transportsender.h"
#include "src/terminal/parser.h"
#include "src/terminal/terminalframebuffer.h"
#include <climits>
#include <vector>
namespace Overlay {
using namespace Terminal;
using namespace Network;
enum Validity
{
Pending,
Correct,
CorrectNoCredit,
IncorrectOrExpired,
Inactive
};
class ConditionalOverlay
{
public:
uint64_t expiration_frame;
int col;
bool active; /* represents a prediction at all */
uint64_t tentative_until_epoch; /* when to show */
uint64_t prediction_time; /* used to find long-pending predictions */
ConditionalOverlay( uint64_t s_exp, int s_col, uint64_t s_tentative )
: expiration_frame( s_exp ), col( s_col ), active( false ), tentative_until_epoch( s_tentative ),
prediction_time( uint64_t( -1 ) )
{}
virtual ~ConditionalOverlay() {}
bool tentative( uint64_t confirmed_epoch ) const { return tentative_until_epoch > confirmed_epoch; }
void reset( void )
{
expiration_frame = tentative_until_epoch = -1;
active = false;
}
void expire( uint64_t s_exp, uint64_t now )
{
expiration_frame = s_exp;
prediction_time = now;
}
};
class ConditionalCursorMove : public ConditionalOverlay
{
public:
int row;
void apply( Framebuffer& fb, uint64_t confirmed_epoch ) const;
Validity get_validity( const Framebuffer& fb, uint64_t early_ack, uint64_t late_ack ) const;
ConditionalCursorMove( uint64_t s_exp, int s_row, int s_col, uint64_t s_tentative )
: ConditionalOverlay( s_exp, s_col, s_tentative ), row( s_row )
{}
};
class ConditionalOverlayCell : public ConditionalOverlay
{
public:
Cell replacement;
bool unknown;
std::vector<Cell> original_contents; /* we don't give credit for correct predictions
that match the original contents */
void apply( Framebuffer& fb, uint64_t confirmed_epoch, int row, bool flag ) const;
Validity get_validity( const Framebuffer& fb, int row, uint64_t early_ack, uint64_t late_ack ) const;
ConditionalOverlayCell( uint64_t s_exp, int s_col, uint64_t s_tentative )
: ConditionalOverlay( s_exp, s_col, s_tentative ), replacement( 0 ), unknown( false ), original_contents()
{}
void reset( void )
{
unknown = false;
original_contents.clear();
ConditionalOverlay::reset();
}
void reset_with_orig( void )
{
if ( ( !active ) || unknown ) {
reset();
return;
}
original_contents.push_back( replacement );
ConditionalOverlay::reset();
}
};
class ConditionalOverlayRow
{
public:
int row_num;
using overlay_cells_type = std::vector<ConditionalOverlayCell>;
overlay_cells_type overlay_cells;
void apply( Framebuffer& fb, uint64_t confirmed_epoch, bool flag ) const;
ConditionalOverlayRow( int s_row_num ) : row_num( s_row_num ), overlay_cells() {}
};
/* the various overlays */
class NotificationEngine
{
private:
uint64_t last_word_from_server;
uint64_t last_acked_state;
std::string escape_key_string;
std::wstring message;
bool message_is_network_error;
uint64_t message_expiration;
bool show_quit_keystroke;
bool server_late( uint64_t ts ) const { return ( ts - last_word_from_server ) > 6500; }
bool reply_late( uint64_t ts ) const { return ( ts - last_acked_state ) > 10000; }
bool need_countup( uint64_t ts ) const { return server_late( ts ) || reply_late( ts ); }
public:
void adjust_message( void );
void apply( Framebuffer& fb ) const;
const std::wstring& get_notification_string( void ) const { return message; }
void server_heard( uint64_t s_last_word ) { last_word_from_server = s_last_word; }
void server_acked( uint64_t s_last_acked ) { last_acked_state = s_last_acked; }
int wait_time( void ) const;
void set_notification_string( const std::wstring& s_message,
bool permanent = false,
bool s_show_quit_keystroke = true )
{
message = s_message;
if ( permanent ) {
message_expiration = -1;
} else {
message_expiration = timestamp() + 1000;
}
message_is_network_error = false;
show_quit_keystroke = s_show_quit_keystroke;
}
void set_escape_key_string( const std::string& s_name )
{
char tmp[128];
snprintf( tmp, sizeof tmp, " [To quit: %s .]", s_name.c_str() );
escape_key_string = tmp;
}
void set_network_error( const std::string& s )
{
wchar_t tmp[128];
swprintf( tmp, 128, L"%s", s.c_str() );
message = tmp;
message_is_network_error = true;
message_expiration = timestamp() + Network::ACK_INTERVAL + 100;
}
void clear_network_error()
{
if ( message_is_network_error ) {
message_expiration = std::min( message_expiration, timestamp() + 1000 );
}
}
NotificationEngine();
};
class PredictionEngine
{
private:
static const uint64_t SRTT_TRIGGER_LOW = 20; /* <= ms cures SRTT trigger to show predictions */
static const uint64_t SRTT_TRIGGER_HIGH = 30; /* > ms starts SRTT trigger */
static const uint64_t FLAG_TRIGGER_LOW = 50; /* <= ms cures flagging */
static const uint64_t FLAG_TRIGGER_HIGH = 80; /* > ms starts flagging */
static const uint64_t GLITCH_THRESHOLD = 250; /* prediction outstanding this long is glitch */
static const uint64_t GLITCH_REPAIR_COUNT = 10; /* non-glitches required to cure glitch trigger */
static const uint64_t GLITCH_REPAIR_MININTERVAL = 150; /* required time in between non-glitches */
static const uint64_t GLITCH_FLAG_THRESHOLD = 5000; /* prediction outstanding this long => underline */
char last_byte;
Parser::UTF8Parser parser;
using overlays_type = std::list<ConditionalOverlayRow>;
overlays_type overlays;
using cursors_type = std::list<ConditionalCursorMove>;
cursors_type cursors;
using overlay_cells_type = ConditionalOverlayRow::overlay_cells_type;
uint64_t local_frame_sent, local_frame_acked, local_frame_late_acked;
ConditionalOverlayRow& get_or_make_row( int row_num, int num_cols );
uint64_t prediction_epoch;
uint64_t confirmed_epoch;
void become_tentative( void );
void newline_carriage_return( const Framebuffer& fb );
bool flagging; /* whether we are underlining predictions */
bool srtt_trigger; /* show predictions because of slow round trip time */
unsigned int glitch_trigger; /* show predictions temporarily because of long-pending prediction */
uint64_t last_quick_confirmation;
ConditionalCursorMove& cursor( void )
{
assert( !cursors.empty() );
return cursors.back();
}
void kill_epoch( uint64_t epoch, const Framebuffer& fb );
void init_cursor( const Framebuffer& fb );
unsigned int send_interval;
int last_height, last_width;
public:
enum DisplayPreference
{
Always,
Never,
Adaptive,
Experimental
};
private:
DisplayPreference display_preference;
bool predict_overwrite;
bool active( void ) const;
bool timing_tests_necessary( void ) const
{
/* Are there any timing-based triggers that haven't fired yet? */
return !( glitch_trigger && flagging );
}
public:
void set_display_preference( DisplayPreference s_pref ) { display_preference = s_pref; }
void set_predict_overwrite( bool overwrite ) { predict_overwrite = overwrite; }
void apply( Framebuffer& fb ) const;
void new_user_byte( char the_byte, const Framebuffer& fb );
void cull( const Framebuffer& fb );
void reset( void );
void set_local_frame_sent( uint64_t x ) { local_frame_sent = x; }
void set_local_frame_acked( uint64_t x ) { local_frame_acked = x; }
void set_local_frame_late_acked( uint64_t x ) { local_frame_late_acked = x; }
void set_send_interval( unsigned int x ) { send_interval = x; }
int wait_time( void ) const { return ( timing_tests_necessary() && active() ) ? 50 : INT_MAX; }
PredictionEngine( void )
: last_byte( 0 ), parser(), overlays(), cursors(), local_frame_sent( 0 ), local_frame_acked( 0 ),
local_frame_late_acked( 0 ), prediction_epoch( 1 ), confirmed_epoch( 0 ), flagging( false ),
srtt_trigger( false ), glitch_trigger( 0 ), last_quick_confirmation( 0 ), send_interval( 250 ),
last_height( 0 ), last_width( 0 ), display_preference( Adaptive ), predict_overwrite( false )
{}
};
class TitleEngine
{
private:
Terminal::Framebuffer::title_type prefix;
public:
void apply( Framebuffer& fb ) const { fb.prefix_window_title( prefix ); }
TitleEngine() : prefix() {}
void set_prefix( const std::wstring& s );
};
/* the overlay manager */
class OverlayManager
{
private:
NotificationEngine notifications;
PredictionEngine predictions;
TitleEngine title;
public:
void apply( Framebuffer& fb );
NotificationEngine& get_notification_engine( void ) { return notifications; }
PredictionEngine& get_prediction_engine( void ) { return predictions; }
void set_title_prefix( const std::wstring& s ) { title.set_prefix( s ); }
OverlayManager() : notifications(), predictions(), title() {}
int wait_time( void ) const { return std::min( notifications.wait_time(), predictions.wait_time() ); }
};
}
#endif
| 10,705
|
C++
|
.h
| 272
| 35.540441
| 110
| 0.707444
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,606
|
terminaluserinput.h
|
mobile-shell_mosh/src/terminal/terminaluserinput.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef TERMINALUSERINPUT_HPP
#define TERMINALUSERINPUT_HPP
#include "src/terminal/parseraction.h"
#include <string>
namespace Terminal {
class UserInput
{
public:
enum UserInputState
{
Ground,
ESC,
SS3
};
private:
UserInputState state;
public:
UserInput() : state( Ground ) {}
std::string input( const Parser::UserByte* act, bool application_mode_cursor_keys );
bool operator==( const UserInput& x ) const { return state == x.state; }
};
}
#endif
| 1,951
|
C++
|
.h
| 49
| 36.061224
| 86
| 0.755426
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,607
|
parser.h
|
mobile-shell_mosh/src/terminal/parser.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef PARSER_HPP
#define PARSER_HPP
/* Based on Paul Williams's parser,
http://www.vt100.net/emu/dec_ansi_parser */
#include <cstring>
#include <cwchar>
#include "parserstate.h"
#include "parserstatefamily.h"
#include "parsertransition.h"
#include "src/terminal/parseraction.h"
namespace Parser {
extern const StateFamily family;
class Parser
{
private:
State const* state;
public:
Parser() : state( &family.s_Ground ) {}
Parser( const Parser& other );
Parser& operator=( const Parser& );
~Parser() {}
void input( wchar_t ch, Actions& actions );
void reset_input( void ) { state = &family.s_Ground; }
};
static const size_t BUF_SIZE = 8;
class UTF8Parser
{
private:
Parser parser;
char buf[BUF_SIZE];
size_t buf_len;
public:
UTF8Parser();
void input( char c, Actions& actions );
void reset_input( void )
{
parser.reset_input();
buf[0] = '\0';
buf_len = 0;
}
};
}
#endif
| 2,403
|
C++
|
.h
| 69
| 31.463768
| 73
| 0.739619
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,608
|
parserstatefamily.h
|
mobile-shell_mosh/src/terminal/parserstatefamily.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef PARSERSTATEFAMILY_HPP
#define PARSERSTATEFAMILY_HPP
#include "parserstate.h"
namespace Parser {
class StateFamily
{
public:
Ground s_Ground;
Escape s_Escape;
Escape_Intermediate s_Escape_Intermediate;
CSI_Entry s_CSI_Entry;
CSI_Param s_CSI_Param;
CSI_Intermediate s_CSI_Intermediate;
CSI_Ignore s_CSI_Ignore;
DCS_Entry s_DCS_Entry;
DCS_Param s_DCS_Param;
DCS_Intermediate s_DCS_Intermediate;
DCS_Passthrough s_DCS_Passthrough;
DCS_Ignore s_DCS_Ignore;
OSC_String s_OSC_String;
SOS_PM_APC_String s_SOS_PM_APC_String;
StateFamily()
: s_Ground(), s_Escape(), s_Escape_Intermediate(), s_CSI_Entry(), s_CSI_Param(), s_CSI_Intermediate(),
s_CSI_Ignore(), s_DCS_Entry(), s_DCS_Param(), s_DCS_Intermediate(), s_DCS_Passthrough(), s_DCS_Ignore(),
s_OSC_String(), s_SOS_PM_APC_String()
{
s_Ground.setfamily( this );
s_Escape.setfamily( this );
s_Escape_Intermediate.setfamily( this );
s_CSI_Entry.setfamily( this );
s_CSI_Param.setfamily( this );
s_CSI_Intermediate.setfamily( this );
s_CSI_Ignore.setfamily( this );
s_DCS_Entry.setfamily( this );
s_DCS_Param.setfamily( this );
s_DCS_Intermediate.setfamily( this );
s_DCS_Passthrough.setfamily( this );
s_DCS_Ignore.setfamily( this );
s_OSC_String.setfamily( this );
s_SOS_PM_APC_String.setfamily( this );
}
};
}
#endif
| 2,853
|
C++
|
.h
| 70
| 36.671429
| 110
| 0.732756
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,609
|
terminal.h
|
mobile-shell_mosh/src/terminal/terminal.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef TERMINAL_CPP
#define TERMINAL_CPP
#include <cstdio>
#include <cwchar>
#include <deque>
#include <vector>
#include "src/terminal/parseraction.h"
#include "src/terminal/terminalframebuffer.h"
#include "terminaldispatcher.h"
#include "terminaldisplay.h"
#include "terminaluserinput.h"
namespace Terminal {
class Emulator
{
friend void Parser::Print::act_on_terminal( Emulator* ) const;
friend void Parser::Execute::act_on_terminal( Emulator* ) const;
friend void Parser::Clear::act_on_terminal( Emulator* ) const;
friend void Parser::Param::act_on_terminal( Emulator* ) const;
friend void Parser::Collect::act_on_terminal( Emulator* ) const;
friend void Parser::CSI_Dispatch::act_on_terminal( Emulator* ) const;
friend void Parser::Esc_Dispatch::act_on_terminal( Emulator* ) const;
friend void Parser::OSC_Start::act_on_terminal( Emulator* ) const;
friend void Parser::OSC_Put::act_on_terminal( Emulator* ) const;
friend void Parser::OSC_End::act_on_terminal( Emulator* ) const;
friend void Parser::UserByte::act_on_terminal( Emulator* ) const;
friend void Parser::Resize::act_on_terminal( Emulator* ) const;
private:
Framebuffer fb;
Dispatcher dispatch;
UserInput user;
/* action methods */
void print( const Parser::Print* act );
void execute( const Parser::Execute* act );
void CSI_dispatch( const Parser::CSI_Dispatch* act );
void Esc_dispatch( const Parser::Esc_Dispatch* act );
void OSC_end( const Parser::OSC_End* act );
void resize( size_t s_width, size_t s_height );
public:
Emulator( size_t s_width, size_t s_height );
std::string read_octets_to_host( void );
const Framebuffer& get_fb( void ) const { return fb; }
bool operator==( Emulator const& x ) const;
};
}
#endif
| 3,219
|
C++
|
.h
| 71
| 42.014085
| 73
| 0.749601
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,610
|
terminalframebuffer.h
|
mobile-shell_mosh/src/terminal/terminalframebuffer.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef TERMINALFB_HPP
#define TERMINALFB_HPP
#include <cassert>
#include <climits>
#include <cstdint>
#include <deque>
#include <list>
#include <memory>
#include <string>
#include <vector>
/* Terminal framebuffer */
namespace Terminal {
using color_type = uint32_t;
class Renditions
{
public:
typedef enum
{
bold,
faint,
italic,
underlined,
blink,
inverse,
invisible,
SIZE
} attribute_type;
private:
static const uint64_t true_color_mask = 0x1000000;
uint64_t foreground_color : 25;
uint64_t background_color : 25;
uint64_t attributes : 8;
public:
Renditions( color_type s_background );
void set_foreground_color( int num );
void set_background_color( int num );
void set_rendition( color_type num );
std::string sgr( void ) const;
static unsigned int make_true_color( unsigned int r, unsigned int g, unsigned int b )
{
return true_color_mask | ( r << 16 ) | ( g << 8 ) | b;
}
static bool is_true_color( unsigned int color ) { return ( color & true_color_mask ) != 0; }
// unsigned int get_foreground_rendition() const { return foreground_color; }
unsigned int get_background_rendition() const { return background_color; }
bool operator==( const Renditions& x ) const
{
return ( attributes == x.attributes ) && ( foreground_color == x.foreground_color )
&& ( background_color == x.background_color );
}
void set_attribute( attribute_type attr, bool val )
{
attributes = val ? ( attributes | ( 1 << attr ) ) : ( attributes & ~( 1 << attr ) );
}
bool get_attribute( attribute_type attr ) const { return attributes & ( 1 << attr ); }
void clear_attributes() { attributes = 0; }
};
class Cell
{
private:
typedef std::string content_type; /* can be std::string, std::vector<uint8_t>, or __gnu_cxx::__vstring */
content_type contents;
Renditions renditions;
unsigned int wide : 1; /* 0 = narrow, 1 = wide */
unsigned int fallback : 1; /* first character is combining character */
unsigned int wrap : 1;
private:
Cell();
public:
Cell( color_type background_color );
void reset( color_type background_color );
bool operator==( const Cell& x ) const
{
return ( ( contents == x.contents ) && ( fallback == x.fallback ) && ( wide == x.wide )
&& ( renditions == x.renditions ) && ( wrap == x.wrap ) );
}
bool operator!=( const Cell& x ) const { return !operator==( x ); }
/* Accessors for contents field */
std::string debug_contents( void ) const;
bool empty( void ) const { return contents.empty(); }
/* 32 seems like a reasonable limit on combining characters */
bool full( void ) const { return contents.size() >= 32; }
void clear( void ) { contents.clear(); }
bool is_blank( void ) const
{
// XXX fix.
return ( contents.empty() || contents == " " || contents == "\xC2\xA0" );
}
bool contents_match( const Cell& other ) const
{
return ( is_blank() && other.is_blank() ) || ( contents == other.contents );
}
bool compare( const Cell& other ) const;
// Is this a printing ISO 8859-1 character?
static bool isprint_iso8859_1( const wchar_t c )
{
return ( c <= 0xff && c >= 0xa0 ) || ( c <= 0x7e && c >= 0x20 );
}
static void append_to_str( std::string& dest, const wchar_t c )
{
/* ASCII? Cheat. */
if ( static_cast<uint32_t>( c ) <= 0x7f ) {
dest.push_back( static_cast<char>( c ) );
return;
}
static mbstate_t ps = mbstate_t();
char tmp[MB_LEN_MAX];
size_t ignore = wcrtomb( NULL, 0, &ps );
(void)ignore;
size_t len = wcrtomb( tmp, c, &ps );
dest.append( tmp, len );
}
void append( const wchar_t c )
{
/* ASCII? Cheat. */
if ( static_cast<uint32_t>( c ) <= 0x7f ) {
contents.push_back( static_cast<char>( c ) );
return;
}
static mbstate_t ps = mbstate_t();
char tmp[MB_LEN_MAX];
size_t ignore = wcrtomb( NULL, 0, &ps );
(void)ignore;
size_t len = wcrtomb( tmp, c, &ps );
contents.insert( contents.end(), tmp, tmp + len );
}
void print_grapheme( std::string& output ) const
{
if ( contents.empty() ) {
output.append( 1, ' ' );
return;
}
/*
* cells that begin with combining character get combiner
* attached to no-break space
*/
if ( fallback ) {
output.append( "\xC2\xA0" );
}
output.append( contents );
}
/* Other accessors */
const Renditions& get_renditions( void ) const { return renditions; }
Renditions& get_renditions( void ) { return renditions; }
void set_renditions( const Renditions& r ) { renditions = r; }
bool get_wide( void ) const { return wide; }
void set_wide( bool w ) { wide = w; }
unsigned int get_width( void ) const { return wide + 1; }
bool get_fallback( void ) const { return fallback; }
void set_fallback( bool f ) { fallback = f; }
bool get_wrap( void ) const { return wrap; }
void set_wrap( bool f ) { wrap = f; }
};
class Row
{
public:
typedef std::vector<Cell> cells_type;
cells_type cells;
// gen is a generation counter. It can be used to quickly rule
// out the possibility of two rows being identical; this is useful
// in scrolling.
uint64_t gen;
private:
Row();
public:
Row( const size_t s_width, const color_type background_color );
void insert_cell( int col, color_type background_color );
void delete_cell( int col, color_type background_color );
void reset( color_type background_color );
bool operator==( const Row& x ) const { return ( gen == x.gen && cells == x.cells ); }
bool get_wrap( void ) const { return cells.back().get_wrap(); }
void set_wrap( bool w ) { cells.back().set_wrap( w ); }
uint64_t get_gen() const;
};
class SavedCursor
{
public:
int cursor_col, cursor_row;
Renditions renditions;
/* not implemented: character set shift state */
bool auto_wrap_mode;
bool origin_mode;
/* not implemented: state of selective erase */
SavedCursor();
};
class DrawState
{
private:
int width, height;
void new_grapheme( void );
void snap_cursor_to_border( void );
int cursor_col, cursor_row;
int combining_char_col, combining_char_row;
bool default_tabs;
std::vector<bool> tabs;
void reinitialize_tabs( unsigned int start );
int scrolling_region_top_row, scrolling_region_bottom_row;
Renditions renditions;
SavedCursor save;
public:
bool next_print_will_wrap;
bool origin_mode;
bool auto_wrap_mode;
bool insert_mode;
bool cursor_visible;
bool reverse_video;
bool bracketed_paste;
enum MouseReportingMode
{
MOUSE_REPORTING_NONE = 0,
MOUSE_REPORTING_X10 = 9,
MOUSE_REPORTING_VT220 = 1000,
MOUSE_REPORTING_VT220_HILIGHT = 1001,
MOUSE_REPORTING_BTN_EVENT = 1002,
MOUSE_REPORTING_ANY_EVENT = 1003
} mouse_reporting_mode;
bool mouse_focus_event; // 1004
bool mouse_alternate_scroll; // 1007
enum MouseEncodingMode
{
MOUSE_ENCODING_DEFAULT = 0,
MOUSE_ENCODING_UTF8 = 1005,
MOUSE_ENCODING_SGR = 1006,
MOUSE_ENCODING_URXVT = 1015
} mouse_encoding_mode;
bool application_mode_cursor_keys;
/* bold, etc. */
void move_row( int N, bool relative = false );
void move_col( int N, bool relative = false, bool implicit = false );
int get_cursor_col( void ) const { return cursor_col; }
int get_cursor_row( void ) const { return cursor_row; }
int get_combining_char_col( void ) const { return combining_char_col; }
int get_combining_char_row( void ) const { return combining_char_row; }
int get_width( void ) const { return width; }
int get_height( void ) const { return height; }
void set_tab( void );
void clear_tab( int col );
void clear_default_tabs( void ) { default_tabs = false; }
/* Default tabs can't be restored without resetting the draw state. */
int get_next_tab( int count ) const;
void set_scrolling_region( int top, int bottom );
int get_scrolling_region_top_row( void ) const { return scrolling_region_top_row; }
int get_scrolling_region_bottom_row( void ) const { return scrolling_region_bottom_row; }
int limit_top( void ) const;
int limit_bottom( void ) const;
void set_foreground_color( int x ) { renditions.set_foreground_color( x ); }
void set_background_color( int x ) { renditions.set_background_color( x ); }
void add_rendition( color_type x ) { renditions.set_rendition( x ); }
const Renditions& get_renditions( void ) const { return renditions; }
Renditions& get_renditions( void ) { return renditions; }
int get_background_rendition( void ) const { return renditions.get_background_rendition(); }
void save_cursor( void );
void restore_cursor( void );
void clear_saved_cursor( void ) { save = SavedCursor(); }
void resize( int s_width, int s_height );
DrawState( int s_width, int s_height );
bool operator==( const DrawState& x ) const
{
/* only compare fields that affect display */
return ( width == x.width ) && ( height == x.height ) && ( cursor_col == x.cursor_col )
&& ( cursor_row == x.cursor_row ) && ( cursor_visible == x.cursor_visible )
&& ( reverse_video == x.reverse_video ) && ( renditions == x.renditions )
&& ( bracketed_paste == x.bracketed_paste ) && ( mouse_reporting_mode == x.mouse_reporting_mode )
&& ( mouse_focus_event == x.mouse_focus_event ) && ( mouse_alternate_scroll == x.mouse_alternate_scroll )
&& ( mouse_encoding_mode == x.mouse_encoding_mode );
}
};
class Framebuffer
{
// To minimize copying of rows and cells, we use shared_ptr to
// share unchanged rows between multiple Framebuffers. If we
// write to a row in a Framebuffer and it is shared with other
// owners, we copy it first. The shared_ptr naturally manages the
// usage of the actual rows themselves.
//
// We gain a couple of free extras by doing this:
//
// * A quick check for equality between rows in different
// Framebuffers is to simply compare the pointer values. If they
// are equal, then the rows are obviously identical.
// * If no row is shared, the frame has not been modified.
public:
typedef std::vector<wchar_t> title_type;
typedef std::shared_ptr<Row> row_pointer;
typedef std::vector<row_pointer> rows_type; /* can be either std::vector or std::deque */
private:
rows_type rows;
title_type icon_name;
title_type window_title;
title_type clipboard;
unsigned int bell_count;
bool title_initialized; /* true if the window title has been set via an OSC */
row_pointer newrow( void )
{
const size_t w = ds.get_width();
const color_type c = ds.get_background_rendition();
return std::make_shared<Row>( w, c );
}
public:
Framebuffer( int s_width, int s_height );
Framebuffer( const Framebuffer& other );
Framebuffer& operator=( const Framebuffer& other );
DrawState ds;
const rows_type& get_rows() const { return rows; }
void scroll( int N );
void move_rows_autoscroll( int rows );
inline const Row* get_row( int row ) const
{
if ( row == -1 )
row = ds.get_cursor_row();
return rows.at( row ).get();
}
inline const Cell* get_cell( int row = -1, int col = -1 ) const
{
if ( row == -1 )
row = ds.get_cursor_row();
if ( col == -1 )
col = ds.get_cursor_col();
return &rows.at( row )->cells.at( col );
}
Row* get_mutable_row( int row )
{
if ( row == -1 )
row = ds.get_cursor_row();
row_pointer& mutable_row = rows.at( row );
// If the row is shared, copy it.
if ( !mutable_row.unique() ) {
mutable_row = std::make_shared<Row>( *mutable_row );
}
return mutable_row.get();
}
Cell* get_mutable_cell( int row = -1, int col = -1 )
{
if ( row == -1 )
row = ds.get_cursor_row();
if ( col == -1 )
col = ds.get_cursor_col();
return &get_mutable_row( row )->cells.at( col );
}
Cell* get_combining_cell( void );
void apply_renditions_to_cell( Cell* cell );
void insert_line( int before_row, int count );
void delete_line( int row, int count );
void insert_cell( int row, int col );
void delete_cell( int row, int col );
void reset( void );
void soft_reset( void );
void set_title_initialized( void ) { title_initialized = true; }
bool is_title_initialized( void ) const { return title_initialized; }
void set_icon_name( const title_type& s ) { icon_name = s; }
void set_window_title( const title_type& s ) { window_title = s; }
void set_clipboard( const title_type& s ) { clipboard = s; }
const title_type& get_icon_name( void ) const { return icon_name; }
const title_type& get_window_title( void ) const { return window_title; }
const title_type& get_clipboard( void ) const { return clipboard; }
void prefix_window_title( const title_type& s );
void resize( int s_width, int s_height );
void reset_cell( Cell* c ) { c->reset( ds.get_background_rendition() ); }
void reset_row( Row* r ) { r->reset( ds.get_background_rendition() ); }
void ring_bell( void ) { bell_count++; }
unsigned int get_bell_count( void ) const { return bell_count; }
bool operator==( const Framebuffer& x ) const
{
return ( rows == x.rows ) && ( window_title == x.window_title ) && ( clipboard == x.clipboard )
&& ( bell_count == x.bell_count ) && ( ds == x.ds );
}
};
}
#endif
| 14,783
|
C++
|
.h
| 395
| 33.617722
| 116
| 0.669628
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,611
|
parsertransition.h
|
mobile-shell_mosh/src/terminal/parsertransition.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef PARSERTRANSITION_HPP
#define PARSERTRANSITION_HPP
#include <cstdlib>
#include "src/terminal/parseraction.h"
namespace Parser {
class State;
class Transition
{
public:
// Transition is only a courier for an Action; it should
// never create/delete one on its own.
ActionPointer action;
State* next_state;
Transition( const Transition& x ) : action( x.action ), next_state( x.next_state ) {}
Transition& operator=( const Transition& t )
{
action = t.action;
next_state = t.next_state;
return *this;
}
Transition( ActionPointer s_action = std::make_shared<Ignore>(), State* s_next_state = NULL )
: action( s_action ), next_state( s_next_state )
{}
// This is only ever used in the 1-argument form;
// we use this instead of an initializer to
// tell Coverity the object never owns *action.
Transition( State* s_next_state, ActionPointer s_action = std::make_shared<Ignore>() )
: action( s_action ), next_state( s_next_state )
{}
};
}
#endif
| 2,474
|
C++
|
.h
| 58
| 38.896552
| 95
| 0.740216
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,612
|
parseraction.h
|
mobile-shell_mosh/src/terminal/parseraction.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef PARSERACTION_HPP
#define PARSERACTION_HPP
#include <memory>
#include <string>
#include <vector>
namespace Terminal {
class Emulator;
}
namespace Parser {
class Action
{
public:
wchar_t ch;
bool char_present;
virtual std::string name( void ) = 0;
virtual void act_on_terminal( Terminal::Emulator* ) const {};
virtual bool ignore() const { return false; }
Action() : ch( -1 ), char_present( false ) {};
virtual ~Action() {};
};
using ActionPointer = std::shared_ptr<Action>;
using Actions = std::vector<ActionPointer>;
class Ignore : public Action
{
public:
std::string name( void ) { return std::string( "Ignore" ); }
bool ignore() const { return true; }
};
class Print : public Action
{
public:
std::string name( void ) { return std::string( "Print" ); }
void act_on_terminal( Terminal::Emulator* emu ) const;
};
class Execute : public Action
{
public:
std::string name( void ) { return std::string( "Execute" ); }
void act_on_terminal( Terminal::Emulator* emu ) const;
};
class Clear : public Action
{
public:
std::string name( void ) { return std::string( "Clear" ); }
void act_on_terminal( Terminal::Emulator* emu ) const;
};
class Collect : public Action
{
public:
std::string name( void ) { return std::string( "Collect" ); }
void act_on_terminal( Terminal::Emulator* emu ) const;
};
class Param : public Action
{
public:
std::string name( void ) { return std::string( "Param" ); }
void act_on_terminal( Terminal::Emulator* emu ) const;
};
class Esc_Dispatch : public Action
{
public:
std::string name( void ) { return std::string( "Esc_Dispatch" ); }
void act_on_terminal( Terminal::Emulator* emu ) const;
};
class CSI_Dispatch : public Action
{
public:
std::string name( void ) { return std::string( "CSI_Dispatch" ); }
void act_on_terminal( Terminal::Emulator* emu ) const;
};
class Hook : public Action
{
public:
std::string name( void ) { return std::string( "Hook" ); }
};
class Put : public Action
{
public:
std::string name( void ) { return std::string( "Put" ); }
};
class Unhook : public Action
{
public:
std::string name( void ) { return std::string( "Unhook" ); }
};
class OSC_Start : public Action
{
public:
std::string name( void ) { return std::string( "OSC_Start" ); }
void act_on_terminal( Terminal::Emulator* emu ) const;
};
class OSC_Put : public Action
{
public:
std::string name( void ) { return std::string( "OSC_Put" ); }
void act_on_terminal( Terminal::Emulator* emu ) const;
};
class OSC_End : public Action
{
public:
std::string name( void ) { return std::string( "OSC_End" ); }
void act_on_terminal( Terminal::Emulator* emu ) const;
};
class UserByte : public Action
{
/* user keystroke -- not part of the host-source state machine*/
public:
char c; /* The user-source byte. We don't try to interpret the charset */
std::string name( void ) { return std::string( "UserByte" ); }
void act_on_terminal( Terminal::Emulator* emu ) const;
UserByte( int s_c ) : c( s_c ) {}
bool operator==( const UserByte& other ) const { return c == other.c; }
};
class Resize : public Action
{
/* resize event -- not part of the host-source state machine*/
public:
size_t width, height;
std::string name( void ) { return std::string( "Resize" ); }
void act_on_terminal( Terminal::Emulator* emu ) const;
Resize( size_t s_width, size_t s_height ) : width( s_width ), height( s_height ) {}
bool operator==( const Resize& other ) const { return ( width == other.width ) && ( height == other.height ); }
};
}
#endif
| 5,007
|
C++
|
.h
| 151
| 30.781457
| 113
| 0.709437
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,613
|
terminaldispatcher.h
|
mobile-shell_mosh/src/terminal/terminaldispatcher.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef TERMINALDISPATCHER_HPP
#define TERMINALDISPATCHER_HPP
#include <map>
#include <string>
#include <vector>
namespace Parser {
class Action;
class Param;
class Collect;
class Clear;
class Esc_Dispatch;
class CSI_Dispatch;
class Execute;
class OSC_Start;
class OSC_Put;
class OSC_End;
}
namespace Terminal {
class Framebuffer;
class Dispatcher;
enum Function_Type
{
ESCAPE,
CSI,
CONTROL
};
class Function
{
public:
Function() : function( NULL ), clears_wrap_state( true ) {}
Function( Function_Type type,
const std::string& dispatch_chars,
void ( *s_function )( Framebuffer*, Dispatcher* ),
bool s_clears_wrap_state = true );
void ( *function )( Framebuffer*, Dispatcher* );
bool clears_wrap_state;
};
using dispatch_map_t = std::map<std::string, Function>;
class DispatchRegistry
{
public:
dispatch_map_t escape;
dispatch_map_t CSI;
dispatch_map_t control;
DispatchRegistry() : escape(), CSI(), control() {}
};
DispatchRegistry& get_global_dispatch_registry( void );
class Dispatcher
{
private:
std::string params;
std::vector<int> parsed_params;
bool parsed;
std::string dispatch_chars;
std::vector<wchar_t> OSC_string; /* only used to set the window title */
void parse_params( void );
public:
static const int PARAM_MAX = 65535;
/* prevent evil escape sequences from causing long loops */
std::string terminal_to_host; /* this is the reply string */
Dispatcher();
int getparam( size_t N, int defaultval );
int param_count( void );
void newparamchar( const Parser::Param* act );
void collect( const Parser::Collect* act );
void clear( const Parser::Clear* act );
std::string str( void );
void dispatch( Function_Type type, const Parser::Action* act, Framebuffer* fb );
std::string get_dispatch_chars( void ) const { return dispatch_chars; }
std::vector<wchar_t> get_OSC_string( void ) const { return OSC_string; }
void OSC_put( const Parser::OSC_Put* act );
void OSC_start( const Parser::OSC_Start* act );
void OSC_dispatch( const Parser::OSC_End* act, Framebuffer* fb );
bool operator==( const Dispatcher& x ) const;
};
}
#endif
| 3,632
|
C++
|
.h
| 103
| 32.058252
| 82
| 0.737579
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,614
|
terminaldisplay.h
|
mobile-shell_mosh/src/terminal/terminaldisplay.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef TERMINALDISPLAY_HPP
#define TERMINALDISPLAY_HPP
#include "src/terminal/terminalframebuffer.h"
namespace Terminal {
/* variables used within a new_frame */
class FrameState
{
public:
std::string str;
int cursor_x, cursor_y;
Renditions current_rendition;
bool cursor_visible;
const Framebuffer& last_frame;
FrameState( const Framebuffer& s_last );
void append( char c ) { str.append( 1, c ); }
void append( size_t s, char c ) { str.append( s, c ); }
void append( wchar_t wc ) { Cell::append_to_str( str, wc ); }
void append( const char* s ) { str.append( s ); }
void append_string( const std::string& append ) { str.append( append ); }
void append_cell( const Cell& cell ) { cell.print_grapheme( str ); }
void append_silent_move( int y, int x );
void append_move( int y, int x );
void update_rendition( const Renditions& r, bool force = false );
};
class Display
{
private:
bool has_ech; /* erase character is part of vt200 but not supported by tmux
(or by "screen" terminfo entry, which is what tmux advertises) */
bool has_bce; /* erases result in cell filled with background color */
bool has_title; /* supports window title and icon name */
const char *smcup, *rmcup; /* enter and exit alternate screen mode */
bool put_row( bool initialized,
FrameState& frame,
const Framebuffer& f,
int frame_y,
const Row& old_row,
bool wrap ) const;
public:
std::string open() const;
std::string close() const;
std::string new_frame( bool initialized, const Framebuffer& last, const Framebuffer& f ) const;
Display( bool use_environment );
};
}
#endif
| 3,181
|
C++
|
.h
| 72
| 39.5
| 97
| 0.71461
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,615
|
parserstate.h
|
mobile-shell_mosh/src/terminal/parserstate.h
|
/*
Mosh: the mobile shell
Copyright 2012 Keith Winstein
This program 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, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
In addition, as a special exception, the copyright holders give
permission to link the code of portions of this program with the
OpenSSL library under certain conditions as described in each
individual source file, and distribute linked combinations including
the two.
You must obey the GNU General Public License in all respects for all
of the code used other than OpenSSL. If you modify file(s) with this
exception, you may extend this exception to your version of the
file(s), but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version. If you delete
this exception statement from all source files in the program, then
also delete it here.
*/
#ifndef PARSERSTATE_HPP
#define PARSERSTATE_HPP
#include "parsertransition.h"
namespace Parser {
class StateFamily;
class State
{
protected:
virtual Transition input_state_rule( wchar_t ch ) const = 0;
StateFamily* family;
private:
Transition anywhere_rule( wchar_t ch ) const;
public:
void setfamily( StateFamily* s_family ) { family = s_family; }
Transition input( wchar_t ch ) const;
virtual ActionPointer enter( void ) const { return std::make_shared<Ignore>(); }
virtual ActionPointer exit( void ) const { return std::make_shared<Ignore>(); }
State() : family( NULL ) {};
virtual ~State() {};
State( const State& );
State& operator=( const State& );
};
class Ground : public State
{
Transition input_state_rule( wchar_t ch ) const;
};
class Escape : public State
{
ActionPointer enter( void ) const;
Transition input_state_rule( wchar_t ch ) const;
};
class Escape_Intermediate : public State
{
Transition input_state_rule( wchar_t ch ) const;
};
class CSI_Entry : public State
{
ActionPointer enter( void ) const;
Transition input_state_rule( wchar_t ch ) const;
};
class CSI_Param : public State
{
Transition input_state_rule( wchar_t ch ) const;
};
class CSI_Intermediate : public State
{
Transition input_state_rule( wchar_t ch ) const;
};
class CSI_Ignore : public State
{
Transition input_state_rule( wchar_t ch ) const;
};
class DCS_Entry : public State
{
ActionPointer enter( void ) const;
Transition input_state_rule( wchar_t ch ) const;
};
class DCS_Param : public State
{
Transition input_state_rule( wchar_t ch ) const;
};
class DCS_Intermediate : public State
{
Transition input_state_rule( wchar_t ch ) const;
};
class DCS_Passthrough : public State
{
ActionPointer enter( void ) const;
Transition input_state_rule( wchar_t ch ) const;
ActionPointer exit( void ) const;
};
class DCS_Ignore : public State
{
Transition input_state_rule( wchar_t ch ) const;
};
class OSC_String : public State
{
ActionPointer enter( void ) const;
Transition input_state_rule( wchar_t ch ) const;
ActionPointer exit( void ) const;
};
class SOS_PM_APC_String : public State
{
Transition input_state_rule( wchar_t ch ) const;
};
}
#endif
| 3,683
|
C++
|
.h
| 113
| 30
| 82
| 0.747042
|
mobile-shell/mosh
| 12,564
| 730
| 193
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,616
|
ProfileFilter.cpp
|
MatsuriDayo_nekoray/db/ProfileFilter.cpp
|
#include "ProfileFilter.hpp"
namespace NekoGui {
QString ProfileFilter_ent_key(const std::shared_ptr<NekoGui::ProxyEntity> &ent, bool by_address) {
by_address &= ent->type != "custom";
return by_address ? (ent->bean->DisplayAddress() + ent->bean->DisplayType())
: QJsonObject2QString(ent->bean->ToJson({"c_cfg", "c_out"}), true) + ent->bean->DisplayType();
}
void ProfileFilter::Uniq(const QList<std::shared_ptr<ProxyEntity>> &in,
QList<std::shared_ptr<ProxyEntity>> &out,
bool by_address, bool keep_last) {
QMap<QString, std::shared_ptr<ProxyEntity>> hashMap;
for (const auto &ent: in) {
QString key = ProfileFilter_ent_key(ent, by_address);
if (hashMap.contains(key)) {
if (keep_last) {
out.removeAll(hashMap[key]);
hashMap[key] = ent;
out += ent;
}
} else {
hashMap[key] = ent;
out += ent;
}
}
}
void ProfileFilter::Common(const QList<std::shared_ptr<ProxyEntity>> &src,
const QList<std::shared_ptr<ProxyEntity>> &dst,
QList<std::shared_ptr<ProxyEntity>> &outSrc,
QList<std::shared_ptr<ProxyEntity>> &outDst,
bool by_address) {
QMap<QString, std::shared_ptr<ProxyEntity>> hashMap;
for (const auto &ent: src) {
QString key = ProfileFilter_ent_key(ent, by_address);
hashMap[key] = ent;
}
for (const auto &ent: dst) {
QString key = ProfileFilter_ent_key(ent, by_address);
if (hashMap.contains(key)) {
outDst += ent;
outSrc += hashMap[key];
}
}
}
void ProfileFilter::OnlyInSrc(const QList<std::shared_ptr<ProxyEntity>> &src,
const QList<std::shared_ptr<ProxyEntity>> &dst,
QList<std::shared_ptr<ProxyEntity>> &out,
bool by_address) {
QMap<QString, bool> hashMap;
for (const auto &ent: dst) {
QString key = ProfileFilter_ent_key(ent, by_address);
hashMap[key] = true;
}
for (const auto &ent: src) {
QString key = ProfileFilter_ent_key(ent, by_address);
if (!hashMap.contains(key)) out += ent;
}
}
void ProfileFilter::OnlyInSrc_ByPointer(const QList<std::shared_ptr<ProxyEntity>> &src,
const QList<std::shared_ptr<ProxyEntity>> &dst,
QList<std::shared_ptr<ProxyEntity>> &out) {
for (const auto &ent: src) {
if (!dst.contains(ent)) out += ent;
}
}
} // namespace NekoGui
| 2,974
|
C++
|
.cpp
| 65
| 30.8
| 120
| 0.506207
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,617
|
Database.cpp
|
MatsuriDayo_nekoray/db/Database.cpp
|
#include "Database.hpp"
#include "fmt/includes.h"
#include <QFile>
#include <QDir>
#include <QColor>
namespace NekoGui {
ProfileManager *profileManager = new ProfileManager();
ProfileManager::ProfileManager() : JsonStore("groups/pm.json") {
_add(new configItem("groups", &groupsTabOrder, itemType::integerList));
}
QList<int> filterIntJsonFile(const QString &path) {
QList<int> result;
QDir dr(path);
auto entryList = dr.entryList(QDir::Files);
for (auto e: entryList) {
e = e.toLower();
if (!e.endsWith(".json", Qt::CaseInsensitive)) continue;
e = e.remove(".json", Qt::CaseInsensitive);
bool ok;
auto id = e.toInt(&ok);
if (ok) {
result << id;
}
}
std::sort(result.begin(), result.end());
return result;
}
void ProfileManager::LoadManager() {
JsonStore::Load();
//
profiles = {};
groups = {};
profilesIdOrder = filterIntJsonFile("profiles");
groupsIdOrder = filterIntJsonFile("groups");
// Load Proxys
QList<int> delProfile;
for (auto id: profilesIdOrder) {
auto ent = LoadProxyEntity(QString("profiles/%1.json").arg(id));
// Corrupted profile?
if (ent == nullptr || ent->bean == nullptr || ent->bean->version == -114514) {
delProfile << id;
continue;
}
profiles[id] = ent;
}
// Clear Corrupted profile
for (auto id: delProfile) {
DeleteProfile(id);
}
// Load Groups
auto loadedOrder = groupsTabOrder;
groupsTabOrder = {};
for (auto id: groupsIdOrder) {
auto ent = LoadGroup(QString("groups/%1.json").arg(id));
// Corrupted group?
if (ent->id != id) {
continue;
}
// Ensure order contains every group
if (!loadedOrder.contains(id)) {
loadedOrder << id;
}
groups[id] = ent;
}
// Ensure groups contains order
for (auto id: loadedOrder) {
if (groups.count(id)) {
groupsTabOrder << id;
}
}
// First setup
if (groups.empty()) {
auto defaultGroup = NekoGui::ProfileManager::NewGroup();
defaultGroup->name = QObject::tr("Default");
NekoGui::profileManager->AddGroup(defaultGroup);
}
//
if (dataStore->flag_reorder) {
{
// remove all (contains orphan)
for (const auto &profile: profiles) {
QFile::remove(profile.second->fn);
}
}
std::map<int, int> gidOld2New;
{
int i = 0;
int ii = 0;
QList<int> newProfilesIdOrder;
std::map<int, std::shared_ptr<ProxyEntity>> newProfiles;
for (auto gid: groupsTabOrder) {
auto group = GetGroup(gid);
gidOld2New[gid] = ii++;
for (auto const &profile: group->ProfilesWithOrder()) {
auto oldId = profile->id;
auto newId = i++;
profile->id = newId;
profile->gid = gidOld2New[gid];
profile->fn = QString("profiles/%1.json").arg(newId);
profile->Save();
newProfiles[newId] = profile;
newProfilesIdOrder << newId;
}
group->order = {};
group->Save();
}
profiles = newProfiles;
profilesIdOrder = newProfilesIdOrder;
}
{
QList<int> newGroupsIdOrder;
std::map<int, std::shared_ptr<Group>> newGroups;
for (auto oldGid: groupsTabOrder) {
auto newId = gidOld2New[oldGid];
auto group = groups[oldGid];
QFile::remove(group->fn);
group->id = newId;
group->fn = QString("groups/%1.json").arg(newId);
group->Save();
newGroups[newId] = group;
newGroupsIdOrder << newId;
}
groups = newGroups;
groupsIdOrder = newGroupsIdOrder;
groupsTabOrder = newGroupsIdOrder;
}
MessageBoxInfo(software_name, "Profiles and groups reorder complete.");
}
}
void ProfileManager::SaveManager() {
JsonStore::Save();
}
std::shared_ptr<ProxyEntity> ProfileManager::LoadProxyEntity(const QString &jsonPath) {
// Load type
ProxyEntity ent0(nullptr, nullptr);
ent0.fn = jsonPath;
auto validJson = ent0.Load();
auto type = ent0.type;
// Load content
std::shared_ptr<ProxyEntity> ent;
bool validType = validJson;
if (validType) {
ent = NewProxyEntity(type);
validType = ent->bean->version != -114514;
}
if (validType) {
ent->load_control_must = true;
ent->fn = jsonPath;
ent->Load();
}
return ent;
}
// 新建的不给 fn 和 id
std::shared_ptr<ProxyEntity> ProfileManager::NewProxyEntity(const QString &type) {
NekoGui_fmt::AbstractBean *bean;
if (type == "socks") {
bean = new NekoGui_fmt::SocksHttpBean(NekoGui_fmt::SocksHttpBean::type_Socks5);
} else if (type == "http") {
bean = new NekoGui_fmt::SocksHttpBean(NekoGui_fmt::SocksHttpBean::type_HTTP);
} else if (type == "shadowsocks") {
bean = new NekoGui_fmt::ShadowSocksBean();
} else if (type == "chain") {
bean = new NekoGui_fmt::ChainBean();
} else if (type == "vmess") {
bean = new NekoGui_fmt::VMessBean();
} else if (type == "trojan") {
bean = new NekoGui_fmt::TrojanVLESSBean(NekoGui_fmt::TrojanVLESSBean::proxy_Trojan);
} else if (type == "vless") {
bean = new NekoGui_fmt::TrojanVLESSBean(NekoGui_fmt::TrojanVLESSBean::proxy_VLESS);
} else if (type == "naive") {
bean = new NekoGui_fmt::NaiveBean();
} else if (type == "hysteria2") {
bean = new NekoGui_fmt::QUICBean(NekoGui_fmt::QUICBean::proxy_Hysteria2);
} else if (type == "tuic") {
bean = new NekoGui_fmt::QUICBean(NekoGui_fmt::QUICBean::proxy_TUIC);
} else if (type == "custom") {
bean = new NekoGui_fmt::CustomBean();
} else {
bean = new NekoGui_fmt::AbstractBean(-114514);
}
auto ent = std::make_shared<ProxyEntity>(bean, type);
return ent;
}
std::shared_ptr<Group> ProfileManager::NewGroup() {
auto ent = std::make_shared<Group>();
return ent;
}
// ProxyEntity
ProxyEntity::ProxyEntity(NekoGui_fmt::AbstractBean *bean, const QString &type_) {
if (type_ != nullptr) this->type = type_;
_add(new configItem("type", &type, itemType::string));
_add(new configItem("id", &id, itemType::integer));
_add(new configItem("gid", &gid, itemType::integer));
_add(new configItem("yc", &latency, itemType::integer));
_add(new configItem("report", &full_test_report, itemType::string));
// 可以不关联 bean,只加载 ProxyEntity 的信息
if (bean != nullptr) {
this->bean = std::shared_ptr<NekoGui_fmt::AbstractBean>(bean);
// 有虚函数就要在这里 dynamic_cast
_add(new configItem("bean", dynamic_cast<JsonStore *>(bean), itemType::jsonStore));
_add(new configItem("traffic", dynamic_cast<JsonStore *>(traffic_data.get()), itemType::jsonStore));
}
};
QString ProxyEntity::DisplayLatency() const {
if (latency < 0) {
return QObject::tr("Unavailable");
} else if (latency > 0) {
return UNICODE_LRO + QString("%1 ms").arg(latency);
} else {
return "";
}
}
QColor ProxyEntity::DisplayLatencyColor() const {
if (latency < 0) {
return Qt::red;
} else if (latency > 0) {
auto greenMs = dataStore->test_latency_url.startsWith("https://") ? 200 : 100;
if (latency < greenMs) {
return Qt::darkGreen;
} else {
return Qt::darkYellow;
}
} else {
return {};
}
}
// Profile
int ProfileManager::NewProfileID() const {
if (profiles.empty()) {
return 0;
} else {
return profilesIdOrder.last() + 1;
}
}
bool ProfileManager::AddProfile(const std::shared_ptr<ProxyEntity> &ent, int gid) {
if (ent->id >= 0) {
return false;
}
ent->gid = gid < 0 ? dataStore->current_group : gid;
ent->id = NewProfileID();
profiles[ent->id] = ent;
profilesIdOrder.push_back(ent->id);
ent->fn = QString("profiles/%1.json").arg(ent->id);
ent->Save();
return true;
}
void ProfileManager::DeleteProfile(int id) {
if (id < 0) return;
if (dataStore->started_id == id) return;
profiles.erase(id);
profilesIdOrder.removeAll(id);
QFile(QString("profiles/%1.json").arg(id)).remove();
}
void ProfileManager::MoveProfile(const std::shared_ptr<ProxyEntity> &ent, int gid) {
if (gid == ent->gid || gid < 0) return;
auto oldGroup = GetGroup(ent->gid);
if (oldGroup != nullptr && !oldGroup->order.isEmpty()) {
oldGroup->order.removeAll(ent->id);
oldGroup->Save();
}
auto newGroup = GetGroup(gid);
if (newGroup != nullptr && !newGroup->order.isEmpty()) {
newGroup->order.push_back(ent->id);
newGroup->Save();
}
ent->gid = gid;
ent->Save();
}
std::shared_ptr<ProxyEntity> ProfileManager::GetProfile(int id) {
return profiles.count(id) ? profiles[id] : nullptr;
}
// Group
Group::Group() {
_add(new configItem("id", &id, itemType::integer));
_add(new configItem("front_proxy_id", &front_proxy_id, itemType::integer));
_add(new configItem("archive", &archive, itemType::boolean));
_add(new configItem("skip_auto_update", &skip_auto_update, itemType::boolean));
_add(new configItem("name", &name, itemType::string));
_add(new configItem("order", &order, itemType::integerList));
_add(new configItem("url", &url, itemType::string));
_add(new configItem("info", &info, itemType::string));
_add(new configItem("lastup", &sub_last_update, itemType::integer64));
_add(new configItem("manually_column_width", &manually_column_width, itemType::boolean));
_add(new configItem("column_width", &column_width, itemType::integerList));
}
std::shared_ptr<Group> ProfileManager::LoadGroup(const QString &jsonPath) {
auto ent = std::make_shared<Group>();
ent->fn = jsonPath;
ent->Load();
return ent;
}
int ProfileManager::NewGroupID() const {
if (groups.empty()) {
return 0;
} else {
return groupsIdOrder.last() + 1;
}
}
bool ProfileManager::AddGroup(const std::shared_ptr<Group> &ent) {
if (ent->id >= 0) {
return false;
}
ent->id = NewGroupID();
groups[ent->id] = ent;
groupsIdOrder.push_back(ent->id);
groupsTabOrder.push_back(ent->id);
ent->fn = QString("groups/%1.json").arg(ent->id);
ent->Save();
return true;
}
void ProfileManager::DeleteGroup(int gid) {
if (groups.size() <= 1) return;
QList<int> toDelete;
for (const auto &[id, profile]: profiles) {
if (profile->gid == gid) toDelete += id; // map访问中,不能操作
}
for (const auto &id: toDelete) {
DeleteProfile(id);
}
groups.erase(gid);
groupsIdOrder.removeAll(gid);
groupsTabOrder.removeAll(gid);
QFile(QString("groups/%1.json").arg(gid)).remove();
}
std::shared_ptr<Group> ProfileManager::GetGroup(int id) {
return groups.count(id) ? groups[id] : nullptr;
}
std::shared_ptr<Group> ProfileManager::CurrentGroup() {
return GetGroup(dataStore->current_group);
}
QList<std::shared_ptr<ProxyEntity>> Group::Profiles() const {
QList<std::shared_ptr<ProxyEntity>> ret;
for (const auto &[_, profile]: profileManager->profiles) {
if (id == profile->gid) ret += profile;
}
return ret;
}
QList<std::shared_ptr<ProxyEntity>> Group::ProfilesWithOrder() const {
if (order.isEmpty()) {
return Profiles();
} else {
QList<std::shared_ptr<ProxyEntity>> ret;
for (auto _id: order) {
auto ent = profileManager->GetProfile(_id);
if (ent != nullptr) ret += ent;
}
return ret;
}
}
} // namespace NekoGui
| 13,515
|
C++
|
.cpp
| 350
| 27.6
| 112
| 0.537082
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,618
|
ConfigBuilder.cpp
|
MatsuriDayo_nekoray/db/ConfigBuilder.cpp
|
#include "db/ConfigBuilder.hpp"
#include "db/Database.hpp"
#include "fmt/includes.h"
#include "fmt/Preset.hpp"
#include <QApplication>
#include <QFile>
#include <QFileInfo>
#define BOX_UNDERLYING_DNS dataStore->core_box_underlying_dns.isEmpty() ? "local" : dataStore->core_box_underlying_dns
namespace NekoGui {
QStringList getAutoBypassExternalProcessPaths(const std::shared_ptr<BuildConfigResult> &result) {
QStringList paths;
for (const auto &extR: result->extRs) {
auto path = extR->program;
if (path.trimmed().isEmpty()) continue;
paths << path.replace("\\", "/");
}
return paths;
}
QString genTunName() {
auto tun_name = "neko-tun";
#ifdef Q_OS_MACOS
tun_name = "utun9";
#endif
return tun_name;
}
void MergeJson(const QJsonObject &custom, QJsonObject &outbound) {
// 合并
if (custom.isEmpty()) return;
for (const auto &key: custom.keys()) {
if (outbound.contains(key)) {
auto v = custom[key];
auto v_orig = outbound[key];
if (v.isObject() && v_orig.isObject()) { // isObject 则合并?
auto vo = v.toObject();
QJsonObject vo_orig = v_orig.toObject();
MergeJson(vo, vo_orig);
outbound[key] = vo_orig;
} else {
outbound[key] = v;
}
} else {
outbound[key] = custom[key];
}
}
}
// Common
std::shared_ptr<BuildConfigResult> BuildConfig(const std::shared_ptr<ProxyEntity> &ent, bool forTest, bool forExport) {
auto result = std::make_shared<BuildConfigResult>();
auto status = std::make_shared<BuildConfigStatus>();
status->ent = ent;
status->result = result;
status->forTest = forTest;
status->forExport = forExport;
auto customBean = dynamic_cast<NekoGui_fmt::CustomBean *>(ent->bean.get());
if (customBean != nullptr && customBean->core == "internal-full") {
result->coreConfig = QString2QJsonObject(customBean->config_simple);
} else {
BuildConfigSingBox(status);
}
// apply custom config
MergeJson(QString2QJsonObject(ent->bean->custom_config), result->coreConfig);
return result;
}
QString BuildChain(int chainId, const std::shared_ptr<BuildConfigStatus> &status) {
auto group = profileManager->GetGroup(status->ent->gid);
if (group == nullptr) {
status->result->error = QString("This profile is not in any group, your data may be corrupted.");
return {};
}
auto resolveChain = [=](const std::shared_ptr<ProxyEntity> &ent) {
QList<std::shared_ptr<ProxyEntity>> resolved;
if (ent->type == "chain") {
auto list = ent->ChainBean()->list;
std::reverse(std::begin(list), std::end(list));
for (auto id: list) {
resolved += profileManager->GetProfile(id);
if (resolved.last() == nullptr) {
status->result->error = QString("chain missing ent: %1").arg(id);
break;
}
if (resolved.last()->type == "chain") {
status->result->error = QString("chain in chain is not allowed: %1").arg(id);
break;
}
}
} else {
resolved += ent;
};
return resolved;
};
// Make list
auto ents = resolveChain(status->ent);
if (!status->result->error.isEmpty()) return {};
if (group->front_proxy_id >= 0) {
auto fEnt = profileManager->GetProfile(group->front_proxy_id);
if (fEnt == nullptr) {
status->result->error = QString("front proxy ent not found.");
return {};
}
ents += resolveChain(fEnt);
if (!status->result->error.isEmpty()) return {};
}
// BuildChain
QString chainTagOut = BuildChainInternal(0, ents, status);
// Chain ent traffic stat
if (ents.length() > 1) {
status->ent->traffic_data->id = status->ent->id;
status->ent->traffic_data->tag = chainTagOut.toStdString();
status->result->outboundStats += status->ent->traffic_data;
}
return chainTagOut;
}
#define DOMAIN_USER_RULE \
for (const auto &line: SplitLinesSkipSharp(dataStore->routing->proxy_domain)) { \
if (dataStore->routing->dns_routing) status->domainListDNSRemote += line; \
status->domainListRemote += line; \
} \
for (const auto &line: SplitLinesSkipSharp(dataStore->routing->direct_domain)) { \
if (dataStore->routing->dns_routing) status->domainListDNSDirect += line; \
status->domainListDirect += line; \
} \
for (const auto &line: SplitLinesSkipSharp(dataStore->routing->block_domain)) { \
status->domainListBlock += line; \
}
#define IP_USER_RULE \
for (const auto &line: SplitLinesSkipSharp(dataStore->routing->block_ip)) { \
status->ipListBlock += line; \
} \
for (const auto &line: SplitLinesSkipSharp(dataStore->routing->proxy_ip)) { \
status->ipListRemote += line; \
} \
for (const auto &line: SplitLinesSkipSharp(dataStore->routing->direct_ip)) { \
status->ipListDirect += line; \
}
QString BuildChainInternal(int chainId, const QList<std::shared_ptr<ProxyEntity>> &ents,
const std::shared_ptr<BuildConfigStatus> &status) {
QString chainTag = "c-" + Int2String(chainId);
QString chainTagOut;
bool muxApplied = false;
QString pastTag;
int pastExternalStat = 0;
int index = 0;
for (const auto &ent: ents) {
// tagOut: v2ray outbound tag for a profile
// profile2 (in) (global) tag g-(id)
// profile1 tag (chainTag)-(id)
// profile0 (out) tag (chainTag)-(id) / single: chainTag=g-(id)
auto tagOut = chainTag + "-" + Int2String(ent->id);
// needGlobal: can only contain one?
bool needGlobal = false;
// first profile set as global
auto isFirstProfile = index == ents.length() - 1;
if (isFirstProfile) {
needGlobal = true;
tagOut = "g-" + Int2String(ent->id);
}
// last profile set as "proxy"
if (chainId == 0 && index == 0) {
needGlobal = false;
tagOut = "proxy";
}
// ignoreConnTag
if (index != 0) {
status->result->ignoreConnTag << tagOut;
}
if (needGlobal) {
if (status->globalProfiles.contains(ent->id)) {
continue;
}
status->globalProfiles += ent->id;
}
if (index > 0) {
// chain rules: past
if (pastExternalStat == 0) {
auto replaced = status->outbounds.last().toObject();
replaced["detour"] = tagOut;
status->outbounds.removeLast();
status->outbounds += replaced;
} else {
status->routingRules += QJsonObject{
{"inbound", QJsonArray{pastTag + "-mapping"}},
{"outbound", tagOut},
};
}
} else {
// index == 0 means last profile in chain / not chain
chainTagOut = tagOut;
status->result->outboundStat = ent->traffic_data;
}
// chain rules: this
auto ext_mapping_port = 0;
auto ext_socks_port = 0;
auto thisExternalStat = ent->bean->NeedExternal(isFirstProfile);
if (thisExternalStat < 0) {
status->result->error = "This configuration cannot be set automatically, please try another.";
return {};
}
// determine port
if (thisExternalStat > 0) {
if (ent->type == "custom") {
auto bean = ent->CustomBean();
if (IsValidPort(bean->mapping_port)) {
ext_mapping_port = bean->mapping_port;
} else {
ext_mapping_port = MkPort();
}
if (IsValidPort(bean->socks_port)) {
ext_socks_port = bean->socks_port;
} else {
ext_socks_port = MkPort();
}
} else {
ext_mapping_port = MkPort();
ext_socks_port = MkPort();
}
}
if (thisExternalStat == 2) dataStore->need_keep_vpn_off = true;
if (thisExternalStat == 1) {
// mapping
status->inbounds += QJsonObject{
{"type", "direct"},
{"tag", tagOut + "-mapping"},
{"listen", "127.0.0.1"},
{"listen_port", ext_mapping_port},
{"override_address", ent->bean->serverAddress},
{"override_port", ent->bean->serverPort},
};
// no chain rule and not outbound, so need to set to direct
if (isFirstProfile) {
status->routingRules += QJsonObject{
{"inbound", QJsonArray{tagOut + "-mapping"}},
{"outbound", "direct"},
};
}
}
// Outbound
QJsonObject outbound;
auto stream = GetStreamSettings(ent->bean.get());
if (thisExternalStat > 0) {
auto extR = ent->bean->BuildExternal(ext_mapping_port, ext_socks_port, thisExternalStat);
if (extR.program.isEmpty()) {
status->result->error = QObject::tr("Core not found: %1").arg(ent->bean->DisplayCoreType());
return {};
}
if (!extR.error.isEmpty()) { // rejected
status->result->error = extR.error;
return {};
}
extR.tag = ent->bean->DisplayType();
status->result->extRs.emplace_back(std::make_shared<NekoGui_fmt::ExternalBuildResult>(extR));
// SOCKS OUTBOUND
outbound["type"] = "socks";
outbound["server"] = "127.0.0.1";
outbound["server_port"] = ext_socks_port;
} else {
const auto coreR = ent->bean->BuildCoreObjSingBox();
if (coreR.outbound.isEmpty()) {
status->result->error = "unsupported outbound";
return {};
}
if (!coreR.error.isEmpty()) { // rejected
status->result->error = coreR.error;
return {};
}
outbound = coreR.outbound;
}
// outbound misc
outbound["tag"] = tagOut;
ent->traffic_data->id = ent->id;
ent->traffic_data->tag = tagOut.toStdString();
status->result->outboundStats += ent->traffic_data;
// mux common
auto needMux = ent->type == "vmess" || ent->type == "trojan" || ent->type == "vless";
needMux &= dataStore->mux_concurrency > 0;
if (stream != nullptr) {
if (stream->network == "grpc" || stream->network == "quic" || (stream->network == "http" && stream->security == "tls")) {
needMux = false;
}
if (stream->multiplex_status == 0) {
if (!dataStore->mux_default_on) needMux = false;
} else if (stream->multiplex_status == 1) {
needMux = true;
} else if (stream->multiplex_status == 2) {
needMux = false;
}
}
if (ent->type == "vless" && outbound["flow"] != "") {
needMux = false;
}
// common
// apply domain_strategy
outbound["domain_strategy"] = dataStore->routing->outbound_domain_strategy;
// apply mux
if (!muxApplied && needMux) {
auto muxObj = QJsonObject{
{"enabled", true},
{"protocol", dataStore->mux_protocol},
{"padding", dataStore->mux_padding},
{"max_streams", dataStore->mux_concurrency},
};
outbound["multiplex"] = muxObj;
muxApplied = true;
}
// apply custom outbound settings
MergeJson(QString2QJsonObject(ent->bean->custom_outbound), outbound);
// Bypass Lookup for the first profile
auto serverAddress = ent->bean->serverAddress;
auto customBean = dynamic_cast<NekoGui_fmt::CustomBean *>(ent->bean.get());
if (customBean != nullptr && customBean->core == "internal") {
auto server = QString2QJsonObject(customBean->config_simple)["server"].toString();
if (!server.isEmpty()) serverAddress = server;
}
if (!IsIpAddress(serverAddress)) {
status->domainListDNSDirect += "full:" + serverAddress;
}
status->outbounds += outbound;
pastTag = tagOut;
pastExternalStat = thisExternalStat;
index++;
}
return chainTagOut;
}
// SingBox
void BuildConfigSingBox(const std::shared_ptr<BuildConfigStatus> &status) {
// Log
status->result->coreConfig["log"] = QJsonObject{{"level", dataStore->log_level}};
// Inbounds
// mixed-in
if (IsValidPort(dataStore->inbound_socks_port) && !status->forTest) {
QJsonObject inboundObj;
inboundObj["tag"] = "mixed-in";
inboundObj["type"] = "mixed";
inboundObj["listen"] = dataStore->inbound_address;
inboundObj["listen_port"] = dataStore->inbound_socks_port;
if (dataStore->routing->sniffing_mode != SniffingMode::DISABLE) {
inboundObj["sniff"] = true;
inboundObj["sniff_override_destination"] = dataStore->routing->sniffing_mode == SniffingMode::FOR_DESTINATION;
}
if (dataStore->inbound_auth->NeedAuth()) {
inboundObj["users"] = QJsonArray{
QJsonObject{
{"username", dataStore->inbound_auth->username},
{"password", dataStore->inbound_auth->password},
},
};
}
inboundObj["domain_strategy"] = dataStore->routing->domain_strategy;
status->inbounds += inboundObj;
}
// tun-in
if (dataStore->vpn_internal_tun && dataStore->spmode_vpn && !status->forTest) {
QJsonObject inboundObj;
inboundObj["tag"] = "tun-in";
inboundObj["type"] = "tun";
inboundObj["interface_name"] = genTunName();
inboundObj["auto_route"] = true;
inboundObj["endpoint_independent_nat"] = true;
inboundObj["mtu"] = dataStore->vpn_mtu;
inboundObj["stack"] = Preset::SingBox::VpnImplementation.value(dataStore->vpn_implementation);
inboundObj["strict_route"] = dataStore->vpn_strict_route;
inboundObj["inet4_address"] = "172.19.0.1/28";
if (dataStore->vpn_ipv6) inboundObj["inet6_address"] = "fdfe:dcba:9876::1/126";
if (dataStore->routing->sniffing_mode != SniffingMode::DISABLE) {
inboundObj["sniff"] = true;
inboundObj["sniff_override_destination"] = dataStore->routing->sniffing_mode == SniffingMode::FOR_DESTINATION;
}
inboundObj["domain_strategy"] = dataStore->routing->domain_strategy;
status->inbounds += inboundObj;
}
// Outbounds
auto tagProxy = BuildChain(0, status);
if (!status->result->error.isEmpty()) return;
// direct & bypass & block
status->outbounds += QJsonObject{
{"type", "direct"},
{"tag", "direct"},
};
status->outbounds += QJsonObject{
{"type", "direct"},
{"tag", "bypass"},
};
status->outbounds += QJsonObject{
{"type", "block"},
{"tag", "block"},
};
if (!status->forTest) {
status->outbounds += QJsonObject{
{"type", "dns"},
{"tag", "dns-out"},
};
}
// custom inbound
if (!status->forTest) QJSONARRAY_ADD(status->inbounds, QString2QJsonObject(dataStore->custom_inbound)["inbounds"].toArray())
status->result->coreConfig.insert("inbounds", status->inbounds);
status->result->coreConfig.insert("outbounds", status->outbounds);
// user rule
if (!status->forTest) {
DOMAIN_USER_RULE
IP_USER_RULE
}
// sing-box common rule object
auto make_rule = [&](const QStringList &list, bool isIP = false) {
QJsonObject rule;
//
QJsonArray ip_cidr;
QJsonArray geoip;
//
QJsonArray domain_keyword;
QJsonArray domain_subdomain;
QJsonArray domain_regexp;
QJsonArray domain_full;
QJsonArray geosite;
for (auto item: list) {
if (isIP) {
if (item.startsWith("geoip:")) {
geoip += item.replace("geoip:", "");
} else {
ip_cidr += item;
}
} else {
// https://www.v2fly.org/config/dns.html#dnsobject
if (item.startsWith("geosite:")) {
geosite += item.replace("geosite:", "");
} else if (item.startsWith("full:")) {
domain_full += item.replace("full:", "").toLower();
} else if (item.startsWith("domain:")) {
domain_subdomain += item.replace("domain:", "").toLower();
} else if (item.startsWith("regexp:")) {
domain_regexp += item.replace("regexp:", "").toLower();
} else if (item.startsWith("keyword:")) {
domain_keyword += item.replace("keyword:", "").toLower();
} else {
domain_full += item.toLower();
}
}
}
if (isIP) {
if (ip_cidr.isEmpty() && geoip.isEmpty()) return rule;
rule["ip_cidr"] = ip_cidr;
rule["geoip"] = geoip;
} else {
if (domain_keyword.isEmpty() && domain_subdomain.isEmpty() && domain_regexp.isEmpty() && domain_full.isEmpty() && geosite.isEmpty()) {
return rule;
}
rule["domain"] = domain_full;
rule["domain_suffix"] = domain_subdomain; // v2ray Subdomain => sing-box suffix
rule["domain_keyword"] = domain_keyword;
rule["domain_regex"] = domain_regexp;
rule["geosite"] = geosite;
}
return rule;
};
// final add DNS
QJsonObject dns;
QJsonArray dnsServers;
QJsonArray dnsRules;
// Remote
if (!status->forTest)
dnsServers += QJsonObject{
{"tag", "dns-remote"},
{"address_resolver", "dns-local"},
{"strategy", dataStore->routing->remote_dns_strategy},
{"address", dataStore->routing->remote_dns},
{"detour", tagProxy},
};
// Direct
QJsonObject directObj{
{"tag", "dns-direct"},
{"address_resolver", "dns-local"},
{"strategy", dataStore->routing->direct_dns_strategy},
{"address", dataStore->routing->direct_dns},
{"detour", "direct"},
};
if (dataStore->routing->dns_final_out == "bypass") {
dnsServers.prepend(directObj);
} else {
dnsServers.append(directObj);
}
dnsRules.append(QJsonObject{
{"outbound", "any"},
{"server", "direct"},
});
// block
if (!status->forTest)
dnsServers += QJsonObject{
{"tag", "dns-block"},
{"address", "rcode://success"},
};
// Fakedns
if (dataStore->fake_dns && dataStore->vpn_internal_tun && dataStore->spmode_vpn && !status->forTest) {
dnsServers += QJsonObject{
{"tag", "dns-fake"},
{"address", "fakeip"},
};
dns["fakeip"] = QJsonObject{
{"enabled", true},
{"inet4_range", "198.18.0.0/15"},
{"inet6_range", "fc00::/18"},
};
}
// Underlying 100% Working DNS ?
dnsServers += QJsonObject{
{"tag", "dns-local"},
{"address", BOX_UNDERLYING_DNS},
{"detour", "direct"},
};
// sing-box dns rule object
auto add_rule_dns = [&](const QStringList &list, const QString &server) {
auto rule = make_rule(list, false);
if (rule.isEmpty()) return;
rule["server"] = server;
dnsRules += rule;
};
add_rule_dns(status->domainListDNSRemote, "dns-remote");
add_rule_dns(status->domainListDNSDirect, "dns-direct");
// built-in rules
if (!status->forTest) {
dnsRules += QJsonObject{
{"query_type", QJsonArray{32, 33}},
{"server", "dns-block"},
};
dnsRules += QJsonObject{
{"domain_suffix", ".lan"},
{"server", "dns-block"},
};
}
// fakedns rule
if (dataStore->fake_dns && dataStore->vpn_internal_tun && dataStore->spmode_vpn && !status->forTest) {
dnsRules += QJsonObject{
{"inbound", "tun-in"},
{"server", "dns-fake"},
};
}
dns["servers"] = dnsServers;
dns["rules"] = dnsRules;
dns["independent_cache"] = true;
if (dataStore->routing->use_dns_object) {
dns = QString2QJsonObject(dataStore->routing->dns_object);
}
status->result->coreConfig.insert("dns", dns);
// Routing
// dns hijack
if (!status->forTest) {
status->routingRules += QJsonObject{
{"protocol", "dns"},
{"outbound", "dns-out"},
};
}
// sing-box routing rule object
auto add_rule_route = [&](const QStringList &list, bool isIP, const QString &out) {
auto rule = make_rule(list, isIP);
if (rule.isEmpty()) return;
rule["outbound"] = out;
status->routingRules += rule;
};
// final add user rule
add_rule_route(status->domainListBlock, false, "block");
add_rule_route(status->domainListRemote, false, tagProxy);
add_rule_route(status->domainListDirect, false, "bypass");
add_rule_route(status->ipListBlock, true, "block");
add_rule_route(status->ipListRemote, true, tagProxy);
add_rule_route(status->ipListDirect, true, "bypass");
// built-in rules
status->routingRules += QJsonObject{
{"network", "udp"},
{"port", QJsonArray{135, 137, 138, 139, 5353}},
{"outbound", "block"},
};
status->routingRules += QJsonObject{
{"ip_cidr", QJsonArray{"224.0.0.0/3", "ff00::/8"}},
{"outbound", "block"},
};
status->routingRules += QJsonObject{
{"source_ip_cidr", QJsonArray{"224.0.0.0/3", "ff00::/8"}},
{"outbound", "block"},
};
// tun user rule
if (dataStore->vpn_internal_tun && dataStore->spmode_vpn && !status->forTest) {
auto match_out = dataStore->vpn_rule_white ? "proxy" : "bypass";
QString process_name_rule = dataStore->vpn_rule_process.trimmed();
if (!process_name_rule.isEmpty()) {
auto arr = SplitLinesSkipSharp(process_name_rule);
QJsonObject rule{{"outbound", match_out},
{"process_name", QList2QJsonArray(arr)}};
status->routingRules += rule;
}
QString cidr_rule = dataStore->vpn_rule_cidr.trimmed();
if (!cidr_rule.isEmpty()) {
auto arr = SplitLinesSkipSharp(cidr_rule);
QJsonObject rule{{"outbound", match_out},
{"ip_cidr", QList2QJsonArray(arr)}};
status->routingRules += rule;
}
auto autoBypassExternalProcessPaths = getAutoBypassExternalProcessPaths(status->result);
if (!autoBypassExternalProcessPaths.isEmpty()) {
QJsonObject rule{{"outbound", "bypass"},
{"process_name", QList2QJsonArray(autoBypassExternalProcessPaths)}};
status->routingRules += rule;
}
}
// geopath
auto geoip = FindCoreAsset("geoip.db");
auto geosite = FindCoreAsset("geosite.db");
if (geoip.isEmpty()) status->result->error = +"geoip.db not found";
if (geosite.isEmpty()) status->result->error = +"geosite.db not found";
// final add routing rule
auto routingRules = QString2QJsonObject(dataStore->routing->custom)["rules"].toArray();
if (status->forTest) routingRules = {};
if (!status->forTest) QJSONARRAY_ADD(routingRules, QString2QJsonObject(dataStore->custom_route_global)["rules"].toArray())
QJSONARRAY_ADD(routingRules, status->routingRules)
auto routeObj = QJsonObject{
{"rules", routingRules},
{"auto_detect_interface", dataStore->spmode_vpn}, // TODO force enable?
{
"geoip",
QJsonObject{
{"path", geoip},
},
},
{
"geosite",
QJsonObject{
{"path", geosite},
},
}};
if (!status->forTest) routeObj["final"] = dataStore->routing->def_outbound;
if (status->forExport) {
routeObj.remove("geoip");
routeObj.remove("geosite");
routeObj.remove("auto_detect_interface");
}
status->result->coreConfig.insert("route", routeObj);
// experimental
QJsonObject experimentalObj;
if (!status->forTest && dataStore->core_box_clash_api > 0) {
QJsonObject clash_api = {
{"external_controller", "127.0.0.1:" + Int2String(dataStore->core_box_clash_api)},
{"secret", dataStore->core_box_clash_api_secret},
{"external_ui", "dashboard"},
};
experimentalObj["clash_api"] = clash_api;
}
if (!experimentalObj.isEmpty()) status->result->coreConfig.insert("experimental", experimentalObj);
}
QString WriteVPNSingBoxConfig() {
// tun user rule
auto match_out = dataStore->vpn_rule_white ? "neko-socks" : "direct";
auto no_match_out = dataStore->vpn_rule_white ? "direct" : "neko-socks";
QString process_name_rule = dataStore->vpn_rule_process.trimmed();
if (!process_name_rule.isEmpty()) {
auto arr = SplitLinesSkipSharp(process_name_rule);
QJsonObject rule{{"outbound", match_out},
{"process_name", QList2QJsonArray(arr)}};
process_name_rule = "," + QJsonObject2QString(rule, false);
}
QString cidr_rule = dataStore->vpn_rule_cidr.trimmed();
if (!cidr_rule.isEmpty()) {
auto arr = SplitLinesSkipSharp(cidr_rule);
QJsonObject rule{{"outbound", match_out},
{"ip_cidr", QList2QJsonArray(arr)}};
cidr_rule = "," + QJsonObject2QString(rule, false);
}
// TODO bypass ext core process path?
// auth
QString socks_user_pass;
if (dataStore->inbound_auth->NeedAuth()) {
socks_user_pass = R"( "username": "%1", "password": "%2", )";
socks_user_pass = socks_user_pass.arg(dataStore->inbound_auth->username, dataStore->inbound_auth->password);
}
// gen config
auto configFn = ":/neko/vpn/sing-box-vpn.json";
if (QFile::exists("vpn/sing-box-vpn.json")) configFn = "vpn/sing-box-vpn.json";
auto config = ReadFileText(configFn)
.replace("//%IPV6_ADDRESS%", dataStore->vpn_ipv6 ? R"("inet6_address": "fdfe:dcba:9876::1/126",)" : "")
.replace("//%SOCKS_USER_PASS%", socks_user_pass)
.replace("//%PROCESS_NAME_RULE%", process_name_rule)
.replace("//%CIDR_RULE%", cidr_rule)
.replace("%MTU%", Int2String(dataStore->vpn_mtu))
.replace("%STACK%", Preset::SingBox::VpnImplementation.value(dataStore->vpn_implementation))
.replace("%TUN_NAME%", genTunName())
.replace("%STRICT_ROUTE%", dataStore->vpn_strict_route ? "true" : "false")
.replace("%FINAL_OUT%", no_match_out)
.replace("%DNS_ADDRESS%", BOX_UNDERLYING_DNS)
.replace("%FAKE_DNS_INBOUND%", dataStore->fake_dns ? "tun-in" : "empty")
.replace("%PORT%", Int2String(dataStore->inbound_socks_port));
// write config
QFile file;
file.setFileName(QFileInfo(configFn).fileName());
file.open(QIODevice::ReadWrite | QIODevice::Truncate);
file.write(config.toUtf8());
file.close();
return QFileInfo(file).absoluteFilePath();
}
QString WriteVPNLinuxScript(const QString &configPath) {
#ifdef Q_OS_WIN
return {};
#endif
// gen script
auto scriptFn = ":/neko/vpn/vpn-run-root.sh";
if (QFile::exists("vpn/vpn-run-root.sh")) scriptFn = "vpn/vpn-run-root.sh";
auto script = ReadFileText(scriptFn)
.replace("./nekobox_core", QApplication::applicationDirPath() + "/nekobox_core")
.replace("$CONFIG_PATH", configPath);
// write script
QFile file2;
file2.setFileName(QFileInfo(scriptFn).fileName());
file2.open(QIODevice::ReadWrite | QIODevice::Truncate);
file2.write(script.toUtf8());
file2.close();
return QFileInfo(file2).absoluteFilePath();
}
} // namespace NekoGui
| 32,376
|
C++
|
.cpp
| 712
| 31.860955
| 150
| 0.503057
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,619
|
TrafficLooper.cpp
|
MatsuriDayo_nekoray/db/traffic/TrafficLooper.cpp
|
#include "TrafficLooper.hpp"
#include "rpc/gRPC.h"
#include "ui/mainwindow_interface.h"
#include <QThread>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#include <QElapsedTimer>
namespace NekoGui_traffic {
TrafficLooper *trafficLooper = new TrafficLooper;
QElapsedTimer elapsedTimer;
TrafficData *TrafficLooper::update_stats(TrafficData *item) {
#ifndef NKR_NO_GRPC
// last update
auto now = elapsedTimer.elapsed();
auto interval = now - item->last_update;
item->last_update = now;
if (interval <= 0) return nullptr;
// query
auto uplink = NekoGui_rpc::defaultClient->QueryStats(item->tag, "uplink");
auto downlink = NekoGui_rpc::defaultClient->QueryStats(item->tag, "downlink");
// add diff
item->downlink += downlink;
item->uplink += uplink;
item->downlink_rate = downlink * 1000 / interval;
item->uplink_rate = uplink * 1000 / interval;
// return diff
auto ret = new TrafficData(item->tag);
ret->downlink = downlink;
ret->uplink = uplink;
ret->downlink_rate = item->downlink_rate;
ret->uplink_rate = item->uplink_rate;
return ret;
#endif
return nullptr;
}
QJsonArray TrafficLooper::get_connection_list() {
#ifndef NKR_NO_GRPC
auto str = NekoGui_rpc::defaultClient->ListConnections();
QJsonDocument jsonDocument = QJsonDocument::fromJson(str.c_str());
return jsonDocument.array();
#else
return QJsonArray{};
#endif
}
void TrafficLooper::UpdateAll() {
std::map<std::string, TrafficData *> updated; // tag to diff
for (const auto &item: this->items) {
auto data = item.get();
auto diff = updated[data->tag];
// 避免重复查询一个 outbound tag
if (diff == nullptr) {
diff = update_stats(data);
updated[data->tag] = diff;
} else {
data->uplink += diff->uplink;
data->downlink += diff->downlink;
data->uplink_rate = diff->uplink_rate;
data->downlink_rate = diff->downlink_rate;
}
}
updated[bypass->tag] = update_stats(bypass);
//
for (const auto &pair: updated) {
delete pair.second;
}
}
void TrafficLooper::Loop() {
elapsedTimer.start();
while (true) {
auto sleep_ms = NekoGui::dataStore->traffic_loop_interval;
if (sleep_ms < 500 || sleep_ms > 5000) sleep_ms = 1000;
QThread::msleep(sleep_ms);
if (NekoGui::dataStore->traffic_loop_interval == 0) continue; // user disabled
// profile start and stop
if (!loop_enabled) {
// 停止
if (looping) {
looping = false;
runOnUiThread([=] {
auto m = GetMainWindow();
m->refresh_status("STOP");
});
}
continue;
} else {
// 开始
if (!looping) {
looping = true;
}
}
// do update
loop_mutex.lock();
UpdateAll();
// do conn list update
QJsonArray conn_list;
if (NekoGui::dataStore->connection_statistics) {
conn_list = get_connection_list();
}
loop_mutex.unlock();
// post to UI
runOnUiThread([=] {
auto m = GetMainWindow();
if (proxy != nullptr) {
m->refresh_status(QObject::tr("Proxy: %1\nDirect: %2").arg(proxy->DisplaySpeed(), bypass->DisplaySpeed()));
}
for (const auto &item: items) {
if (item->id < 0) continue;
m->refresh_proxy_list(item->id);
}
if (NekoGui::dataStore->connection_statistics) {
m->refresh_connection_list(conn_list);
}
});
}
}
} // namespace NekoGui_traffic
| 4,244
|
C++
|
.cpp
| 117
| 24.863248
| 127
| 0.526561
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,621
|
WinCommander.cpp
|
MatsuriDayo_nekoray/3rdparty/WinCommander.cpp
|
/****************************************************************************
**
** Copyright (C) 2014 UpdateNode UG (haftungsbeschr√§nkt)
** Contact: code@updatenode.com
**
** This file is part of the UpdateNode Client.
**
** Commercial License Usage
** Licensees holding valid commercial UpdateNode license may use this file
** under the terms of the the Apache License, Version 2.0
** Full license description file: LICENSE.COM
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation. Please review the following information to ensure the
** GNU General Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
** Full license description file: LICENSE.GPL
**
****************************************************************************/
#include "WinCommander.hpp"
#include <QSysInfo>
#include <QDir>
#ifdef Q_OS_WIN
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <shellapi.h>
#include <sddl.h>
#define MAX_KEY_LENGTH 255
#define MAX_VALUE_NAME 16383
#endif
/*!
Executes a command elevated specified by \apath , using paramters \aparameters.
\n
Parameter /aaWait decides if the function should return immediatelly after it's\n
execution or wait for the exit of the launched process
\n
Returns the return value of the executed command
*/
uint WinCommander::runProcessElevated(const QString &path,
const QStringList ¶meters,
const QString &workingDir,
int nShow, bool aWait) {
uint result = 0;
#ifdef Q_OS_WIN
QString params;
HWND hwnd = NULL;
LPCTSTR pszPath = (LPCTSTR)path.utf16();
foreach(QString item, parameters)
params += "\"" + item + "\" ";
LPCTSTR pszParameters = (LPCTSTR)params.utf16();
QString dir;
if (workingDir.count() == 0)
dir = QDir::toNativeSeparators(QDir::currentPath());
else
dir = QDir::toNativeSeparators(workingDir);
LPCTSTR pszDirectory = (LPCTSTR)dir.utf16();
SHELLEXECUTEINFO shex;
DWORD dwCode = 0;
ZeroMemory(&shex, sizeof(shex));
shex.cbSize = sizeof(shex);
shex.fMask = SEE_MASK_NOCLOSEPROCESS;
shex.hwnd = hwnd;
shex.lpVerb = TEXT("runas");
shex.lpFile = pszPath;
shex.lpParameters = pszParameters;
shex.lpDirectory = pszDirectory;
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-showwindow
shex.nShow = nShow;
ShellExecuteEx(&shex);
if (shex.hProcess)
{
if(aWait)
{
WaitForSingleObject(shex.hProcess, INFINITE );
GetExitCodeProcess(shex.hProcess, &dwCode);
}
CloseHandle (shex.hProcess) ;
}
else
return -1;
result = (uint)dwCode;
#else
Q_UNUSED(path);
Q_UNUSED(parameters);
Q_UNUSED(workingDir);
Q_UNUSED(aWait);
#endif
return result;
}
| 3,112
|
C++
|
.cpp
| 93
| 28.741935
| 87
| 0.643831
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,622
|
base64.cpp
|
MatsuriDayo_nekoray/3rdparty/base64.cpp
|
#include "base64.h"
#ifndef qsizetype
#define qsizetype size_t
#endif
namespace Qt515Base64 {
namespace {
struct fromBase64_helper_result {
qsizetype decodedLength;
Base64DecodingStatus status;
};
fromBase64_helper_result fromBase64_helper(const char *input, qsizetype inputSize,
char *output /* may alias input */,
Base64Options options) {
fromBase64_helper_result result{0, Base64DecodingStatus::Ok};
unsigned int buf = 0;
int nbits = 0;
qsizetype offset = 0;
for (qsizetype i = 0; i < inputSize; ++i) {
int ch = input[i];
int d;
if (ch >= 'A' && ch <= 'Z') {
d = ch - 'A';
} else if (ch >= 'a' && ch <= 'z') {
d = ch - 'a' + 26;
} else if (ch >= '0' && ch <= '9') {
d = ch - '0' + 52;
} else if (ch == '+' && (options & Base64UrlEncoding) == 0) {
d = 62;
} else if (ch == '-' && (options & Base64UrlEncoding) != 0) {
d = 62;
} else if (ch == '/' && (options & Base64UrlEncoding) == 0) {
d = 63;
} else if (ch == '_' && (options & Base64UrlEncoding) != 0) {
d = 63;
} else {
if (options & AbortOnBase64DecodingErrors) {
if (ch == '=') {
// can have 1 or 2 '=' signs, in both cases padding base64Size to
// a multiple of 4. Any other case is illegal.
if ((inputSize % 4) != 0) {
result.status = Base64DecodingStatus::IllegalInputLength;
return result;
} else if ((i == inputSize - 1) ||
(i == inputSize - 2 && input[++i] == '=')) {
d = -1; // ... and exit the loop, normally
} else {
result.status = Base64DecodingStatus::IllegalPadding;
return result;
}
} else {
result.status = Base64DecodingStatus::IllegalCharacter;
return result;
}
} else {
d = -1;
}
}
if (d != -1) {
buf = (buf << 6) | d;
nbits += 6;
if (nbits >= 8) {
nbits -= 8;
Q_ASSERT(offset < i);
output[offset++] = buf >> nbits;
buf &= (1 << nbits) - 1;
}
}
}
result.decodedLength = offset;
return result;
}
} // namespace
FromBase64Result QByteArray_fromBase64Encoding(const QByteArray &base64, Base64Options options) {
const auto base64Size = base64.size();
QByteArray result((base64Size * 3) / 4, Qt::Uninitialized);
const auto base64result = fromBase64_helper(base64.data(),
base64Size,
const_cast<char *>(result.constData()),
options);
result.truncate(int(base64result.decodedLength));
return {std::move(result), base64result.status};
}
} // namespace Qt515Base64
| 3,811
|
C++
|
.cpp
| 83
| 25.903614
| 101
| 0.390696
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,623
|
QtExtKeySequenceEdit.cpp
|
MatsuriDayo_nekoray/3rdparty/QtExtKeySequenceEdit.cpp
|
#include "QtExtKeySequenceEdit.h"
QtExtKeySequenceEdit::QtExtKeySequenceEdit(QWidget *parent)
: QKeySequenceEdit(parent) {
}
QtExtKeySequenceEdit::~QtExtKeySequenceEdit() {
}
void QtExtKeySequenceEdit::keyPressEvent(QKeyEvent *pEvent) {
QKeySequenceEdit::keyPressEvent(pEvent);
QKeySequence keySeq = keySequence();
if (keySeq.count() <= 0) {
return;
}
int key = keySeq[0];
if (key == Qt::Key_Backspace || key == Qt::Key_Delete) {
key = 0;
}
setKeySequence(key);
}
| 524
|
C++
|
.cpp
| 18
| 24.777778
| 61
| 0.689243
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,624
|
QvProxyConfigurator.cpp
|
MatsuriDayo_nekoray/3rdparty/qv2ray/v2/components/proxy/QvProxyConfigurator.cpp
|
#include "QvProxyConfigurator.hpp"
#ifdef Q_OS_WIN
//
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
//
#include <wininet.h>
#include <ras.h>
#include <raserror.h>
#include <vector>
#endif
#include <QStandardPaths>
#include <QProcess>
#include "3rdparty/fix_old_qt.h"
#include "3rdparty/qv2ray/wrapper.hpp"
#include "fmt/Preset.hpp"
#include "main/NekoGui.hpp"
#define QV_MODULE_NAME "SystemProxy"
#define QSTRN(num) QString::number(num)
namespace Qv2ray::components::proxy {
using ProcessArgument = QPair<QString, QStringList>;
#ifdef Q_OS_MACOS
QStringList macOSgetNetworkServices() {
QProcess p;
p.setProgram("/usr/sbin/networksetup");
p.setArguments(QStringList{"-listallnetworkservices"});
p.start();
p.waitForStarted();
p.waitForFinished();
LOG(p.errorString());
auto str = p.readAllStandardOutput();
auto lines = SplitLines(str);
QStringList result;
// Start from 1 since first line is unneeded.
for (auto i = 1; i < lines.count(); i++) {
// * means disabled.
if (!lines[i].contains("*")) {
result << lines[i];
}
}
LOG("Found " + QSTRN(result.size()) + " network services: " + result.join(";"));
return result;
}
#endif
#ifdef Q_OS_WIN
#define NO_CONST(expr) const_cast<wchar_t *>(expr)
// static auto DEFAULT_CONNECTION_NAME =
// NO_CONST(L"DefaultConnectionSettings");
///
/// INTERNAL FUNCTION
bool __QueryProxyOptions() {
INTERNET_PER_CONN_OPTION_LIST List;
INTERNET_PER_CONN_OPTION Option[5];
//
unsigned long nSize = sizeof(INTERNET_PER_CONN_OPTION_LIST);
Option[0].dwOption = INTERNET_PER_CONN_AUTOCONFIG_URL;
Option[1].dwOption = INTERNET_PER_CONN_AUTODISCOVERY_FLAGS;
Option[2].dwOption = INTERNET_PER_CONN_FLAGS;
Option[3].dwOption = INTERNET_PER_CONN_PROXY_BYPASS;
Option[4].dwOption = INTERNET_PER_CONN_PROXY_SERVER;
//
List.dwSize = sizeof(INTERNET_PER_CONN_OPTION_LIST);
List.pszConnection = nullptr; // NO_CONST(DEFAULT_CONNECTION_NAME);
List.dwOptionCount = 5;
List.dwOptionError = 0;
List.pOptions = Option;
if (!InternetQueryOption(nullptr, INTERNET_OPTION_PER_CONNECTION_OPTION, &List, &nSize)) {
LOG("InternetQueryOption failed, GLE=" + QSTRN(GetLastError()));
}
LOG("System default proxy info:");
if (Option[0].Value.pszValue != nullptr) {
LOG(QString::fromWCharArray(Option[0].Value.pszValue));
}
if ((Option[2].Value.dwValue & PROXY_TYPE_AUTO_PROXY_URL) == PROXY_TYPE_AUTO_PROXY_URL) {
LOG("PROXY_TYPE_AUTO_PROXY_URL");
}
if ((Option[2].Value.dwValue & PROXY_TYPE_AUTO_DETECT) == PROXY_TYPE_AUTO_DETECT) {
LOG("PROXY_TYPE_AUTO_DETECT");
}
if ((Option[2].Value.dwValue & PROXY_TYPE_DIRECT) == PROXY_TYPE_DIRECT) {
LOG("PROXY_TYPE_DIRECT");
}
if ((Option[2].Value.dwValue & PROXY_TYPE_PROXY) == PROXY_TYPE_PROXY) {
LOG("PROXY_TYPE_PROXY");
}
if (!InternetQueryOption(nullptr, INTERNET_OPTION_PER_CONNECTION_OPTION, &List, &nSize)) {
LOG("InternetQueryOption failed,GLE=" + QSTRN(GetLastError()));
}
if (Option[4].Value.pszValue != nullptr) {
LOG(QString::fromStdWString(Option[4].Value.pszValue));
}
INTERNET_VERSION_INFO Version;
nSize = sizeof(INTERNET_VERSION_INFO);
InternetQueryOption(nullptr, INTERNET_OPTION_VERSION, &Version, &nSize);
if (Option[0].Value.pszValue != nullptr) {
GlobalFree(Option[0].Value.pszValue);
}
if (Option[3].Value.pszValue != nullptr) {
GlobalFree(Option[3].Value.pszValue);
}
if (Option[4].Value.pszValue != nullptr) {
GlobalFree(Option[4].Value.pszValue);
}
return false;
}
bool __SetProxyOptions(LPWSTR proxy_full_addr, bool isPAC) {
INTERNET_PER_CONN_OPTION_LIST list;
DWORD dwBufSize = sizeof(list);
// Fill the list structure.
list.dwSize = sizeof(list);
// NULL == LAN, otherwise connectoid name.
list.pszConnection = nullptr;
if (nullptr == proxy_full_addr) {
LOG("Clearing system proxy");
//
list.dwOptionCount = 1;
list.pOptions = new INTERNET_PER_CONN_OPTION[1];
// Ensure that the memory was allocated.
if (nullptr == list.pOptions) {
// Return if the memory wasn't allocated.
return false;
}
// Set flags.
list.pOptions[0].dwOption = INTERNET_PER_CONN_FLAGS;
list.pOptions[0].Value.dwValue = PROXY_TYPE_DIRECT;
} else if (isPAC) {
LOG("Setting system proxy for PAC");
//
list.dwOptionCount = 2;
list.pOptions = new INTERNET_PER_CONN_OPTION[2];
if (nullptr == list.pOptions) {
return false;
}
// Set flags.
list.pOptions[0].dwOption = INTERNET_PER_CONN_FLAGS;
list.pOptions[0].Value.dwValue = PROXY_TYPE_DIRECT | PROXY_TYPE_AUTO_PROXY_URL;
// Set proxy name.
list.pOptions[1].dwOption = INTERNET_PER_CONN_AUTOCONFIG_URL;
list.pOptions[1].Value.pszValue = proxy_full_addr;
} else {
LOG("Setting system proxy for Global Proxy");
//
list.dwOptionCount = 2;
list.pOptions = new INTERNET_PER_CONN_OPTION[2];
if (nullptr == list.pOptions) {
return false;
}
// Set flags.
list.pOptions[0].dwOption = INTERNET_PER_CONN_FLAGS;
list.pOptions[0].Value.dwValue = PROXY_TYPE_DIRECT | PROXY_TYPE_PROXY;
// Set proxy name.
list.pOptions[1].dwOption = INTERNET_PER_CONN_PROXY_SERVER;
list.pOptions[1].Value.pszValue = proxy_full_addr;
// Set proxy override.
// list.pOptions[2].dwOption = INTERNET_PER_CONN_PROXY_BYPASS;
// auto localhost = L"localhost";
// list.pOptions[2].Value.pszValue = NO_CONST(localhost);
}
// Set proxy for LAN.
if (!InternetSetOption(nullptr, INTERNET_OPTION_PER_CONNECTION_OPTION, &list, dwBufSize)) {
LOG("InternetSetOption failed for LAN, GLE=" + QSTRN(GetLastError()));
}
RASENTRYNAME entry;
entry.dwSize = sizeof(entry);
std::vector<RASENTRYNAME> entries;
DWORD size = sizeof(entry), count;
LPRASENTRYNAME entryAddr = &entry;
auto ret = RasEnumEntries(nullptr, nullptr, entryAddr, &size, &count);
if (ERROR_BUFFER_TOO_SMALL == ret) {
entries.resize(count);
entries[0].dwSize = sizeof(RASENTRYNAME);
entryAddr = entries.data();
ret = RasEnumEntries(nullptr, nullptr, entryAddr, &size, &count);
}
if (ERROR_SUCCESS != ret) {
LOG("Failed to list entry names");
return false;
}
// Set proxy for each connectoid.
for (DWORD i = 0; i < count; ++i) {
list.pszConnection = entryAddr[i].szEntryName;
if (!InternetSetOption(nullptr, INTERNET_OPTION_PER_CONNECTION_OPTION, &list, dwBufSize)) {
LOG("InternetSetOption failed for connectoid " + QString::fromWCharArray(list.pszConnection) + ", GLE=" + QSTRN(GetLastError()));
}
}
delete[] list.pOptions;
InternetSetOption(nullptr, INTERNET_OPTION_SETTINGS_CHANGED, nullptr, 0);
InternetSetOption(nullptr, INTERNET_OPTION_REFRESH, nullptr, 0);
return true;
}
#endif
void SetSystemProxy(int httpPort, int socksPort) {
const QString &address = "127.0.0.1";
bool hasHTTP = (httpPort > 0 && httpPort < 65536);
bool hasSOCKS = (socksPort > 0 && socksPort < 65536);
#ifdef Q_OS_WIN
if (!hasHTTP) {
LOG("Nothing?");
return;
} else {
LOG("Qv2ray will set system proxy to use HTTP");
}
#else
if (!hasHTTP && !hasSOCKS) {
LOG("Nothing?");
return;
}
if (hasHTTP) {
LOG("Qv2ray will set system proxy to use HTTP");
}
if (hasSOCKS) {
LOG("Qv2ray will set system proxy to use SOCKS");
}
#endif
#ifdef Q_OS_WIN
QString str = NekoGui::dataStore->system_proxy_format;
if (str.isEmpty()) str = Preset::Windows::system_proxy_format[0];
str = str.replace("{ip}", address)
.replace("{http_port}", Int2String(httpPort))
.replace("{socks_port}", Int2String(socksPort));
//
LOG("Windows proxy string: " + str);
auto proxyStrW = new WCHAR[str.length() + 1];
wcscpy(proxyStrW, str.toStdWString().c_str());
//
__QueryProxyOptions();
if (!__SetProxyOptions(proxyStrW, false)) {
LOG("Failed to set proxy.");
}
__QueryProxyOptions();
#elif defined(Q_OS_LINUX)
QList<ProcessArgument> actions;
actions << ProcessArgument{"gsettings", {"set", "org.gnome.system.proxy", "mode", "manual"}};
//
bool isKDE = qEnvironmentVariable("XDG_SESSION_DESKTOP") == "KDE" ||
qEnvironmentVariable("XDG_SESSION_DESKTOP") == "plasma";
const auto configPath = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation);
//
// Configure HTTP Proxies for HTTP, FTP and HTTPS
if (hasHTTP) {
// iterate over protocols...
for (const auto &protocol: QStringList{"http", "ftp", "https"}) {
// for GNOME:
{
actions << ProcessArgument{"gsettings",
{"set", "org.gnome.system.proxy." + protocol, "host", address}};
actions << ProcessArgument{"gsettings",
{"set", "org.gnome.system.proxy." + protocol, "port", QSTRN(httpPort)}};
}
// for KDE:
if (isKDE) {
actions << ProcessArgument{"kwriteconfig5",
{"--file", configPath + "/kioslaverc", //
"--group", "Proxy Settings", //
"--key", protocol + "Proxy", //
"http://" + address + " " + QSTRN(httpPort)}};
}
}
}
// Configure SOCKS5 Proxies
if (hasSOCKS) {
// for GNOME:
{
actions << ProcessArgument{"gsettings", {"set", "org.gnome.system.proxy.socks", "host", address}};
actions << ProcessArgument{"gsettings",
{"set", "org.gnome.system.proxy.socks", "port", QSTRN(socksPort)}};
// for KDE:
if (isKDE) {
actions << ProcessArgument{"kwriteconfig5",
{"--file", configPath + "/kioslaverc", //
"--group", "Proxy Settings", //
"--key", "socksProxy", //
"socks://" + address + " " + QSTRN(socksPort)}};
}
}
}
// Setting Proxy Mode to Manual
{
// for GNOME:
{
actions << ProcessArgument{"gsettings", {"set", "org.gnome.system.proxy", "mode", "manual"}};
}
// for KDE:
if (isKDE) {
actions << ProcessArgument{"kwriteconfig5",
{"--file", configPath + "/kioslaverc", //
"--group", "Proxy Settings", //
"--key", "ProxyType", "1"}};
}
}
// Notify kioslaves to reload system proxy configuration.
if (isKDE) {
actions << ProcessArgument{"dbus-send",
{"--type=signal", "/KIO/Scheduler", //
"org.kde.KIO.Scheduler.reparseSlaveConfiguration", //
"string:''"}};
}
// Execute them all!
//
// note: do not use std::all_of / any_of / none_of,
// because those are short-circuit and cannot guarantee atomicity.
QList<bool> results;
for (const auto &action: actions) {
// execute and get the code
const auto returnCode = QProcess::execute(action.first, action.second);
// print out the commands and result codes
DEBUG(QString("[%1] Program: %2, Args: %3").arg(returnCode).arg(action.first).arg(action.second.join(";")));
// give the code back
results << (returnCode == QProcess::NormalExit);
}
if (results.count(true) != actions.size()) {
LOG("Something wrong when setting proxies.");
}
#else
for (const auto &service: macOSgetNetworkServices()) {
LOG("Setting proxy for interface: " + service);
if (hasHTTP) {
QProcess::execute("/usr/sbin/networksetup", {"-setwebproxystate", service, "on"});
QProcess::execute("/usr/sbin/networksetup", {"-setsecurewebproxystate", service, "on"});
QProcess::execute("/usr/sbin/networksetup", {"-setwebproxy", service, address, QSTRN(httpPort)});
QProcess::execute("/usr/sbin/networksetup", {"-setsecurewebproxy", service, address, QSTRN(httpPort)});
}
if (hasSOCKS) {
QProcess::execute("/usr/sbin/networksetup", {"-setsocksfirewallproxystate", service, "on"});
QProcess::execute("/usr/sbin/networksetup", {"-setsocksfirewallproxy", service, address, QSTRN(socksPort)});
}
}
#endif
}
void ClearSystemProxy() {
LOG("Clearing System Proxy");
#ifdef Q_OS_WIN
if (!__SetProxyOptions(nullptr, false)) {
LOG("Failed to clear proxy.");
}
#elif defined(Q_OS_LINUX)
QList<ProcessArgument> actions;
const bool isKDE = qEnvironmentVariable("XDG_SESSION_DESKTOP") == "KDE" ||
qEnvironmentVariable("XDG_SESSION_DESKTOP") == "plasma";
const auto configRoot = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation);
// Setting System Proxy Mode to: None
{
// for GNOME:
{
actions << ProcessArgument{"gsettings", {"set", "org.gnome.system.proxy", "mode", "none"}};
}
// for KDE:
if (isKDE) {
actions << ProcessArgument{"kwriteconfig5",
{"--file", configRoot + "/kioslaverc", //
"--group", "Proxy Settings", //
"--key", "ProxyType", "0"}};
}
}
// Notify kioslaves to reload system proxy configuration.
if (isKDE) {
actions << ProcessArgument{"dbus-send",
{"--type=signal", "/KIO/Scheduler", //
"org.kde.KIO.Scheduler.reparseSlaveConfiguration", //
"string:''"}};
}
// Execute the Actions
for (const auto &action: actions) {
// execute and get the code
const auto returnCode = QProcess::execute(action.first, action.second);
// print out the commands and result codes
DEBUG(QString("[%1] Program: %2, Args: %3").arg(returnCode).arg(action.first).arg(action.second.join(";")));
}
#else
for (const auto &service: macOSgetNetworkServices()) {
LOG("Clearing proxy for interface: " + service);
QProcess::execute("/usr/sbin/networksetup", {"-setautoproxystate", service, "off"});
QProcess::execute("/usr/sbin/networksetup", {"-setwebproxystate", service, "off"});
QProcess::execute("/usr/sbin/networksetup", {"-setsecurewebproxystate", service, "off"});
QProcess::execute("/usr/sbin/networksetup", {"-setsocksfirewallproxystate", service, "off"});
}
#endif
}
} // namespace Qv2ray::components::proxy
| 16,973
|
C++
|
.cpp
| 381
| 32.173228
| 145
| 0.539648
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,625
|
QvAutoCompleteTextEdit.cpp
|
MatsuriDayo_nekoray/3rdparty/qv2ray/v2/ui/QvAutoCompleteTextEdit.cpp
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "QvAutoCompleteTextEdit.hpp"
#include <QAbstractItemModel>
#include <QAbstractItemView>
#include <QApplication>
#include <QCompleter>
#include <QKeyEvent>
#include <QModelIndex>
#include <QScrollBar>
#include <QStringListModel>
#include <QToolTip>
#include <QtDebug>
namespace Qv2ray::ui::widgets {
AutoCompleteTextEdit::AutoCompleteTextEdit(const QString &prefix, const QStringList &sourceStrings, QWidget *parent) : QPlainTextEdit(parent) {
this->prefix = prefix;
this->setLineWrapMode(QPlainTextEdit::NoWrap);
c = new QCompleter(this);
c->setModel(new QStringListModel(sourceStrings, c));
c->setWidget(this);
c->setCompletionMode(QCompleter::PopupCompletion);
c->setCaseSensitivity(Qt::CaseInsensitive);
QObject::connect(c, static_cast<void (QCompleter::*)(const QString &)>(&QCompleter::activated), this, &AutoCompleteTextEdit::insertCompletion);
}
AutoCompleteTextEdit::~AutoCompleteTextEdit() {
}
void AutoCompleteTextEdit::insertCompletion(const QString &completion) {
QTextCursor tc = textCursor();
int extra = completion.length() - c->completionPrefix().length();
tc.movePosition(QTextCursor::Left);
tc.movePosition(QTextCursor::EndOfWord);
tc.insertText(completion.right(extra).toLower());
setTextCursor(tc);
}
QString AutoCompleteTextEdit::lineUnderCursor() const {
QTextCursor tc = textCursor();
tc.select(QTextCursor::LineUnderCursor);
return tc.selectedText();
}
QString AutoCompleteTextEdit::wordUnderCursor() const {
QTextCursor tc = textCursor();
tc.select(QTextCursor::WordUnderCursor);
return tc.selectedText();
}
void AutoCompleteTextEdit::focusInEvent(QFocusEvent *e) {
if (c)
c->setWidget(this);
QPlainTextEdit::focusInEvent(e);
}
void AutoCompleteTextEdit::keyPressEvent(QKeyEvent *e) {
const bool hasCtrlOrShiftModifier = e->modifiers().testFlag(Qt::ControlModifier) || e->modifiers().testFlag(Qt::ShiftModifier);
const bool hasOtherModifiers = (e->modifiers() != Qt::NoModifier) && !hasCtrlOrShiftModifier; // has other modifiers
//
const bool isSpace = (e->modifiers().testFlag(Qt::ShiftModifier) || e->modifiers().testFlag(Qt::NoModifier)) //
&& e->key() == Qt::Key_Space;
const bool isTab = (e->modifiers().testFlag(Qt::NoModifier) && e->key() == Qt::Key_Tab);
const bool isOtherSpace = e->text() == " ";
//
if (isSpace || isTab || isOtherSpace) {
QToolTip::showText(this->mapToGlobal(QPoint(0, 0)), tr("You can not input space characters here."), this, QRect{}, 2000);
return;
}
//
if (c && c->popup()->isVisible()) {
// The following keys are forwarded by the completer to the widget
switch (e->key()) {
case Qt::Key_Enter:
case Qt::Key_Return:
case Qt::Key_Escape:
case Qt::Key_Tab:
case Qt::Key_Backtab:
e->ignore();
return; // let the completer do default behavior
default:
break;
}
}
QPlainTextEdit::keyPressEvent(e);
if (!c || (hasCtrlOrShiftModifier && e->text().isEmpty()))
return;
// if we have other modifiers, or the text is empty, or the line does not start with our prefix.
if (hasOtherModifiers || e->text().isEmpty() || !lineUnderCursor().startsWith(prefix)) {
c->popup()->hide();
return;
}
if (auto word = wordUnderCursor(); word != c->completionPrefix()) {
c->setCompletionPrefix(word);
c->popup()->setCurrentIndex(c->completionModel()->index(0, 0));
}
QRect cr = cursorRect();
cr.setWidth(c->popup()->sizeHintForColumn(0) + c->popup()->verticalScrollBar()->sizeHint().width());
c->complete(cr); // popup it up!
}
} // namespace Qv2ray::ui::widgets
| 6,601
|
C++
|
.cpp
| 141
| 40.560284
| 151
| 0.658752
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,626
|
w_JsonEditor.cpp
|
MatsuriDayo_nekoray/3rdparty/qv2ray/v2/ui/widgets/editors/w_JsonEditor.cpp
|
#include "w_JsonEditor.hpp"
#include "main/NekoGui.hpp"
JsonEditor::JsonEditor(const QJsonObject& rootObject, QWidget* parent) : QDialog(parent) {
setupUi(this);
// QvMessageBusConnect(JsonEditor);
//
original = rootObject;
final = rootObject;
QString jsonString = JsonToString(rootObject);
if (VerifyJsonString(jsonString).isEmpty()) {
jsonTree->setModel(&model);
model.loadJson(QJsonDocument(rootObject).toJson());
} else {
QvMessageBoxWarn(this, tr("Json Contains Syntax Errors"),
tr("Original Json may contain syntax errors. Json tree is disabled."));
}
jsonEditor->setText(JsonToString(rootObject));
jsonTree->expandAll();
jsonTree->resizeColumnToContents(0);
}
// QvMessageBusSlotImpl(JsonEditor)
// {
// switch (msg)
// {
// MBShowDefaultImpl;
// MBHideDefaultImpl;
// MBRetranslateDefaultImpl;
// case UPDATE_COLORSCHEME:
// break;
// }
// }
QJsonObject JsonEditor::OpenEditor() {
int resultCode = this->exec();
auto string = jsonEditor->toPlainText();
while (resultCode == QDialog::Accepted && !VerifyJsonString(string).isEmpty()) {
if (string.isEmpty()) {
resultCode = QDialog::Accepted;
final = {};
break;
}
QvMessageBoxWarn(this, tr("Json Contains Syntax Errors"),
tr("You must correct these errors before continuing."));
resultCode = this->exec();
string = jsonEditor->toPlainText();
}
return resultCode == QDialog::Accepted ? final : original;
}
JsonEditor::~JsonEditor() {
}
void JsonEditor::on_jsonEditor_textChanged() {
auto string = jsonEditor->toPlainText();
auto VerifyResult = VerifyJsonString(string);
jsonValidateStatus->setText(VerifyResult);
if (VerifyResult.isEmpty()) {
BLACK(jsonEditor);
final = JsonFromString(string);
model.loadJson(QJsonDocument(final).toJson());
jsonTree->expandAll();
jsonTree->resizeColumnToContents(0);
} else {
RED(jsonEditor);
}
}
void JsonEditor::on_formatJsonBtn_clicked() {
auto string = jsonEditor->toPlainText();
auto VerifyResult = VerifyJsonString(string);
jsonValidateStatus->setText(VerifyResult);
if (VerifyResult.isEmpty()) {
BLACK(jsonEditor);
jsonEditor->setPlainText(JsonToString(JsonFromString(string)));
model.loadJson(QJsonDocument(JsonFromString(string)).toJson());
jsonTree->setModel(&model);
jsonTree->expandAll();
jsonTree->resizeColumnToContents(0);
} else {
RED(jsonEditor);
QvMessageBoxWarn(this, tr("Syntax Errors"),
tr("Please fix the JSON errors or remove the comments before continue"));
}
}
void JsonEditor::on_removeCommentsBtn_clicked() {
jsonEditor->setPlainText(JsonToString(JsonFromString(jsonEditor->toPlainText())));
}
| 3,101
|
C++
|
.cpp
| 83
| 31.289157
| 98
| 0.633822
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
|
10,627
|
GeositeReader.cpp
|
MatsuriDayo_nekoray/3rdparty/qv2ray/v3/components/GeositeReader/GeositeReader.cpp
|
#include "GeositeReader.hpp"
#include "3rdparty/qv2ray/wrapper.hpp"
#include "picoproto.hpp"
#include <QFile>
#include <QMap>
namespace Qv2ray::components::GeositeReader {
QMap<QString, QStringList> GeositeEntries;
QStringList ReadGeoSiteFromFile(const QString &filepath, bool allowCache) {
if (GeositeEntries.contains(filepath) && allowCache)
return GeositeEntries.value(filepath);
QStringList list;
qInfo() << "Reading geosites from:" << filepath;
QFile f(filepath);
bool opened = f.open(QFile::OpenModeFlag::ReadOnly);
if (!opened) {
qInfo() << "File cannot be opened:" << filepath;
return list;
}
const auto content = f.readAll();
f.close();
{
picoproto::Message root;
root.ParseFromBytes((unsigned char *) content.data(), content.size());
list.reserve(root.GetMessageArray(1).size());
for (const auto &geosite: root.GetMessageArray(1))
list << QString::fromStdString(geosite->GetString(1));
}
qInfo() << "Loaded" << list.count() << "geosite entries from data file.";
list.sort();
GeositeEntries[filepath] = list;
return list;
}
} // namespace Qv2ray::components::GeositeReader
| 1,323
|
C++
|
.cpp
| 33
| 31.787879
| 82
| 0.627635
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,629
|
GroupUpdater.cpp
|
MatsuriDayo_nekoray/sub/GroupUpdater.cpp
|
#include "db/ProfileFilter.hpp"
#include "fmt/includes.h"
#include "fmt/Preset.hpp"
#include "main/HTTPRequestHelper.hpp"
#include "GroupUpdater.hpp"
#include <QInputDialog>
#include <QUrlQuery>
#ifndef NKR_NO_YAML
#include <yaml-cpp/yaml.h>
#endif
namespace NekoGui_sub {
GroupUpdater *groupUpdater = new GroupUpdater;
void RawUpdater_FixEnt(const std::shared_ptr<NekoGui::ProxyEntity> &ent) {
if (ent == nullptr) return;
auto stream = NekoGui_fmt::GetStreamSettings(ent->bean.get());
if (stream == nullptr) return;
// 1. "security"
if (stream->security == "none" || stream->security == "0" || stream->security == "false") {
stream->security = "";
} else if (stream->security == "1" || stream->security == "true") {
stream->security = "tls";
}
// 2. TLS SNI: v2rayN config builder generate sni like this, so set sni here for their format.
if (stream->security == "tls" && IsIpAddress(ent->bean->serverAddress) && (!stream->host.isEmpty()) && stream->sni.isEmpty()) {
stream->sni = stream->host;
}
}
void RawUpdater::update(const QString &str) {
// Base64 encoded subscription
if (auto str2 = DecodeB64IfValid(str); !str2.isEmpty()) {
update(str2);
return;
}
// Clash
if (str.contains("proxies:")) {
updateClash(str);
return;
}
// Multi line
if (str.count("\n") > 0) {
auto list = str.split("\n");
for (const auto &str2: list) {
update(str2.trimmed());
}
return;
}
std::shared_ptr<NekoGui::ProxyEntity> ent;
bool needFix = true;
// Nekoray format
if (str.startsWith("nekoray://")) {
needFix = false;
auto link = QUrl(str);
if (!link.isValid()) return;
ent = NekoGui::ProfileManager::NewProxyEntity(link.host());
if (ent->bean->version == -114514) return;
auto j = DecodeB64IfValid(link.fragment().toUtf8(), QByteArray::Base64UrlEncoding);
if (j.isEmpty()) return;
ent->bean->FromJsonBytes(j);
}
// SOCKS
if (str.startsWith("socks5://") || str.startsWith("socks4://") ||
str.startsWith("socks4a://") || str.startsWith("socks://")) {
ent = NekoGui::ProfileManager::NewProxyEntity("socks");
auto ok = ent->SocksHTTPBean()->TryParseLink(str);
if (!ok) return;
}
// HTTP
if (str.startsWith("http://") || str.startsWith("https://")) {
ent = NekoGui::ProfileManager::NewProxyEntity("http");
auto ok = ent->SocksHTTPBean()->TryParseLink(str);
if (!ok) return;
}
// ShadowSocks
if (str.startsWith("ss://")) {
ent = NekoGui::ProfileManager::NewProxyEntity("shadowsocks");
auto ok = ent->ShadowSocksBean()->TryParseLink(str);
if (!ok) return;
}
// VMess
if (str.startsWith("vmess://")) {
ent = NekoGui::ProfileManager::NewProxyEntity("vmess");
auto ok = ent->VMessBean()->TryParseLink(str);
if (!ok) return;
}
// VLESS
if (str.startsWith("vless://")) {
ent = NekoGui::ProfileManager::NewProxyEntity("vless");
auto ok = ent->TrojanVLESSBean()->TryParseLink(str);
if (!ok) return;
}
// Trojan
if (str.startsWith("trojan://")) {
ent = NekoGui::ProfileManager::NewProxyEntity("trojan");
auto ok = ent->TrojanVLESSBean()->TryParseLink(str);
if (!ok) return;
}
// Naive
if (str.startsWith("naive+")) {
needFix = false;
ent = NekoGui::ProfileManager::NewProxyEntity("naive");
auto ok = ent->NaiveBean()->TryParseLink(str);
if (!ok) return;
}
// Hysteria2
if (str.startsWith("hysteria2://") || str.startsWith("hy2://")) {
needFix = false;
ent = NekoGui::ProfileManager::NewProxyEntity("hysteria2");
auto ok = ent->QUICBean()->TryParseLink(str);
if (!ok) return;
}
// TUIC
if (str.startsWith("tuic://")) {
needFix = false;
ent = NekoGui::ProfileManager::NewProxyEntity("tuic");
auto ok = ent->QUICBean()->TryParseLink(str);
if (!ok) return;
}
if (ent == nullptr) return;
// Fix
if (needFix) RawUpdater_FixEnt(ent);
// End
NekoGui::profileManager->AddProfile(ent, gid_add_to);
updated_order += ent;
}
#ifndef NKR_NO_YAML
QString Node2QString(const YAML::Node &n, const QString &def = "") {
try {
return n.as<std::string>().c_str();
} catch (const YAML::Exception &ex) {
qDebug() << ex.what();
return def;
}
}
QStringList Node2QStringList(const YAML::Node &n) {
try {
if (n.IsSequence()) {
QStringList list;
for (auto item: n) {
list << item.as<std::string>().c_str();
}
return list;
} else {
return {};
}
} catch (const YAML::Exception &ex) {
qDebug() << ex.what();
return {};
}
}
int Node2Int(const YAML::Node &n, const int &def = 0) {
try {
return n.as<int>();
} catch (const YAML::Exception &ex) {
qDebug() << ex.what();
return def;
}
}
bool Node2Bool(const YAML::Node &n, const bool &def = false) {
try {
return n.as<bool>();
} catch (const YAML::Exception &ex) {
try {
return n.as<int>();
} catch (const YAML::Exception &ex2) {
qDebug() << ex2.what();
}
qDebug() << ex.what();
return def;
}
}
// NodeChild returns the first defined children or Null Node
YAML::Node NodeChild(const YAML::Node &n, const std::list<std::string> &keys) {
for (const auto &key: keys) {
auto child = n[key];
if (child.IsDefined()) return child;
}
return {};
}
#endif
// https://github.com/Dreamacro/clash/wiki/configuration
void RawUpdater::updateClash(const QString &str) {
#ifndef NKR_NO_YAML
try {
auto proxies = YAML::Load(str.toStdString())["proxies"];
for (auto proxy: proxies) {
auto type = Node2QString(proxy["type"]).toLower();
auto type_clash = type;
if (type == "ss" || type == "ssr") type = "shadowsocks";
if (type == "socks5") type = "socks";
auto ent = NekoGui::ProfileManager::NewProxyEntity(type);
if (ent->bean->version == -114514) continue;
bool needFix = false;
// common
ent->bean->name = Node2QString(proxy["name"]);
ent->bean->serverAddress = Node2QString(proxy["server"]);
ent->bean->serverPort = Node2Int(proxy["port"]);
if (type_clash == "ss") {
auto bean = ent->ShadowSocksBean();
bean->method = Node2QString(proxy["cipher"]).replace("dummy", "none");
bean->password = Node2QString(proxy["password"]);
auto plugin_n = proxy["plugin"];
auto pluginOpts_n = proxy["plugin-opts"];
// UDP over TCP
if (Node2Bool(proxy["udp-over-tcp"])) {
bean->uot = Node2Int(proxy["udp-over-tcp-version"]);
if (bean->uot == 0) bean->uot = 2;
}
if (plugin_n.IsDefined() && pluginOpts_n.IsDefined()) {
QStringList ssPlugin;
auto plugin = Node2QString(plugin_n);
if (plugin == "obfs") {
ssPlugin << "obfs-local";
ssPlugin << "obfs=" + Node2QString(pluginOpts_n["mode"]);
ssPlugin << "obfs-host=" + Node2QString(pluginOpts_n["host"]);
} else if (plugin == "v2ray-plugin") {
auto mode = Node2QString(pluginOpts_n["mode"]);
auto host = Node2QString(pluginOpts_n["host"]);
auto path = Node2QString(pluginOpts_n["path"]);
ssPlugin << "v2ray-plugin";
if (!mode.isEmpty() && mode != "websocket") ssPlugin << "mode=" + mode;
if (Node2Bool(pluginOpts_n["tls"])) ssPlugin << "tls";
if (!host.isEmpty()) ssPlugin << "host=" + host;
if (!path.isEmpty()) ssPlugin << "path=" + path;
// clash only: skip-cert-verify
// clash only: headers
// clash: mux=?
}
bean->plugin = ssPlugin.join(";");
}
// sing-mux
auto smux = NodeChild(proxy, {"smux"});
if (Node2Bool(smux["enabled"])) bean->stream->multiplex_status = 1;
} else if (type == "socks" || type == "http") {
auto bean = ent->SocksHTTPBean();
bean->username = Node2QString(proxy["username"]);
bean->password = Node2QString(proxy["password"]);
if (Node2Bool(proxy["tls"])) bean->stream->security = "tls";
if (Node2Bool(proxy["skip-cert-verify"])) bean->stream->allow_insecure = true;
} else if (type == "trojan" || type == "vless") {
needFix = true;
auto bean = ent->TrojanVLESSBean();
if (type == "vless") {
bean->flow = Node2QString(proxy["flow"]);
bean->password = Node2QString(proxy["uuid"]);
// meta packet encoding
if (Node2Bool(proxy["packet-addr"])) {
bean->stream->packet_encoding = "packetaddr";
} else {
// For VLESS, default to use xudp
bean->stream->packet_encoding = "xudp";
}
} else {
bean->password = Node2QString(proxy["password"]);
}
bean->stream->security = "tls";
bean->stream->network = Node2QString(proxy["network"], "tcp");
bean->stream->sni = FIRST_OR_SECOND(Node2QString(proxy["sni"]), Node2QString(proxy["servername"]));
bean->stream->alpn = Node2QStringList(proxy["alpn"]).join(",");
bean->stream->allow_insecure = Node2Bool(proxy["skip-cert-verify"]);
bean->stream->utlsFingerprint = Node2QString(proxy["client-fingerprint"]);
if (bean->stream->utlsFingerprint.isEmpty()) {
bean->stream->utlsFingerprint = NekoGui::dataStore->utlsFingerprint;
}
// sing-mux
auto smux = NodeChild(proxy, {"smux"});
if (Node2Bool(smux["enabled"])) bean->stream->multiplex_status = 1;
// opts
auto ws = NodeChild(proxy, {"ws-opts", "ws-opt"});
if (ws.IsMap()) {
auto headers = ws["headers"];
for (auto header: headers) {
if (Node2QString(header.first).toLower() == "host") {
bean->stream->host = Node2QString(header.second);
}
}
bean->stream->path = Node2QString(ws["path"]);
bean->stream->ws_early_data_length = Node2Int(ws["max-early-data"]);
bean->stream->ws_early_data_name = Node2QString(ws["early-data-header-name"]);
}
auto grpc = NodeChild(proxy, {"grpc-opts", "grpc-opt"});
if (grpc.IsMap()) {
bean->stream->path = Node2QString(grpc["grpc-service-name"]);
}
auto reality = NodeChild(proxy, {"reality-opts"});
if (reality.IsMap()) {
bean->stream->reality_pbk = Node2QString(reality["public-key"]);
bean->stream->reality_sid = Node2QString(reality["short-id"]);
}
} else if (type == "vmess") {
needFix = true;
auto bean = ent->VMessBean();
bean->uuid = Node2QString(proxy["uuid"]);
bean->aid = Node2Int(proxy["alterId"]);
bean->security = Node2QString(proxy["cipher"], bean->security);
bean->stream->network = Node2QString(proxy["network"], "tcp").replace("h2", "http");
bean->stream->sni = FIRST_OR_SECOND(Node2QString(proxy["sni"]), Node2QString(proxy["servername"]));
bean->stream->alpn = Node2QStringList(proxy["alpn"]).join(",");
if (Node2Bool(proxy["tls"])) bean->stream->security = "tls";
if (Node2Bool(proxy["skip-cert-verify"])) bean->stream->allow_insecure = true;
bean->stream->utlsFingerprint = Node2QString(proxy["client-fingerprint"]);
bean->stream->utlsFingerprint = Node2QString(proxy["client-fingerprint"]);
if (bean->stream->utlsFingerprint.isEmpty()) {
bean->stream->utlsFingerprint = NekoGui::dataStore->utlsFingerprint;
}
// sing-mux
auto smux = NodeChild(proxy, {"smux"});
if (Node2Bool(smux["enabled"])) bean->stream->multiplex_status = 1;
// meta packet encoding
if (Node2Bool(proxy["xudp"])) bean->stream->packet_encoding = "xudp";
if (Node2Bool(proxy["packet-addr"])) bean->stream->packet_encoding = "packetaddr";
// opts
auto ws = NodeChild(proxy, {"ws-opts", "ws-opt"});
if (ws.IsMap()) {
auto headers = ws["headers"];
for (auto header: headers) {
if (Node2QString(header.first).toLower() == "host") {
bean->stream->host = Node2QString(header.second);
}
}
bean->stream->path = Node2QString(ws["path"]);
bean->stream->ws_early_data_length = Node2Int(ws["max-early-data"]);
bean->stream->ws_early_data_name = Node2QString(ws["early-data-header-name"]);
// for Xray
if (Node2QString(ws["early-data-header-name"]) == "Sec-WebSocket-Protocol") {
bean->stream->path += "?ed=" + Node2QString(ws["max-early-data"]);
}
}
auto grpc = NodeChild(proxy, {"grpc-opts", "grpc-opt"});
if (grpc.IsMap()) {
bean->stream->path = Node2QString(grpc["grpc-service-name"]);
}
auto h2 = NodeChild(proxy, {"h2-opts", "h2-opt"});
if (h2.IsMap()) {
auto hosts = h2["host"];
for (auto host: hosts) {
bean->stream->host = Node2QString(host);
break;
}
bean->stream->path = Node2QString(h2["path"]);
}
auto tcp_http = NodeChild(proxy, {"http-opts", "http-opt"});
if (tcp_http.IsMap()) {
bean->stream->network = "tcp";
bean->stream->header_type = "http";
auto headers = tcp_http["headers"];
for (auto header: headers) {
if (Node2QString(header.first).toLower() == "host") {
bean->stream->host = Node2QString(header.second[0]);
}
break;
}
auto paths = tcp_http["path"];
for (auto path: paths) {
bean->stream->path = Node2QString(path);
break;
}
}
} else if (type == "hysteria2") {
auto bean = ent->QUICBean();
bean->hopPort = Node2QString(proxy["ports"]);
bean->allowInsecure = Node2Bool(proxy["skip-cert-verify"]);
bean->caText = Node2QString(proxy["ca-str"]);
bean->sni = Node2QString(proxy["sni"]);
bean->obfsPassword = Node2QString(proxy["obfs-password"]);
bean->password = Node2QString(proxy["password"]);
bean->uploadMbps = Node2QString(proxy["up"]).split(" ")[0].toInt();
bean->downloadMbps = Node2QString(proxy["down"]).split(" ")[0].toInt();
} else if (type == "tuic") {
auto bean = ent->QUICBean();
bean->uuid = Node2QString(proxy["uuid"]);
bean->password = Node2QString(proxy["password"]);
if (Node2Int(proxy["heartbeat-interval"]) != 0) {
bean->heartbeat = Int2String(Node2Int(proxy["heartbeat-interval"])) + "ms";
}
bean->udpRelayMode = Node2QString(proxy["udp-relay-mode"], bean->udpRelayMode);
bean->congestionControl = Node2QString(proxy["congestion-controller"], bean->congestionControl);
bean->disableSni = Node2Bool(proxy["disable-sni"]);
bean->zeroRttHandshake = Node2Bool(proxy["reduce-rtt"]);
bean->allowInsecure = Node2Bool(proxy["skip-cert-verify"]);
bean->alpn = Node2QStringList(proxy["alpn"]).join(",");
bean->caText = Node2QString(proxy["ca-str"]);
bean->sni = Node2QString(proxy["sni"]);
if (Node2Bool(proxy["udp-over-stream"])) bean->uos = true;
if (!Node2QString(proxy["ip"]).isEmpty()) {
if (bean->sni.isEmpty()) bean->sni = bean->serverAddress;
bean->serverAddress = Node2QString(proxy["ip"]);
}
} else {
continue;
}
if (needFix) RawUpdater_FixEnt(ent);
NekoGui::profileManager->AddProfile(ent, gid_add_to);
updated_order += ent;
}
} catch (const YAML::Exception &ex) {
runOnUiThread([=] {
MessageBoxWarning("YAML Exception", ex.what());
});
}
#endif
}
// 在新的 thread 运行
void GroupUpdater::AsyncUpdate(const QString &str, int _sub_gid, const std::function<void()> &finish) {
auto content = str.trimmed();
bool asURL = false;
bool createNewGroup = false;
if (_sub_gid < 0 && (content.startsWith("http://") || content.startsWith("https://"))) {
auto items = QStringList{
QObject::tr("As Subscription (add to this group)"),
QObject::tr("As Subscription (create new group)"),
QObject::tr("As link"),
};
bool ok;
auto a = QInputDialog::getItem(nullptr,
QObject::tr("url detected"),
QObject::tr("%1\nHow to update?").arg(content),
items, 0, false, &ok);
if (!ok) return;
if (items.indexOf(a) <= 1) asURL = true;
if (items.indexOf(a) == 1) createNewGroup = true;
}
runOnNewThread([=] {
auto gid = _sub_gid;
if (createNewGroup) {
auto group = NekoGui::ProfileManager::NewGroup();
group->name = QUrl(str).host();
group->url = str;
NekoGui::profileManager->AddGroup(group);
gid = group->id;
MW_dialog_message("SubUpdater", "NewGroup");
}
Update(str, gid, asURL);
emit asyncUpdateCallback(gid);
if (finish != nullptr) finish();
});
}
void GroupUpdater::Update(const QString &_str, int _sub_gid, bool _not_sub_as_url) {
// 创建 rawUpdater
NekoGui::dataStore->imported_count = 0;
auto rawUpdater = std::make_unique<RawUpdater>();
rawUpdater->gid_add_to = _sub_gid;
// 准备
QString sub_user_info;
bool asURL = _sub_gid >= 0 || _not_sub_as_url; // 把 _str 当作 url 处理(下载内容)
auto content = _str.trimmed();
auto group = NekoGui::profileManager->GetGroup(_sub_gid);
if (group != nullptr && group->archive) return;
// 网络请求
if (asURL) {
auto groupName = group == nullptr ? content : group->name;
MW_show_log(">>>>>>>> " + QObject::tr("Requesting subscription: %1").arg(groupName));
auto resp = NetworkRequestHelper::HttpGet(content);
if (!resp.error.isEmpty()) {
MW_show_log("<<<<<<<< " + QObject::tr("Requesting subscription %1 error: %2").arg(groupName, resp.error + "\n" + resp.data));
return;
}
content = resp.data;
sub_user_info = NetworkRequestHelper::GetHeader(resp.header, "Subscription-UserInfo");
MW_show_log("<<<<<<<< " + QObject::tr("Subscription request fininshed: %1").arg(groupName));
}
QList<std::shared_ptr<NekoGui::ProxyEntity>> in; // 更新前
QList<std::shared_ptr<NekoGui::ProxyEntity>> out_all; // 更新前 + 更新后
QList<std::shared_ptr<NekoGui::ProxyEntity>> out; // 更新后
QList<std::shared_ptr<NekoGui::ProxyEntity>> only_in; // 只在更新前有的
QList<std::shared_ptr<NekoGui::ProxyEntity>> only_out; // 只在更新后有的
QList<std::shared_ptr<NekoGui::ProxyEntity>> update_del; // 更新前后都有的,需要删除的新配置
QList<std::shared_ptr<NekoGui::ProxyEntity>> update_keep; // 更新前后都有的,被保留的旧配置
// 订阅解析前
if (group != nullptr) {
in = group->Profiles();
group->sub_last_update = QDateTime::currentMSecsSinceEpoch() / 1000;
group->info = sub_user_info;
group->order.clear();
group->Save();
//
if (NekoGui::dataStore->sub_clear) {
MW_show_log(QObject::tr("Clearing servers..."));
for (const auto &profile: in) {
NekoGui::profileManager->DeleteProfile(profile->id);
}
}
}
// 解析并添加 profile
rawUpdater->update(content);
if (group != nullptr) {
out_all = group->Profiles();
QString change_text;
if (NekoGui::dataStore->sub_clear) {
// all is new profile
for (const auto &ent: out_all) {
change_text += "[+] " + ent->bean->DisplayTypeAndName() + "\n";
}
} else {
// find and delete not updated profile by ProfileFilter
NekoGui::ProfileFilter::OnlyInSrc_ByPointer(out_all, in, out);
NekoGui::ProfileFilter::OnlyInSrc(in, out, only_in);
NekoGui::ProfileFilter::OnlyInSrc(out, in, only_out);
NekoGui::ProfileFilter::Common(in, out, update_keep, update_del, false);
QString notice_added;
QString notice_deleted;
for (const auto &ent: only_out) {
notice_added += "[+] " + ent->bean->DisplayTypeAndName() + "\n";
}
for (const auto &ent: only_in) {
notice_deleted += "[-] " + ent->bean->DisplayTypeAndName() + "\n";
}
// sort according to order in remote
group->order = {};
for (const auto &ent: rawUpdater->updated_order) {
auto deleted_index = update_del.indexOf(ent);
if (deleted_index > 0) {
if (deleted_index >= update_keep.count()) continue; // should not happen
auto ent2 = update_keep[deleted_index];
group->order.append(ent2->id);
} else {
group->order.append(ent->id);
}
}
group->Save();
// cleanup
for (const auto &ent: out_all) {
if (!group->order.contains(ent->id)) {
NekoGui::profileManager->DeleteProfile(ent->id);
}
}
change_text = "\n" + QObject::tr("Added %1 profiles:\n%2\nDeleted %3 Profiles:\n%4")
.arg(only_out.length())
.arg(notice_added)
.arg(only_in.length())
.arg(notice_deleted);
if (only_out.length() + only_in.length() == 0) change_text = QObject::tr("Nothing");
}
MW_show_log("<<<<<<<< " + QObject::tr("Change of %1:").arg(group->name) + "\n" + change_text);
MW_dialog_message("SubUpdater", "finish-dingyue");
} else {
NekoGui::dataStore->imported_count = rawUpdater->updated_order.count();
MW_dialog_message("SubUpdater", "finish");
}
}
} // namespace NekoGui_sub
bool UI_update_all_groups_Updating = false;
#define should_skip_group(g) (g == nullptr || g->url.isEmpty() || g->archive || (onlyAllowed && g->skip_auto_update))
void serialUpdateSubscription(const QList<int> &groupsTabOrder, int _order, bool onlyAllowed) {
if (_order >= groupsTabOrder.size()) {
UI_update_all_groups_Updating = false;
return;
}
// calculate this group
auto group = NekoGui::profileManager->GetGroup(groupsTabOrder[_order]);
if (group == nullptr || should_skip_group(group)) {
serialUpdateSubscription(groupsTabOrder, _order + 1, onlyAllowed);
return;
}
int nextOrder = _order + 1;
while (nextOrder < groupsTabOrder.size()) {
auto nextGid = groupsTabOrder[nextOrder];
auto nextGroup = NekoGui::profileManager->GetGroup(nextGid);
if (!should_skip_group(nextGroup)) {
break;
}
nextOrder += 1;
}
// Async update current group
UI_update_all_groups_Updating = true;
NekoGui_sub::groupUpdater->AsyncUpdate(group->url, group->id, [=] {
serialUpdateSubscription(groupsTabOrder, nextOrder, onlyAllowed);
});
}
void UI_update_all_groups(bool onlyAllowed) {
if (UI_update_all_groups_Updating) {
MW_show_log("The last subscription update has not exited.");
return;
}
auto groupsTabOrder = NekoGui::profileManager->groupsTabOrder;
serialUpdateSubscription(groupsTabOrder, 0, onlyAllowed);
}
| 28,287
|
C++
|
.cpp
| 576
| 33.012153
| 141
| 0.489869
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,630
|
Icon.cpp
|
MatsuriDayo_nekoray/ui/Icon.cpp
|
#include "Icon.hpp"
#include "main/NekoGui.hpp"
#include <QPainter>
QPixmap Icon::GetTrayIcon(Icon::TrayIconStatus status) {
QPixmap pixmap;
// software embedded icon
auto pixmap_read = QPixmap(":/neko/" + software_name.toLower() + ".png");
if (!pixmap_read.isNull()) pixmap = pixmap_read;
// software pack icon
pixmap_read = QPixmap("../" + software_name.toLower() + ".png");
if (!pixmap_read.isNull()) pixmap = pixmap_read;
// user icon
pixmap_read = QPixmap("./" + software_name.toLower() + ".png");
if (!pixmap_read.isNull()) pixmap = pixmap_read;
if (status == TrayIconStatus::NONE) return pixmap;
auto p = QPainter(&pixmap);
auto side = pixmap.width();
auto radius = side * 0.4;
auto d = side * 0.3;
auto margin = side * 0.05;
if (status == TrayIconStatus::RUNNING) {
p.setBrush(QBrush(Qt::darkGreen));
} else if (status == TrayIconStatus::SYSTEM_PROXY) {
p.setBrush(QBrush(Qt::blue));
} else if (status == TrayIconStatus::VPN) {
p.setBrush(QBrush(Qt::red));
}
p.drawRoundedRect(
QRect(side - d - margin,
side - d - margin,
d,
d),
radius,
radius);
p.end();
return pixmap;
}
QPixmap Icon::GetMaterialIcon(const QString &name) {
QPixmap pixmap(":/icon/material/" + name + ".svg");
return pixmap;
}
| 1,404
|
C++
|
.cpp
| 41
| 28.317073
| 77
| 0.607698
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,631
|
dialog_vpn_settings.cpp
|
MatsuriDayo_nekoray/ui/dialog_vpn_settings.cpp
|
#include "dialog_vpn_settings.h"
#include "ui_dialog_vpn_settings.h"
#include "main/GuiUtils.hpp"
#include "main/NekoGui.hpp"
#include "ui/mainwindow_interface.h"
#include <QMessageBox>
DialogVPNSettings::DialogVPNSettings(QWidget *parent) : QDialog(parent), ui(new Ui::DialogVPNSettings) {
ui->setupUi(this);
ADD_ASTERISK(this);
ui->fake_dns->setChecked(NekoGui::dataStore->fake_dns);
ui->vpn_implementation->setCurrentIndex(NekoGui::dataStore->vpn_implementation);
ui->vpn_mtu->setCurrentText(Int2String(NekoGui::dataStore->vpn_mtu));
ui->vpn_ipv6->setChecked(NekoGui::dataStore->vpn_ipv6);
ui->hide_console->setChecked(NekoGui::dataStore->vpn_hide_console);
#ifndef Q_OS_WIN
ui->hide_console->setVisible(false);
#endif
ui->strict_route->setChecked(NekoGui::dataStore->vpn_strict_route);
ui->single_core->setChecked(NekoGui::dataStore->vpn_internal_tun);
//
D_LOAD_STRING_PLAIN(vpn_rule_cidr)
D_LOAD_STRING_PLAIN(vpn_rule_process)
//
connect(ui->whitelist_mode, &QCheckBox::stateChanged, this, [=](int state) {
if (state == Qt::Checked) {
ui->gb_cidr->setTitle(tr("Proxy CIDR"));
ui->gb_process_name->setTitle(tr("Proxy Process Name"));
} else {
ui->gb_cidr->setTitle(tr("Bypass CIDR"));
ui->gb_process_name->setTitle(tr("Bypass Process Name"));
}
});
ui->whitelist_mode->setChecked(NekoGui::dataStore->vpn_rule_white);
}
DialogVPNSettings::~DialogVPNSettings() {
delete ui;
}
void DialogVPNSettings::accept() {
//
auto mtu = ui->vpn_mtu->currentText().toInt();
if (mtu > 10000 || mtu < 1000) mtu = 9000;
NekoGui::dataStore->vpn_implementation = ui->vpn_implementation->currentIndex();
NekoGui::dataStore->fake_dns = ui->fake_dns->isChecked();
NekoGui::dataStore->vpn_mtu = mtu;
NekoGui::dataStore->vpn_ipv6 = ui->vpn_ipv6->isChecked();
NekoGui::dataStore->vpn_hide_console = ui->hide_console->isChecked();
NekoGui::dataStore->vpn_strict_route = ui->strict_route->isChecked();
NekoGui::dataStore->vpn_rule_white = ui->whitelist_mode->isChecked();
bool isInternalChanged = NekoGui::dataStore->vpn_internal_tun != ui->single_core->isChecked();
NekoGui::dataStore->vpn_internal_tun = ui->single_core->isChecked();
//
D_SAVE_STRING_PLAIN(vpn_rule_cidr)
D_SAVE_STRING_PLAIN(vpn_rule_process)
//
QStringList msg{"UpdateDataStore"};
if (isInternalChanged) {
msg << "NeedRestart";
} else {
msg << "VPNChanged";
}
MW_dialog_message("", msg.join(","));
QDialog::accept();
}
void DialogVPNSettings::on_troubleshooting_clicked() {
auto r = QMessageBox::information(this, tr("Troubleshooting"),
tr("If you have trouble starting VPN, you can force reset nekobox_core process here.\n\n"
"If still not working, see documentation for more information.\n"
"https://matsuridayo.github.io/n-configuration/#vpn-tun"),
tr("Reset"), tr("Cancel"), "",
1, 1);
if (r == 0) {
GetMainWindow()->StopVPNProcess(true);
}
}
| 3,265
|
C++
|
.cpp
| 74
| 36.756757
| 127
| 0.640704
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,632
|
dialog_manage_groups.cpp
|
MatsuriDayo_nekoray/ui/dialog_manage_groups.cpp
|
#include "dialog_manage_groups.h"
#include "ui_dialog_manage_groups.h"
#include "db/Database.hpp"
#include "sub/GroupUpdater.hpp"
#include "main/GuiUtils.hpp"
#include "ui/widget/GroupItem.h"
#include "ui/edit/dialog_edit_group.h"
#include <QInputDialog>
#include <QListWidgetItem>
#include <QMessageBox>
#define AddGroupToListIfExist(_id) \
auto __ent = NekoGui::profileManager->GetGroup(_id); \
if (__ent != nullptr) { \
auto wI = new QListWidgetItem(); \
auto w = new GroupItem(this, __ent, wI); \
wI->setData(114514, _id); \
ui->listWidget->addItem(wI); \
ui->listWidget->setItemWidget(wI, w); \
}
DialogManageGroups::DialogManageGroups(QWidget *parent) : QDialog(parent), ui(new Ui::DialogManageGroups) {
ui->setupUi(this);
for (auto id: NekoGui::profileManager->groupsTabOrder) {
AddGroupToListIfExist(id)
}
connect(ui->listWidget, &QListWidget::itemDoubleClicked, this, [=](QListWidgetItem *wI) {
auto w = dynamic_cast<GroupItem *>(ui->listWidget->itemWidget(wI));
emit w->edit_clicked();
});
}
DialogManageGroups::~DialogManageGroups() {
delete ui;
}
void DialogManageGroups::on_add_clicked() {
auto ent = NekoGui::ProfileManager::NewGroup();
auto dialog = new DialogEditGroup(ent, this);
int ret = dialog->exec();
dialog->deleteLater();
if (ret == QDialog::Accepted) {
NekoGui::profileManager->AddGroup(ent);
AddGroupToListIfExist(ent->id);
MW_dialog_message(Dialog_DialogManageGroups, "refresh-1");
}
}
void DialogManageGroups::on_update_all_clicked() {
if (QMessageBox::question(this, tr("Confirmation"), tr("Update all subscriptions?")) == QMessageBox::StandardButton::Yes) {
UI_update_all_groups();
}
}
| 1,919
|
C++
|
.cpp
| 48
| 35.354167
| 127
| 0.636217
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,633
|
dialog_manage_routes.cpp
|
MatsuriDayo_nekoray/ui/dialog_manage_routes.cpp
|
#include "dialog_manage_routes.h"
#include "ui_dialog_manage_routes.h"
#include "3rdparty/qv2ray/v2/ui/widgets/editors/w_JsonEditor.hpp"
#include "3rdparty/qv2ray/v3/components/GeositeReader/GeositeReader.hpp"
#include "main/GuiUtils.hpp"
#include "fmt/Preset.hpp"
#include <QFile>
#include <QMessageBox>
#include <QListWidget>
#include <QLineEdit>
#define REFRESH_ACTIVE_ROUTING(name, obj) \
this->active_routing = name; \
setWindowTitle(title_base + " [" + name + "]"); \
UpdateDisplayRouting(obj, false);
DialogManageRoutes::DialogManageRoutes(QWidget *parent) : QDialog(parent), ui(new Ui::DialogManageRoutes) {
ui->setupUi(this);
title_base = windowTitle();
QStringList qsValue = {""};
QString dnsHelpDocumentUrl;
//
ui->outbound_domain_strategy->addItems(Preset::SingBox::DomainStrategy);
ui->domainStrategyCombo->addItems(Preset::SingBox::DomainStrategy);
qsValue += QString("prefer_ipv4 prefer_ipv6 ipv4_only ipv6_only").split(" ");
ui->dns_object->setPlaceholderText(DecodeB64IfValid("ewogICJzZXJ2ZXJzIjogW10sCiAgInJ1bGVzIjogW10sCiAgImZpbmFsIjogIiIsCiAgInN0cmF0ZWd5IjogIiIsCiAgImRpc2FibGVfY2FjaGUiOiBmYWxzZSwKICAiZGlzYWJsZV9leHBpcmUiOiBmYWxzZSwKICAiaW5kZXBlbmRlbnRfY2FjaGUiOiBmYWxzZSwKICAicmV2ZXJzZV9tYXBwaW5nIjogZmFsc2UsCiAgImZha2VpcCI6IHt9Cn0="));
dnsHelpDocumentUrl = "https://sing-box.sagernet.org/configuration/dns/";
//
ui->direct_dns_strategy->addItems(qsValue);
ui->remote_dns_strategy->addItems(qsValue);
//
D_C_LOAD_STRING(custom_route_global)
//
connect(ui->use_dns_object, &QCheckBox::stateChanged, this, [=](int state) {
auto useDNSObject = state == Qt::Checked;
ui->simple_dns_box->setDisabled(useDNSObject);
ui->dns_object->setDisabled(!useDNSObject);
});
ui->use_dns_object->stateChanged(Qt::Unchecked); // uncheck to uncheck
connect(ui->dns_document, &QPushButton::clicked, this, [=] {
MessageBoxInfo("DNS", dnsHelpDocumentUrl);
});
connect(ui->format_dns_object, &QPushButton::clicked, this, [=] {
auto obj = QString2QJsonObject(ui->dns_object->toPlainText());
if (obj.isEmpty()) {
MessageBoxInfo("DNS", "invaild json");
} else {
ui->dns_object->setPlainText(QJsonObject2QString(obj, false));
}
});
//
connect(ui->custom_route_edit, &QPushButton::clicked, this, [=] {
C_EDIT_JSON_ALLOW_EMPTY(custom_route)
});
connect(ui->custom_route_global_edit, &QPushButton::clicked, this, [=] {
C_EDIT_JSON_ALLOW_EMPTY(custom_route_global)
});
//
builtInSchemesMenu = new QMenu(this);
builtInSchemesMenu->addActions(this->getBuiltInSchemes());
ui->preset->setMenu(builtInSchemesMenu);
QString geoipFn = NekoGui::FindCoreAsset("geoip.dat");
QString geositeFn = NekoGui::FindCoreAsset("geosite.dat");
//
const auto sourceStringsDomain = Qv2ray::components::GeositeReader::ReadGeoSiteFromFile(geositeFn);
directDomainTxt = new AutoCompleteTextEdit("geosite", sourceStringsDomain, this);
proxyDomainTxt = new AutoCompleteTextEdit("geosite", sourceStringsDomain, this);
blockDomainTxt = new AutoCompleteTextEdit("geosite", sourceStringsDomain, this);
//
const auto sourceStringsIP = Qv2ray::components::GeositeReader::ReadGeoSiteFromFile(geoipFn);
directIPTxt = new AutoCompleteTextEdit("geoip", sourceStringsIP, this);
proxyIPTxt = new AutoCompleteTextEdit("geoip", sourceStringsIP, this);
blockIPTxt = new AutoCompleteTextEdit("geoip", sourceStringsIP, this);
//
ui->directTxtLayout->addWidget(directDomainTxt, 0, 0);
ui->proxyTxtLayout->addWidget(proxyDomainTxt, 0, 0);
ui->blockTxtLayout->addWidget(blockDomainTxt, 0, 0);
//
ui->directIPLayout->addWidget(directIPTxt, 0, 0);
ui->proxyIPLayout->addWidget(proxyIPTxt, 0, 0);
ui->blockIPLayout->addWidget(blockIPTxt, 0, 0);
//
REFRESH_ACTIVE_ROUTING(NekoGui::dataStore->active_routing, NekoGui::dataStore->routing.get())
ADD_ASTERISK(this)
}
DialogManageRoutes::~DialogManageRoutes() {
delete ui;
}
void DialogManageRoutes::accept() {
D_C_SAVE_STRING(custom_route_global)
bool routeChanged = false;
if (NekoGui::dataStore->active_routing != active_routing) routeChanged = true;
SaveDisplayRouting(NekoGui::dataStore->routing.get());
NekoGui::dataStore->active_routing = active_routing;
NekoGui::dataStore->routing->fn = ROUTES_PREFIX + NekoGui::dataStore->active_routing;
if (NekoGui::dataStore->routing->Save()) routeChanged = true;
//
QString info = "UpdateDataStore";
if (routeChanged) info += "RouteChanged";
MW_dialog_message(Dialog_DialogManageRoutes, info);
QDialog::accept();
}
// built in settings
QList<QAction *> DialogManageRoutes::getBuiltInSchemes() {
QList<QAction *> list;
list.append(this->schemeToAction(tr("Bypass LAN and China"), routing_cn_lan));
list.append(this->schemeToAction(tr("Global"), routing_global));
return list;
}
QAction *DialogManageRoutes::schemeToAction(const QString &name, const NekoGui::Routing &scheme) {
auto *action = new QAction(name, this);
connect(action, &QAction::triggered, [this, &scheme] { this->UpdateDisplayRouting((NekoGui::Routing *) &scheme, true); });
return action;
}
void DialogManageRoutes::UpdateDisplayRouting(NekoGui::Routing *conf, bool qv) {
//
directDomainTxt->setPlainText(conf->direct_domain);
proxyDomainTxt->setPlainText(conf->proxy_domain);
blockDomainTxt->setPlainText(conf->block_domain);
//
blockIPTxt->setPlainText(conf->block_ip);
directIPTxt->setPlainText(conf->direct_ip);
proxyIPTxt->setPlainText(conf->proxy_ip);
//
CACHE.custom_route = conf->custom;
ui->def_outbound->setCurrentText(conf->def_outbound);
//
if (qv) return;
//
ui->sniffing_mode->setCurrentIndex(conf->sniffing_mode);
ui->outbound_domain_strategy->setCurrentText(conf->outbound_domain_strategy);
ui->domainStrategyCombo->setCurrentText(conf->domain_strategy);
ui->use_dns_object->setChecked(conf->use_dns_object);
ui->dns_object->setPlainText(conf->dns_object);
ui->dns_routing->setChecked(conf->dns_routing);
ui->remote_dns->setCurrentText(conf->remote_dns);
ui->remote_dns_strategy->setCurrentText(conf->remote_dns_strategy);
ui->direct_dns->setCurrentText(conf->direct_dns);
ui->direct_dns_strategy->setCurrentText(conf->direct_dns_strategy);
ui->dns_final_out->setCurrentText(conf->dns_final_out);
}
void DialogManageRoutes::SaveDisplayRouting(NekoGui::Routing *conf) {
conf->direct_ip = directIPTxt->toPlainText();
conf->direct_domain = directDomainTxt->toPlainText();
conf->proxy_ip = proxyIPTxt->toPlainText();
conf->proxy_domain = proxyDomainTxt->toPlainText();
conf->block_ip = blockIPTxt->toPlainText();
conf->block_domain = blockDomainTxt->toPlainText();
conf->def_outbound = ui->def_outbound->currentText();
conf->custom = CACHE.custom_route;
//
conf->sniffing_mode = ui->sniffing_mode->currentIndex();
conf->domain_strategy = ui->domainStrategyCombo->currentText();
conf->outbound_domain_strategy = ui->outbound_domain_strategy->currentText();
conf->use_dns_object = ui->use_dns_object->isChecked();
conf->dns_object = ui->dns_object->toPlainText();
conf->dns_routing = ui->dns_routing->isChecked();
conf->remote_dns = ui->remote_dns->currentText();
conf->remote_dns_strategy = ui->remote_dns_strategy->currentText();
conf->direct_dns = ui->direct_dns->currentText();
conf->direct_dns_strategy = ui->direct_dns_strategy->currentText();
conf->dns_final_out = ui->dns_final_out->currentText();
}
void DialogManageRoutes::on_load_save_clicked() {
auto w = new QDialog;
auto layout = new QVBoxLayout;
w->setLayout(layout);
auto lineEdit = new QLineEdit;
layout->addWidget(lineEdit);
auto list = new QListWidget;
layout->addWidget(list);
for (const auto &name: NekoGui::Routing::List()) {
list->addItem(name);
}
connect(list, &QListWidget::currentTextChanged, lineEdit, &QLineEdit::setText);
auto bottom = new QHBoxLayout;
layout->addLayout(bottom);
auto load = new QPushButton;
load->setText(tr("Load"));
bottom->addWidget(load);
auto save = new QPushButton;
save->setText(tr("Save"));
bottom->addWidget(save);
auto remove = new QPushButton;
remove->setText(tr("Remove"));
bottom->addWidget(remove);
auto cancel = new QPushButton;
cancel->setText(tr("Cancel"));
bottom->addWidget(cancel);
connect(load, &QPushButton::clicked, w, [=] {
auto fn = lineEdit->text();
if (!fn.isEmpty()) {
auto r = std::make_unique<NekoGui::Routing>();
r->load_control_must = true;
r->fn = ROUTES_PREFIX + fn;
if (r->Load()) {
if (QMessageBox::question(nullptr, software_name, tr("Load routing: %1").arg(fn) + "\n" + r->DisplayRouting()) == QMessageBox::Yes) {
REFRESH_ACTIVE_ROUTING(fn, r.get()) // temp save to the window
w->accept();
}
}
}
});
connect(save, &QPushButton::clicked, w, [=] {
auto fn = lineEdit->text();
if (!fn.isEmpty()) {
auto r = std::make_unique<NekoGui::Routing>();
SaveDisplayRouting(r.get());
r->fn = ROUTES_PREFIX + fn;
if (QMessageBox::question(nullptr, software_name, tr("Save routing: %1").arg(fn) + "\n" + r->DisplayRouting()) == QMessageBox::Yes) {
r->Save();
REFRESH_ACTIVE_ROUTING(fn, r.get())
w->accept();
}
}
});
connect(remove, &QPushButton::clicked, w, [=] {
auto fn = lineEdit->text();
if (!fn.isEmpty() && NekoGui::Routing::List().length() > 1) {
if (QMessageBox::question(nullptr, software_name, tr("Remove routing: %1").arg(fn)) == QMessageBox::Yes) {
QFile f(ROUTES_PREFIX + fn);
f.remove();
if (NekoGui::dataStore->active_routing == fn) {
NekoGui::Routing::SetToActive(NekoGui::Routing::List().first());
REFRESH_ACTIVE_ROUTING(NekoGui::dataStore->active_routing, NekoGui::dataStore->routing.get())
}
w->accept();
}
}
});
connect(cancel, &QPushButton::clicked, w, &QDialog::accept);
connect(list, &QListWidget::itemDoubleClicked, this, [=](QListWidgetItem *item) {
lineEdit->setText(item->text());
emit load->clicked();
});
w->exec();
w->deleteLater();
}
| 10,752
|
C++
|
.cpp
| 236
| 39.34322
| 321
| 0.674983
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,634
|
ThemeManager.cpp
|
MatsuriDayo_nekoray/ui/ThemeManager.cpp
|
#include <QStyle>
#include <QApplication>
#include <QStyleFactory>
#include "ThemeManager.hpp"
ThemeManager *themeManager = new ThemeManager;
extern QString ReadFileText(const QString &path);
void ThemeManager::ApplyTheme(const QString &theme) {
auto internal = [=] {
if (this->system_style_name.isEmpty()) {
this->system_style_name = qApp->style()->objectName();
}
if (this->current_theme == theme) {
return;
}
bool ok;
auto themeId = theme.toInt(&ok);
if (ok) {
// System & Built-in
QString qss;
if (themeId != 0) {
QString path;
std::map<QString, QString> replace;
switch (themeId) {
case 1:
path = ":/themes/feiyangqingyun/qss/flatgray.css";
replace[":/qss/"] = ":/themes/feiyangqingyun/qss/";
break;
case 2:
path = ":/themes/feiyangqingyun/qss/lightblue.css";
replace[":/qss/"] = ":/themes/feiyangqingyun/qss/";
break;
case 3:
path = ":/themes/feiyangqingyun/qss/blacksoft.css";
replace[":/qss/"] = ":/themes/feiyangqingyun/qss/";
break;
default:
return;
}
qss = ReadFileText(path);
for (auto const &[a, b]: replace) {
qss = qss.replace(a, b);
}
}
auto system_style = QStyleFactory::create(this->system_style_name);
if (themeId == 0) {
// system theme
qApp->setPalette(system_style->standardPalette());
qApp->setStyle(system_style);
qApp->setStyleSheet("");
} else {
if (themeId == 1 || themeId == 2 || themeId == 3) {
// feiyangqingyun theme
QString paletteColor = qss.mid(20, 7);
qApp->setPalette(QPalette(paletteColor));
} else {
// other theme
qApp->setPalette(system_style->standardPalette());
}
qApp->setStyleSheet(qss);
}
} else {
// QStyleFactory
const auto &_style = QStyleFactory::create(theme);
if (_style != nullptr) {
qApp->setPalette(_style->standardPalette());
qApp->setStyle(_style);
qApp->setStyleSheet("");
}
}
current_theme = theme;
};
internal();
auto nekoray_css = ReadFileText(":/neko/neko.css");
qApp->setStyleSheet(qApp->styleSheet().append("\n").append(nekoray_css));
}
| 2,907
|
C++
|
.cpp
| 75
| 24.333333
| 79
| 0.470046
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,635
|
dialog_basic_settings.cpp
|
MatsuriDayo_nekoray/ui/dialog_basic_settings.cpp
|
#include "dialog_basic_settings.h"
#include "ui_dialog_basic_settings.h"
#include "3rdparty/qv2ray/v2/ui/widgets/editors/w_JsonEditor.hpp"
#include "fmt/Preset.hpp"
#include "ui/ThemeManager.hpp"
#include "ui/Icon.hpp"
#include "main/GuiUtils.hpp"
#include "main/NekoGui.hpp"
#include <QStyleFactory>
#include <QFileDialog>
#include <QInputDialog>
#include <QMessageBox>
#include <QTimer>
class ExtraCoreWidget : public QWidget {
public:
QString coreName;
QLabel *label_name;
MyLineEdit *lineEdit_path;
QPushButton *pushButton_pick;
explicit ExtraCoreWidget(QJsonObject *extraCore, const QString &coreName_,
QWidget *parent = nullptr)
: QWidget(parent) {
coreName = coreName_;
label_name = new QLabel;
label_name->setText(coreName);
lineEdit_path = new MyLineEdit;
lineEdit_path->setText(extraCore->value(coreName).toString());
pushButton_pick = new QPushButton;
pushButton_pick->setText(QObject::tr("Select"));
auto layout = new QHBoxLayout;
layout->addWidget(label_name);
layout->addWidget(lineEdit_path);
layout->addWidget(pushButton_pick);
setLayout(layout);
setContentsMargins(0, 0, 0, 0);
//
connect(pushButton_pick, &QPushButton::clicked, this, [=] {
auto fn = QFileDialog::getOpenFileName(this, QObject::tr("Select"), QDir::currentPath(),
"", nullptr, QFileDialog::Option::ReadOnly);
if (!fn.isEmpty()) {
lineEdit_path->setText(fn);
}
});
connect(lineEdit_path, &QLineEdit::textChanged, this, [=](const QString &newTxt) {
extraCore->insert(coreName, newTxt);
});
}
};
DialogBasicSettings::DialogBasicSettings(QWidget *parent)
: QDialog(parent), ui(new Ui::DialogBasicSettings) {
ui->setupUi(this);
ADD_ASTERISK(this);
// Common
ui->log_level->addItems(QString("trace debug info warn error fatal panic").split(" "));
ui->mux_protocol->addItems({"h2mux", "smux", "yamux"});
refresh_auth();
D_LOAD_STRING(inbound_address)
D_LOAD_COMBO_STRING(log_level)
CACHE.custom_inbound = NekoGui::dataStore->custom_inbound;
D_LOAD_INT(inbound_socks_port)
D_LOAD_INT(test_concurrent)
D_LOAD_INT(test_download_timeout)
D_LOAD_STRING(test_latency_url)
D_LOAD_STRING(test_download_url)
D_LOAD_BOOL(old_share_link_format)
connect(ui->custom_inbound_edit, &QPushButton::clicked, this, [=] {
C_EDIT_JSON_ALLOW_EMPTY(custom_inbound)
});
#ifdef Q_OS_WIN
connect(ui->sys_proxy_format, &QPushButton::clicked, this, [=] {
bool ok;
auto str = QInputDialog::getItem(this, ui->sys_proxy_format->text() + " (Windows)",
tr("Advanced system proxy settings. Please select a format."),
Preset::Windows::system_proxy_format,
Preset::Windows::system_proxy_format.indexOf(NekoGui::dataStore->system_proxy_format),
false, &ok);
if (ok) NekoGui::dataStore->system_proxy_format = str;
});
#else
ui->sys_proxy_format->hide();
#endif
// Style
ui->connection_statistics_box->setDisabled(true);
//
D_LOAD_BOOL(check_include_pre)
D_LOAD_BOOL(connection_statistics)
D_LOAD_BOOL(start_minimal)
D_LOAD_INT(max_log_line)
//
if (NekoGui::dataStore->traffic_loop_interval == 500) {
ui->rfsh_r->setCurrentIndex(0);
} else if (NekoGui::dataStore->traffic_loop_interval == 1000) {
ui->rfsh_r->setCurrentIndex(1);
} else if (NekoGui::dataStore->traffic_loop_interval == 2000) {
ui->rfsh_r->setCurrentIndex(2);
} else if (NekoGui::dataStore->traffic_loop_interval == 3000) {
ui->rfsh_r->setCurrentIndex(3);
} else if (NekoGui::dataStore->traffic_loop_interval == 5000) {
ui->rfsh_r->setCurrentIndex(4);
} else {
ui->rfsh_r->setCurrentIndex(5);
}
//
ui->language->setCurrentIndex(NekoGui::dataStore->language);
connect(ui->language, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, [=](int index) {
CACHE.needRestart = true;
});
//
int built_in_len = ui->theme->count();
ui->theme->addItems(QStyleFactory::keys());
//
bool ok;
auto themeId = NekoGui::dataStore->theme.toInt(&ok);
if (ok) {
ui->theme->setCurrentIndex(themeId);
} else {
ui->theme->setCurrentText(NekoGui::dataStore->theme);
}
//
connect(ui->theme, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, [=](int index) {
if (index + 1 <= built_in_len) {
themeManager->ApplyTheme(Int2String(index));
NekoGui::dataStore->theme = Int2String(index);
} else {
themeManager->ApplyTheme(ui->theme->currentText());
NekoGui::dataStore->theme = ui->theme->currentText();
}
repaint();
mainwindow->repaint();
NekoGui::dataStore->Save();
});
// Subscription
ui->user_agent->setText(NekoGui::dataStore->user_agent);
ui->user_agent->setPlaceholderText(NekoGui::dataStore->GetUserAgent(true));
D_LOAD_BOOL(sub_use_proxy)
D_LOAD_BOOL(sub_clear)
D_LOAD_BOOL(sub_insecure)
D_LOAD_INT_ENABLE(sub_auto_update, sub_auto_update_enable)
// Core
ui->groupBox_core->setTitle(software_core_name);
//
CACHE.extraCore = QString2QJsonObject(NekoGui::dataStore->extraCore->core_map);
if (!CACHE.extraCore.contains("naive")) CACHE.extraCore.insert("naive", "");
if (!CACHE.extraCore.contains("hysteria2")) CACHE.extraCore.insert("hysteria2", "");
if (!CACHE.extraCore.contains("tuic")) CACHE.extraCore.insert("tuic", "");
//
auto extra_core_layout = ui->extra_core_box_scrollAreaWidgetContents->layout();
for (const auto &s: CACHE.extraCore.keys()) {
extra_core_layout->addWidget(new ExtraCoreWidget(&CACHE.extraCore, s));
}
//
connect(ui->extra_core_add, &QPushButton::clicked, this, [=] {
bool ok;
auto s = QInputDialog::getText(nullptr, tr("Add"),
tr("Please input the core name."),
QLineEdit::Normal, "", &ok)
.trimmed();
if (s.isEmpty() || !ok) return;
if (CACHE.extraCore.contains(s)) return;
extra_core_layout->addWidget(new ExtraCoreWidget(&CACHE.extraCore, s));
CACHE.extraCore.insert(s, "");
});
connect(ui->extra_core_del, &QPushButton::clicked, this, [=] {
bool ok;
auto s = QInputDialog::getItem(nullptr, tr("Delete"),
tr("Please select the core name."),
CACHE.extraCore.keys(), 0, false, &ok);
if (s.isEmpty() || !ok) return;
for (int i = 0; i < extra_core_layout->count(); i++) {
auto item = extra_core_layout->itemAt(i);
auto ecw = dynamic_cast<ExtraCoreWidget *>(item->widget());
if (ecw != nullptr && ecw->coreName == s) {
ecw->deleteLater();
CACHE.extraCore.remove(s);
return;
}
}
});
// Mux
D_LOAD_INT(mux_concurrency)
D_LOAD_COMBO_STRING(mux_protocol)
D_LOAD_BOOL(mux_padding)
D_LOAD_BOOL(mux_default_on)
// Security
ui->utlsFingerprint->addItems(Preset::SingBox::UtlsFingerPrint);
D_LOAD_BOOL(skip_cert)
ui->utlsFingerprint->setCurrentText(NekoGui::dataStore->utlsFingerprint);
}
DialogBasicSettings::~DialogBasicSettings() {
delete ui;
}
void DialogBasicSettings::accept() {
// Common
D_SAVE_STRING(inbound_address)
D_SAVE_COMBO_STRING(log_level)
NekoGui::dataStore->custom_inbound = CACHE.custom_inbound;
D_SAVE_INT(inbound_socks_port)
D_SAVE_INT(test_concurrent)
D_SAVE_INT(test_download_timeout)
D_SAVE_STRING(test_latency_url)
D_SAVE_STRING(test_download_url)
D_SAVE_BOOL(old_share_link_format)
// Style
NekoGui::dataStore->language = ui->language->currentIndex();
D_SAVE_BOOL(connection_statistics)
D_SAVE_BOOL(check_include_pre)
D_SAVE_BOOL(start_minimal)
D_SAVE_INT(max_log_line)
if (NekoGui::dataStore->max_log_line <= 0) {
NekoGui::dataStore->max_log_line = 200;
}
if (ui->rfsh_r->currentIndex() == 0) {
NekoGui::dataStore->traffic_loop_interval = 500;
} else if (ui->rfsh_r->currentIndex() == 1) {
NekoGui::dataStore->traffic_loop_interval = 1000;
} else if (ui->rfsh_r->currentIndex() == 2) {
NekoGui::dataStore->traffic_loop_interval = 2000;
} else if (ui->rfsh_r->currentIndex() == 3) {
NekoGui::dataStore->traffic_loop_interval = 3000;
} else if (ui->rfsh_r->currentIndex() == 4) {
NekoGui::dataStore->traffic_loop_interval = 5000;
} else {
NekoGui::dataStore->traffic_loop_interval = 0;
}
// Subscription
if (ui->sub_auto_update_enable->isChecked()) {
TM_auto_update_subsctiption_Reset_Minute(ui->sub_auto_update->text().toInt());
} else {
TM_auto_update_subsctiption_Reset_Minute(0);
}
NekoGui::dataStore->user_agent = ui->user_agent->text();
D_SAVE_BOOL(sub_use_proxy)
D_SAVE_BOOL(sub_clear)
D_SAVE_BOOL(sub_insecure)
D_SAVE_INT_ENABLE(sub_auto_update, sub_auto_update_enable)
// Core
NekoGui::dataStore->extraCore->core_map = QJsonObject2QString(CACHE.extraCore, true);
// Mux
D_SAVE_INT(mux_concurrency)
D_SAVE_COMBO_STRING(mux_protocol)
D_SAVE_BOOL(mux_padding)
D_SAVE_BOOL(mux_default_on)
// Security
D_SAVE_BOOL(skip_cert)
NekoGui::dataStore->utlsFingerprint = ui->utlsFingerprint->currentText();
// 关闭连接统计,停止刷新前清空记录。
if (NekoGui::dataStore->traffic_loop_interval == 0 || !NekoGui::dataStore->connection_statistics) {
MW_dialog_message("", "ClearConnectionList");
}
QStringList str{"UpdateDataStore"};
if (CACHE.needRestart) str << "NeedRestart";
MW_dialog_message(Dialog_DialogBasicSettings, str.join(","));
QDialog::accept();
}
// slots
void DialogBasicSettings::refresh_auth() {
ui->inbound_auth->setText({});
if (NekoGui::dataStore->inbound_auth->NeedAuth()) {
ui->inbound_auth->setIcon(Icon::GetMaterialIcon("lock-outline"));
} else {
ui->inbound_auth->setIcon(Icon::GetMaterialIcon("lock-open-outline"));
}
}
void DialogBasicSettings::on_set_custom_icon_clicked() {
auto title = ui->set_custom_icon->text();
QString user_icon_path = "./" + software_name.toLower() + ".png";
auto c = QMessageBox::question(this, title, tr("Please select a PNG file."),
tr("Select"), tr("Reset"), tr("Cancel"), 2, 2);
if (c == 0) {
auto fn = QFileDialog::getOpenFileName(this, QObject::tr("Select"), QDir::currentPath(),
"*.png", nullptr, QFileDialog::Option::ReadOnly);
QImage img(fn);
if (img.isNull() || img.height() != img.width()) {
MessageBoxWarning(title, tr("Please select a valid square image."));
return;
}
QFile::remove(user_icon_path);
QFile::copy(fn, user_icon_path);
} else if (c == 1) {
QFile::remove(user_icon_path);
} else {
return;
}
MW_dialog_message(Dialog_DialogBasicSettings, "UpdateIcon");
}
void DialogBasicSettings::on_inbound_auth_clicked() {
auto w = new QDialog(this);
w->setWindowTitle(tr("Inbound Auth"));
auto layout = new QGridLayout;
w->setLayout(layout);
//
auto user_l = new QLabel(tr("Username"));
auto pass_l = new QLabel(tr("Password"));
auto user = new MyLineEdit;
auto pass = new MyLineEdit;
user->setText(NekoGui::dataStore->inbound_auth->username);
pass->setText(NekoGui::dataStore->inbound_auth->password);
//
layout->addWidget(user_l, 0, 0);
layout->addWidget(user, 0, 1);
layout->addWidget(pass_l, 1, 0);
layout->addWidget(pass, 1, 1);
auto box = new QDialogButtonBox;
box->setOrientation(Qt::Horizontal);
box->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Ok);
connect(box, &QDialogButtonBox::accepted, w, [=] {
NekoGui::dataStore->inbound_auth->username = user->text();
NekoGui::dataStore->inbound_auth->password = pass->text();
MW_dialog_message(Dialog_DialogBasicSettings, "UpdateDataStore");
w->accept();
});
connect(box, &QDialogButtonBox::rejected, w, &QDialog::reject);
layout->addWidget(box, 2, 1);
//
w->exec();
w->deleteLater();
refresh_auth();
}
void DialogBasicSettings::on_core_settings_clicked() {
auto w = new QDialog(this);
w->setWindowTitle(software_core_name + " Core Options");
auto layout = new QGridLayout;
w->setLayout(layout);
//
auto line = -1;
QCheckBox *core_box_enable_clash_api;
MyLineEdit *core_box_clash_api;
MyLineEdit *core_box_clash_api_secret;
MyLineEdit *core_box_underlying_dns;
//
auto core_box_underlying_dns_l = new QLabel(tr("Override underlying DNS"));
core_box_underlying_dns = new MyLineEdit;
core_box_underlying_dns->setText(NekoGui::dataStore->core_box_underlying_dns);
core_box_underlying_dns->setMinimumWidth(300);
layout->addWidget(core_box_underlying_dns_l, ++line, 0);
layout->addWidget(core_box_underlying_dns, line, 1);
//
auto core_box_enable_clash_api_l = new QLabel("Enable Clash API");
core_box_enable_clash_api = new QCheckBox;
core_box_enable_clash_api->setChecked(NekoGui::dataStore->core_box_clash_api > 0);
layout->addWidget(core_box_enable_clash_api_l, ++line, 0);
layout->addWidget(core_box_enable_clash_api, line, 1);
//
auto core_box_clash_api_l = new QLabel("Clash API Listen Port");
core_box_clash_api = new MyLineEdit;
core_box_clash_api->setText(Int2String(std::abs(NekoGui::dataStore->core_box_clash_api)));
layout->addWidget(core_box_clash_api_l, ++line, 0);
layout->addWidget(core_box_clash_api, line, 1);
//
auto core_box_clash_api_secret_l = new QLabel("Clash API Secret");
core_box_clash_api_secret = new MyLineEdit;
core_box_clash_api_secret->setText(NekoGui::dataStore->core_box_clash_api_secret);
layout->addWidget(core_box_clash_api_secret_l, ++line, 0);
layout->addWidget(core_box_clash_api_secret, line, 1);
//
auto box = new QDialogButtonBox;
box->setOrientation(Qt::Horizontal);
box->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Ok);
connect(box, &QDialogButtonBox::accepted, w, [=] {
NekoGui::dataStore->core_box_underlying_dns = core_box_underlying_dns->text();
NekoGui::dataStore->core_box_clash_api = core_box_clash_api->text().toInt() * (core_box_enable_clash_api->isChecked() ? 1 : -1);
NekoGui::dataStore->core_box_clash_api_secret = core_box_clash_api_secret->text();
MW_dialog_message(Dialog_DialogBasicSettings, "UpdateDataStore");
w->accept();
});
connect(box, &QDialogButtonBox::rejected, w, &QDialog::reject);
layout->addWidget(box, ++line, 1);
//
ADD_ASTERISK(w)
w->exec();
w->deleteLater();
refresh_auth();
}
| 15,517
|
C++
|
.cpp
| 373
| 34.273458
| 136
| 0.634632
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
10,636
|
mainwindow.cpp
|
MatsuriDayo_nekoray/ui/mainwindow.cpp
|
#include "./ui_mainwindow.h"
#include "mainwindow.h"
#include "fmt/Preset.hpp"
#include "db/ProfileFilter.hpp"
#include "db/ConfigBuilder.hpp"
#include "sub/GroupUpdater.hpp"
#include "sys/ExternalProcess.hpp"
#include "sys/AutoRun.hpp"
#include "ui/ThemeManager.hpp"
#include "ui/Icon.hpp"
#include "ui/edit/dialog_edit_profile.h"
#include "ui/dialog_basic_settings.h"
#include "ui/dialog_manage_groups.h"
#include "ui/dialog_manage_routes.h"
#include "ui/dialog_vpn_settings.h"
#include "ui/dialog_hotkey.h"
#include "3rdparty/fix_old_qt.h"
#include "3rdparty/qrcodegen.hpp"
#include "3rdparty/VT100Parser.hpp"
#include "3rdparty/qv2ray/v2/components/proxy/QvProxyConfigurator.hpp"
#ifndef NKR_NO_ZXING
#include "3rdparty/ZxingQtReader.hpp"
#endif
#ifdef Q_OS_WIN
#include "3rdparty/WinCommander.hpp"
#else
#ifdef Q_OS_LINUX
#include "sys/linux/LinuxCap.h"
#endif
#include <unistd.h>
#endif
#include <QClipboard>
#include <QLabel>
#include <QTextBlock>
#include <QScrollBar>
#include <QScreen>
#include <QDesktopServices>
#include <QInputDialog>
#include <QThread>
#include <QTimer>
#include <QMessageBox>
#include <QDir>
#include <QFileInfo>
void UI_InitMainWindow() {
mainwindow = new MainWindow;
}
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) {
mainwindow = this;
MW_dialog_message = [=](const QString &a, const QString &b) {
runOnUiThread([=] { dialog_message_impl(a, b); });
};
// Load Manager
NekoGui::profileManager->LoadManager();
// Setup misc UI
themeManager->ApplyTheme(NekoGui::dataStore->theme);
ui->setupUi(this);
//
connect(ui->menu_start, &QAction::triggered, this, [=]() { neko_start(); });
connect(ui->menu_stop, &QAction::triggered, this, [=]() { neko_stop(); });
connect(ui->tabWidget->tabBar(), &QTabBar::tabMoved, this, [=](int from, int to) {
// use tabData to track tab & gid
NekoGui::profileManager->groupsTabOrder.clear();
for (int i = 0; i < ui->tabWidget->tabBar()->count(); i++) {
NekoGui::profileManager->groupsTabOrder += ui->tabWidget->tabBar()->tabData(i).toInt();
}
NekoGui::profileManager->SaveManager();
});
ui->label_running->installEventFilter(this);
ui->label_inbound->installEventFilter(this);
ui->splitter->installEventFilter(this);
//
RegisterHotkey(false);
//
auto last_size = NekoGui::dataStore->mw_size.split("x");
if (last_size.length() == 2) {
auto w = last_size[0].toInt();
auto h = last_size[1].toInt();
if (w > 0 && h > 0) {
resize(w, h);
}
}
if (QDir("dashboard").count() == 0) {
QDir().mkdir("dashboard");
QFile::copy(":/neko/dashboard-notice.html", "dashboard/index.html");
}
// top bar
ui->toolButton_program->setMenu(ui->menu_program);
ui->toolButton_preferences->setMenu(ui->menu_preferences);
ui->toolButton_server->setMenu(ui->menu_server);
ui->menubar->setVisible(false);
connect(ui->toolButton_document, &QToolButton::clicked, this, [=] { QDesktopServices::openUrl(QUrl("https://matsuridayo.github.io/")); });
connect(ui->toolButton_ads, &QToolButton::clicked, this, [=] { QDesktopServices::openUrl(QUrl("https://matsuricom.pages.dev/")); });
connect(ui->toolButton_update, &QToolButton::clicked, this, [=] { runOnNewThread([=] { CheckUpdate(); }); });
connect(ui->toolButton_url_test, &QToolButton::clicked, this, [=] { speedtest_current_group(1, true); });
// Setup log UI
ui->splitter->restoreState(DecodeB64IfValid(NekoGui::dataStore->splitter_state));
qvLogDocument->setUndoRedoEnabled(false);
ui->masterLogBrowser->setUndoRedoEnabled(false);
ui->masterLogBrowser->setDocument(qvLogDocument);
ui->masterLogBrowser->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));
{
auto font = ui->masterLogBrowser->font();
font.setPointSize(9);
ui->masterLogBrowser->setFont(font);
qvLogDocument->setDefaultFont(font);
}
connect(ui->masterLogBrowser->verticalScrollBar(), &QSlider::valueChanged, this, [=](int value) {
if (ui->masterLogBrowser->verticalScrollBar()->maximum() == value)
qvLogAutoScoll = true;
else
qvLogAutoScoll = false;
});
connect(ui->masterLogBrowser, &QTextBrowser::textChanged, this, [=]() {
if (!qvLogAutoScoll)
return;
auto bar = ui->masterLogBrowser->verticalScrollBar();
bar->setValue(bar->maximum());
});
MW_show_log = [=](const QString &log) {
runOnUiThread([=] { show_log_impl(log); });
};
MW_show_log_ext = [=](const QString &tag, const QString &log) {
runOnUiThread([=] { show_log_impl("[" + tag + "] " + log); });
};
MW_show_log_ext_vt100 = [=](const QString &log) {
runOnUiThread([=] { show_log_impl(cleanVT100String(log)); });
};
// table UI
ui->proxyListTable->callback_save_order = [=] {
auto group = NekoGui::profileManager->CurrentGroup();
group->order = ui->proxyListTable->order;
group->Save();
};
ui->proxyListTable->refresh_data = [=](int id) { refresh_proxy_list_impl_refresh_data(id); };
if (auto button = ui->proxyListTable->findChild<QAbstractButton *>(QString(), Qt::FindDirectChildrenOnly)) {
// Corner Button
connect(button, &QAbstractButton::clicked, this, [=] { refresh_proxy_list_impl(-1, {GroupSortMethod::ById}); });
}
connect(ui->proxyListTable->horizontalHeader(), &QHeaderView::sectionClicked, this, [=](int logicalIndex) {
GroupSortAction action;
// 不正确的descending实现
if (proxy_last_order == logicalIndex) {
action.descending = true;
proxy_last_order = -1;
} else {
proxy_last_order = logicalIndex;
}
action.save_sort = true;
// 表头
if (logicalIndex == 0) {
action.method = GroupSortMethod::ByType;
} else if (logicalIndex == 1) {
action.method = GroupSortMethod::ByAddress;
} else if (logicalIndex == 2) {
action.method = GroupSortMethod::ByName;
} else if (logicalIndex == 3) {
action.method = GroupSortMethod::ByLatency;
} else {
return;
}
refresh_proxy_list_impl(-1, action);
});
connect(ui->proxyListTable->horizontalHeader(), &QHeaderView::sectionResized, this, [=](int logicalIndex, int oldSize, int newSize) {
auto group = NekoGui::profileManager->CurrentGroup();
if (NekoGui::dataStore->refreshing_group || group == nullptr || !group->manually_column_width) return;
// save manually column width
group->column_width.clear();
for (int i = 0; i < ui->proxyListTable->horizontalHeader()->count(); i++) {
group->column_width.push_back(ui->proxyListTable->horizontalHeader()->sectionSize(i));
}
group->column_width[logicalIndex] = newSize;
group->Save();
});
ui->tableWidget_conn->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
ui->tableWidget_conn->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
ui->tableWidget_conn->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch);
ui->proxyListTable->verticalHeader()->setDefaultSectionSize(24);
// search box
ui->search->setVisible(false);
connect(shortcut_ctrl_f, &QShortcut::activated, this, [=] {
ui->search->setVisible(true);
ui->search->setFocus();
});
connect(shortcut_esc, &QShortcut::activated, this, [=] {
if (ui->search->isVisible()) {
ui->search->setText("");
ui->search->textChanged("");
ui->search->setVisible(false);
}
if (select_mode) {
emit profile_selected(-1);
select_mode = false;
refresh_status();
}
});
connect(ui->search, &QLineEdit::textChanged, this, [=](const QString &text) {
if (text.isEmpty()) {
for (int i = 0; i < ui->proxyListTable->rowCount(); i++) {
ui->proxyListTable->setRowHidden(i, false);
}
} else {
QList<QTableWidgetItem *> findItem = ui->proxyListTable->findItems(text, Qt::MatchContains);
for (int i = 0; i < ui->proxyListTable->rowCount(); i++) {
ui->proxyListTable->setRowHidden(i, true);
}
for (auto item: findItem) {
if (item != nullptr) ui->proxyListTable->setRowHidden(item->row(), false);
}
}
});
// refresh
this->refresh_groups();
// Setup Tray
tray = new QSystemTrayIcon(this); // 初始化托盘对象tray
tray->setIcon(Icon::GetTrayIcon(Icon::NONE));
tray->setContextMenu(ui->menu_program); // 创建托盘菜单
tray->show(); // 让托盘图标显示在系统托盘上
connect(tray, &QSystemTrayIcon::activated, this, [=](QSystemTrayIcon::ActivationReason reason) {
if (reason == QSystemTrayIcon::Trigger) {
if (this->isVisible()) {
hide();
} else {
ActivateWindow(this);
}
}
});
// Misc menu
connect(ui->menu_open_config_folder, &QAction::triggered, this, [=] { QDesktopServices::openUrl(QUrl::fromLocalFile(QDir::currentPath())); });
ui->menu_program_preference->addActions(ui->menu_preferences->actions());
connect(ui->menu_add_from_clipboard2, &QAction::triggered, ui->menu_add_from_clipboard, &QAction::trigger);
connect(ui->actionRestart_Proxy, &QAction::triggered, this, [=] { if (NekoGui::dataStore->started_id>=0) neko_start(NekoGui::dataStore->started_id); });
connect(ui->actionRestart_Program, &QAction::triggered, this, [=] { MW_dialog_message("", "RestartProgram"); });
connect(ui->actionShow_window, &QAction::triggered, this, [=] { tray->activated(QSystemTrayIcon::ActivationReason::Trigger); });
//
connect(ui->menu_program, &QMenu::aboutToShow, this, [=]() {
ui->actionRemember_last_proxy->setChecked(NekoGui::dataStore->remember_enable);
ui->actionStart_with_system->setChecked(AutoRun_IsEnabled());
ui->actionAllow_LAN->setChecked(QStringList{"::", "0.0.0.0"}.contains(NekoGui::dataStore->inbound_address));
// active server
for (const auto &old: ui->menuActive_Server->actions()) {
ui->menuActive_Server->removeAction(old);
old->deleteLater();
}
int active_server_item_count = 0;
for (const auto &pf: NekoGui::profileManager->CurrentGroup()->ProfilesWithOrder()) {
auto a = new QAction(pf->bean->DisplayTypeAndName(), this);
a->setProperty("id", pf->id);
a->setCheckable(true);
if (NekoGui::dataStore->started_id == pf->id) a->setChecked(true);
ui->menuActive_Server->addAction(a);
if (++active_server_item_count == 100) break;
}
// active routing
for (const auto &old: ui->menuActive_Routing->actions()) {
ui->menuActive_Routing->removeAction(old);
old->deleteLater();
}
for (const auto &name: NekoGui::Routing::List()) {
auto a = new QAction(name, this);
a->setCheckable(true);
a->setChecked(name == NekoGui::dataStore->active_routing);
ui->menuActive_Routing->addAction(a);
}
});
connect(ui->menuActive_Server, &QMenu::triggered, this, [=](QAction *a) {
bool ok;
auto id = a->property("id").toInt(&ok);
if (!ok) return;
if (NekoGui::dataStore->started_id == id) {
neko_stop();
} else {
neko_start(id);
}
});
connect(ui->menuActive_Routing, &QMenu::triggered, this, [=](QAction *a) {
auto fn = a->text();
if (!fn.isEmpty()) {
NekoGui::Routing r;
r.load_control_must = true;
r.fn = ROUTES_PREFIX + fn;
if (r.Load()) {
if (QMessageBox::question(GetMessageBoxParent(), software_name, tr("Load routing and apply: %1").arg(fn) + "\n" + r.DisplayRouting()) == QMessageBox::Yes) {
NekoGui::Routing::SetToActive(fn);
if (NekoGui::dataStore->started_id >= 0) {
neko_start(NekoGui::dataStore->started_id);
} else {
refresh_status();
}
}
}
}
});
connect(ui->actionRemember_last_proxy, &QAction::triggered, this, [=](bool checked) {
NekoGui::dataStore->remember_enable = checked;
NekoGui::dataStore->Save();
});
connect(ui->actionStart_with_system, &QAction::triggered, this, [=](bool checked) {
AutoRun_SetEnabled(checked);
});
connect(ui->actionAllow_LAN, &QAction::triggered, this, [=](bool checked) {
NekoGui::dataStore->inbound_address = checked ? "::" : "127.0.0.1";
MW_dialog_message("", "UpdateDataStore");
});
//
connect(ui->checkBox_VPN, &QCheckBox::clicked, this, [=](bool checked) { neko_set_spmode_vpn(checked); });
connect(ui->checkBox_SystemProxy, &QCheckBox::clicked, this, [=](bool checked) { neko_set_spmode_system_proxy(checked); });
connect(ui->menu_spmode, &QMenu::aboutToShow, this, [=]() {
ui->menu_spmode_disabled->setChecked(!(NekoGui::dataStore->spmode_system_proxy || NekoGui::dataStore->spmode_vpn));
ui->menu_spmode_system_proxy->setChecked(NekoGui::dataStore->spmode_system_proxy);
ui->menu_spmode_vpn->setChecked(NekoGui::dataStore->spmode_vpn);
});
connect(ui->menu_spmode_system_proxy, &QAction::triggered, this, [=](bool checked) { neko_set_spmode_system_proxy(checked); });
connect(ui->menu_spmode_vpn, &QAction::triggered, this, [=](bool checked) { neko_set_spmode_vpn(checked); });
connect(ui->menu_spmode_disabled, &QAction::triggered, this, [=]() {
neko_set_spmode_system_proxy(false);
neko_set_spmode_vpn(false);
});
connect(ui->menu_qr, &QAction::triggered, this, [=]() { display_qr_link(false); });
connect(ui->menu_tcp_ping, &QAction::triggered, this, [=]() { speedtest_current_group(0, false); });
connect(ui->menu_url_test, &QAction::triggered, this, [=]() { speedtest_current_group(1, false); });
connect(ui->menu_full_test, &QAction::triggered, this, [=]() { speedtest_current_group(2, false); });
connect(ui->menu_stop_testing, &QAction::triggered, this, [=]() { speedtest_current_group(114514, false); });
//
auto set_selected_or_group = [=](int mode) {
// 0=group 1=select 2=unknown(menu is hide)
ui->menu_server->setProperty("selected_or_group", mode);
};
auto move_tests_to_menu = [=](bool menuCurrent_Select) {
return [=] {
if (menuCurrent_Select) {
ui->menuCurrent_Select->insertAction(ui->actionfake_4, ui->menu_tcp_ping);
ui->menuCurrent_Select->insertAction(ui->actionfake_4, ui->menu_url_test);
ui->menuCurrent_Select->insertAction(ui->actionfake_4, ui->menu_full_test);
ui->menuCurrent_Select->insertAction(ui->actionfake_4, ui->menu_stop_testing);
ui->menuCurrent_Select->insertAction(ui->actionfake_4, ui->menu_clear_test_result);
ui->menuCurrent_Select->insertAction(ui->actionfake_4, ui->menu_resolve_domain);
} else {
ui->menuCurrent_Group->insertAction(ui->actionfake_5, ui->menu_tcp_ping);
ui->menuCurrent_Group->insertAction(ui->actionfake_5, ui->menu_url_test);
ui->menuCurrent_Group->insertAction(ui->actionfake_5, ui->menu_full_test);
ui->menuCurrent_Group->insertAction(ui->actionfake_5, ui->menu_stop_testing);
ui->menuCurrent_Group->insertAction(ui->actionfake_5, ui->menu_clear_test_result);
ui->menuCurrent_Group->insertAction(ui->actionfake_5, ui->menu_resolve_domain);
}
set_selected_or_group(menuCurrent_Select ? 1 : 0);
};
};
connect(ui->menuCurrent_Select, &QMenu::aboutToShow, this, move_tests_to_menu(true));
connect(ui->menuCurrent_Group, &QMenu::aboutToShow, this, move_tests_to_menu(false));
connect(ui->menu_server, &QMenu::aboutToHide, this, [=] {
setTimeout([=] { set_selected_or_group(2); }, this, 200);
});
set_selected_or_group(2);
//
connect(ui->menu_share_item, &QMenu::aboutToShow, this, [=] {
QString name;
auto selected = get_now_selected_list();
if (!selected.isEmpty()) {
auto ent = selected.first();
name = ent->bean->DisplayCoreType();
}
ui->menu_export_config->setVisible(name == software_core_name);
ui->menu_export_config->setText(tr("Export %1 config").arg(name));
});
refresh_status();
// Prepare core
NekoGui::dataStore->core_token = GetRandomString(32);
NekoGui::dataStore->core_port = MkPort();
if (NekoGui::dataStore->core_port <= 0) NekoGui::dataStore->core_port = 19810;
auto core_path = QApplication::applicationDirPath() + "/";
core_path += "nekobox_core";
QStringList args;
args.push_back("nekobox");
args.push_back("-port");
args.push_back(Int2String(NekoGui::dataStore->core_port));
if (NekoGui::dataStore->flag_debug) args.push_back("-debug");
// Start core
runOnUiThread(
[=] {
core_process = new NekoGui_sys::CoreProcess(core_path, args);
// Remember last started
if (NekoGui::dataStore->remember_enable && NekoGui::dataStore->remember_id >= 0) {
core_process->start_profile_when_core_is_up = NekoGui::dataStore->remember_id;
}
// Setup
core_process->Start();
setup_grpc();
},
DS_cores);
// Remember system proxy
if (NekoGui::dataStore->remember_enable || NekoGui::dataStore->flag_restart_tun_on) {
if (NekoGui::dataStore->remember_spmode.contains("system_proxy")) {
neko_set_spmode_system_proxy(true, false);
}
if (NekoGui::dataStore->remember_spmode.contains("vpn") || NekoGui::dataStore->flag_restart_tun_on) {
neko_set_spmode_vpn(true, false);
}
}
connect(qApp, &QGuiApplication::commitDataRequest, this, &MainWindow::on_commitDataRequest);
auto t = new QTimer;
connect(t, &QTimer::timeout, this, [=]() { refresh_status(); });
t->start(2000);
t = new QTimer;
connect(t, &QTimer::timeout, this, [&] { NekoGui_sys::logCounter.fetchAndStoreRelaxed(0); });
t->start(1000);
TM_auto_update_subsctiption = new QTimer;
TM_auto_update_subsctiption_Reset_Minute = [&](int m) {
TM_auto_update_subsctiption->stop();
if (m >= 30) TM_auto_update_subsctiption->start(m * 60 * 1000);
};
connect(TM_auto_update_subsctiption, &QTimer::timeout, this, [&] { UI_update_all_groups(true); });
TM_auto_update_subsctiption_Reset_Minute(NekoGui::dataStore->sub_auto_update);
if (!NekoGui::dataStore->flag_tray) show();
}
void MainWindow::closeEvent(QCloseEvent *event) {
if (tray->isVisible()) {
hide(); // 隐藏窗口
event->ignore(); // 忽略事件
}
}
MainWindow::~MainWindow() {
delete ui;
}
// Group tab manage
inline int tabIndex2GroupId(int index) {
if (NekoGui::profileManager->groupsTabOrder.length() <= index) return -1;
return NekoGui::profileManager->groupsTabOrder[index];
}
inline int groupId2TabIndex(int gid) {
for (int key = 0; key < NekoGui::profileManager->groupsTabOrder.count(); key++) {
if (NekoGui::profileManager->groupsTabOrder[key] == gid) return key;
}
return 0;
}
void MainWindow::on_tabWidget_currentChanged(int index) {
if (NekoGui::dataStore->refreshing_group_list) return;
if (tabIndex2GroupId(index) == NekoGui::dataStore->current_group) return;
show_group(tabIndex2GroupId(index));
}
void MainWindow::show_group(int gid) {
if (NekoGui::dataStore->refreshing_group) return;
NekoGui::dataStore->refreshing_group = true;
auto group = NekoGui::profileManager->GetGroup(gid);
if (group == nullptr) {
MessageBoxWarning(tr("Error"), QString("No such group: %1").arg(gid));
NekoGui::dataStore->refreshing_group = false;
return;
}
if (NekoGui::dataStore->current_group != gid) {
NekoGui::dataStore->current_group = gid;
NekoGui::dataStore->Save();
}
ui->tabWidget->widget(groupId2TabIndex(gid))->layout()->addWidget(ui->proxyListTable);
// 列宽是否可调
if (group->manually_column_width) {
for (int i = 0; i <= 4; i++) {
ui->proxyListTable->horizontalHeader()->setSectionResizeMode(i, QHeaderView::Interactive);
auto size = group->column_width.value(i);
if (size <= 0) size = ui->proxyListTable->horizontalHeader()->defaultSectionSize();
ui->proxyListTable->horizontalHeader()->resizeSection(i, size);
}
} else {
ui->proxyListTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
ui->proxyListTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
ui->proxyListTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch);
ui->proxyListTable->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents);
ui->proxyListTable->horizontalHeader()->setSectionResizeMode(4, QHeaderView::ResizeToContents);
}
// show proxies
GroupSortAction gsa;
gsa.scroll_to_started = true;
refresh_proxy_list_impl(-1, gsa);
NekoGui::dataStore->refreshing_group = false;
}
// callback
void MainWindow::dialog_message_impl(const QString &sender, const QString &info) {
// info
if (info.contains("UpdateIcon")) {
icon_status = -1;
refresh_status();
}
if (info.contains("UpdateDataStore")) {
auto suggestRestartProxy = NekoGui::dataStore->Save();
if (info.contains("RouteChanged")) {
suggestRestartProxy = true;
}
if (info.contains("NeedRestart")) {
suggestRestartProxy = false;
}
refresh_proxy_list();
if (info.contains("VPNChanged") && NekoGui::dataStore->spmode_vpn) {
MessageBoxWarning(tr("Tun Settings changed"), tr("Restart Tun to take effect."));
}
if (suggestRestartProxy && NekoGui::dataStore->started_id >= 0 &&
QMessageBox::question(GetMessageBoxParent(), tr("Confirmation"), tr("Settings changed, restart proxy?")) == QMessageBox::StandardButton::Yes) {
neko_start(NekoGui::dataStore->started_id);
}
refresh_status();
}
if (info.contains("NeedRestart")) {
auto n = QMessageBox::warning(GetMessageBoxParent(), tr("Settings changed"), tr("Restart the program to take effect."), QMessageBox::Yes | QMessageBox::No);
if (n == QMessageBox::Yes) {
this->exit_reason = 2;
on_menu_exit_triggered();
}
}
//
if (info == "RestartProgram") {
this->exit_reason = 2;
on_menu_exit_triggered();
} else if (info == "Raise") {
ActivateWindow(this);
} else if (info == "ClearConnectionList") {
refresh_connection_list({});
}
// sender
if (sender == Dialog_DialogEditProfile) {
auto msg = info.split(",");
if (msg.contains("accept")) {
refresh_proxy_list();
if (msg.contains("restart")) {
if (QMessageBox::question(GetMessageBoxParent(), tr("Confirmation"), tr("Settings changed, restart proxy?")) == QMessageBox::StandardButton::Yes) {
neko_start(NekoGui::dataStore->started_id);
}
}
}
} else if (sender == Dialog_DialogManageGroups) {
if (info.startsWith("refresh")) {
this->refresh_groups();
}
} else if (sender == "SubUpdater") {
if (info.startsWith("finish")) {
refresh_proxy_list();
if (!info.contains("dingyue")) {
show_log_impl(tr("Imported %1 profile(s)").arg(NekoGui::dataStore->imported_count));
}
} else if (info == "NewGroup") {
refresh_groups();
}
} else if (sender == "ExternalProcess") {
if (info == "Crashed") {
neko_stop();
} else if (info == "CoreCrashed") {
neko_stop(true);
} else if (info.startsWith("CoreStarted")) {
neko_start(info.split(",")[1].toInt());
}
}
}
// top bar & tray menu
inline bool dialog_is_using = false;
#define USE_DIALOG(a) \
if (dialog_is_using) return; \
dialog_is_using = true; \
auto dialog = new a(this); \
connect(dialog, &QDialog::finished, this, [=] { \
dialog->deleteLater(); \
dialog_is_using = false; \
}); \
dialog->show();
void MainWindow::on_menu_basic_settings_triggered() {
USE_DIALOG(DialogBasicSettings)
}
void MainWindow::on_menu_manage_groups_triggered() {
USE_DIALOG(DialogManageGroups)
}
void MainWindow::on_menu_routing_settings_triggered() {
USE_DIALOG(DialogManageRoutes)
}
void MainWindow::on_menu_vpn_settings_triggered() {
USE_DIALOG(DialogVPNSettings)
}
void MainWindow::on_menu_hotkey_settings_triggered() {
USE_DIALOG(DialogHotkey)
}
void MainWindow::on_commitDataRequest() {
qDebug() << "Start of data save";
//
if (!isMaximized()) {
auto olds = NekoGui::dataStore->mw_size;
auto news = QString("%1x%2").arg(size().width()).arg(size().height());
if (olds != news) {
NekoGui::dataStore->mw_size = news;
}
}
//
NekoGui::dataStore->splitter_state = ui->splitter->saveState().toBase64();
//
auto last_id = NekoGui::dataStore->started_id;
if (NekoGui::dataStore->remember_enable && last_id >= 0) {
NekoGui::dataStore->remember_id = last_id;
}
//
NekoGui::dataStore->Save();
NekoGui::profileManager->SaveManager();
qDebug() << "End of data save";
}
void MainWindow::on_menu_exit_triggered() {
if (mu_exit.tryLock()) {
NekoGui::dataStore->prepare_exit = true;
//
neko_set_spmode_system_proxy(false, false);
neko_set_spmode_vpn(false, false);
if (NekoGui::dataStore->spmode_vpn) {
mu_exit.unlock(); // retry
return;
}
RegisterHotkey(true);
//
on_commitDataRequest();
//
NekoGui::dataStore->save_control_no_save = true; // don't change datastore after this line
neko_stop(false, true);
//
hide();
runOnNewThread([=] {
sem_stopped.acquire();
stop_core_daemon();
runOnUiThread([=] {
on_menu_exit_triggered(); // continue exit progress
});
});
return;
}
//
MF_release_runguard();
if (exit_reason == 1) {
QDir::setCurrent(QApplication::applicationDirPath());
QProcess::startDetached("./updater", QStringList{});
} else if (exit_reason == 2 || exit_reason == 3) {
QDir::setCurrent(QApplication::applicationDirPath());
auto arguments = NekoGui::dataStore->argv;
if (arguments.length() > 0) {
arguments.removeFirst();
arguments.removeAll("-tray");
arguments.removeAll("-flag_restart_tun_on");
arguments.removeAll("-flag_reorder");
}
auto isLauncher = qEnvironmentVariable("NKR_FROM_LAUNCHER") == "1";
if (isLauncher) arguments.prepend("--");
auto program = isLauncher ? "./launcher" : QApplication::applicationFilePath();
if (exit_reason == 3) {
// Tun restart as admin
arguments << "-flag_restart_tun_on";
#ifdef Q_OS_WIN
WinCommander::runProcessElevated(program, arguments, "", WinCommander::SW_NORMAL, false);
#else
QProcess::startDetached(program, arguments);
#endif
} else {
QProcess::startDetached(program, arguments);
}
}
tray->hide();
QCoreApplication::quit();
}
#define neko_set_spmode_FAILED \
refresh_status(); \
return;
void MainWindow::neko_set_spmode_system_proxy(bool enable, bool save) {
if (enable != NekoGui::dataStore->spmode_system_proxy) {
if (enable) {
auto socks_port = NekoGui::dataStore->inbound_socks_port;
auto http_port = NekoGui::dataStore->inbound_socks_port;
SetSystemProxy(http_port, socks_port);
} else {
ClearSystemProxy();
}
}
if (save) {
NekoGui::dataStore->remember_spmode.removeAll("system_proxy");
if (enable && NekoGui::dataStore->remember_enable) {
NekoGui::dataStore->remember_spmode.append("system_proxy");
}
NekoGui::dataStore->Save();
}
NekoGui::dataStore->spmode_system_proxy = enable;
refresh_status();
}
void MainWindow::neko_set_spmode_vpn(bool enable, bool save) {
if (enable != NekoGui::dataStore->spmode_vpn) {
if (enable) {
if (NekoGui::dataStore->vpn_internal_tun) {
bool requestPermission = !NekoGui::IsAdmin();
if (requestPermission) {
#ifdef Q_OS_LINUX
if (!Linux_HavePkexec()) {
MessageBoxWarning(software_name, "Please install \"pkexec\" first.");
neko_set_spmode_FAILED
}
auto ret = Linux_Pkexec_SetCapString(NekoGui::FindNekoBoxCoreRealPath(), "cap_net_admin=ep");
if (ret == 0) {
this->exit_reason = 3;
on_menu_exit_triggered();
} else {
MessageBoxWarning(software_name, "Setcap for Tun mode failed.\n\n1. You may canceled the dialog.\n2. You may be using an incompatible environment like AppImage.");
if (QProcessEnvironment::systemEnvironment().contains("APPIMAGE")) {
MW_show_log("If you are using AppImage, it's impossible to start a Tun. Please use other package instead.");
}
}
#endif
#ifdef Q_OS_WIN
auto n = QMessageBox::warning(GetMessageBoxParent(), software_name, tr("Please run NekoBox as admin"), QMessageBox::Yes | QMessageBox::No);
if (n == QMessageBox::Yes) {
this->exit_reason = 3;
on_menu_exit_triggered();
}
#endif
neko_set_spmode_FAILED
}
} else {
if (NekoGui::dataStore->need_keep_vpn_off) {
MessageBoxWarning(software_name, tr("Current server is incompatible with Tun. Please stop the server first, enable Tun Mode, and then restart."));
neko_set_spmode_FAILED
}
if (!StartVPNProcess()) {
neko_set_spmode_FAILED
}
}
} else {
if (NekoGui::dataStore->vpn_internal_tun) {
// current core is sing-box
} else {
if (!StopVPNProcess()) {
neko_set_spmode_FAILED
}
}
}
}
if (save) {
NekoGui::dataStore->remember_spmode.removeAll("vpn");
if (enable && NekoGui::dataStore->remember_enable) {
NekoGui::dataStore->remember_spmode.append("vpn");
}
NekoGui::dataStore->Save();
}
NekoGui::dataStore->spmode_vpn = enable;
refresh_status();
if (NekoGui::dataStore->vpn_internal_tun && NekoGui::dataStore->started_id >= 0) neko_start(NekoGui::dataStore->started_id);
}
void MainWindow::refresh_status(const QString &traffic_update) {
auto refresh_speed_label = [=] {
if (traffic_update_cache == "") {
ui->label_speed->setText(QObject::tr("Proxy: %1\nDirect: %2").arg("", ""));
} else {
ui->label_speed->setText(traffic_update_cache);
}
};
// From TrafficLooper
if (!traffic_update.isEmpty()) {
traffic_update_cache = traffic_update;
if (traffic_update == "STOP") {
traffic_update_cache = "";
} else {
refresh_speed_label();
return;
}
}
refresh_speed_label();
// From UI
QString group_name;
if (running != nullptr) {
auto group = NekoGui::profileManager->GetGroup(running->gid);
if (group != nullptr) group_name = group->name;
}
if (last_test_time.addSecs(2) < QTime::currentTime()) {
auto txt = running == nullptr ? tr("Not Running")
: QString("[%1] %2").arg(group_name, running->bean->DisplayName()).left(30);
ui->label_running->setText(txt);
}
//
auto display_socks = DisplayAddress(NekoGui::dataStore->inbound_address, NekoGui::dataStore->inbound_socks_port);
auto inbound_txt = QString("Mixed: %1").arg(display_socks);
ui->label_inbound->setText(inbound_txt);
//
ui->checkBox_VPN->setChecked(NekoGui::dataStore->spmode_vpn);
ui->checkBox_SystemProxy->setChecked(NekoGui::dataStore->spmode_system_proxy);
if (select_mode) {
ui->label_running->setText(tr("Select") + " *");
ui->label_running->setToolTip(tr("Select mode, double-click or press Enter to select a profile, press ESC to exit."));
} else {
ui->label_running->setToolTip({});
}
auto make_title = [=](bool isTray) {
QStringList tt;
if (!isTray && NekoGui::IsAdmin()) tt << "[Admin]";
if (select_mode) tt << "[" + tr("Select") + "]";
if (!title_error.isEmpty()) tt << "[" + title_error + "]";
if (NekoGui::dataStore->spmode_vpn && !NekoGui::dataStore->spmode_system_proxy) tt << "[Tun]";
if (!NekoGui::dataStore->spmode_vpn && NekoGui::dataStore->spmode_system_proxy) tt << "[" + tr("System Proxy") + "]";
if (NekoGui::dataStore->spmode_vpn && NekoGui::dataStore->spmode_system_proxy) tt << "[Tun+" + tr("System Proxy") + "]";
tt << software_name;
if (!isTray) tt << "(" + QString(NKR_VERSION) + ")";
if (!NekoGui::dataStore->active_routing.isEmpty() && NekoGui::dataStore->active_routing != "Default") {
tt << "[" + NekoGui::dataStore->active_routing + "]";
}
if (running != nullptr) tt << running->bean->DisplayTypeAndName() + "@" + group_name;
return tt.join(isTray ? "\n" : " ");
};
auto icon_status_new = Icon::NONE;
if (running != nullptr) {
if (NekoGui::dataStore->spmode_vpn) {
icon_status_new = Icon::VPN;
} else if (NekoGui::dataStore->spmode_system_proxy) {
icon_status_new = Icon::SYSTEM_PROXY;
} else {
icon_status_new = Icon::RUNNING;
}
}
// refresh title & window icon
setWindowTitle(make_title(false));
if (icon_status_new != icon_status) QApplication::setWindowIcon(Icon::GetTrayIcon(Icon::NONE));
// refresh tray
if (tray != nullptr) {
tray->setToolTip(make_title(true));
if (icon_status_new != icon_status) tray->setIcon(Icon::GetTrayIcon(icon_status_new));
}
icon_status = icon_status_new;
}
// table显示
// refresh_groups -> show_group -> refresh_proxy_list
void MainWindow::refresh_groups() {
NekoGui::dataStore->refreshing_group_list = true;
// refresh group?
for (int i = ui->tabWidget->count() - 1; i > 0; i--) {
ui->tabWidget->removeTab(i);
}
int index = 0;
for (const auto &gid: NekoGui::profileManager->groupsTabOrder) {
auto group = NekoGui::profileManager->GetGroup(gid);
if (index == 0) {
ui->tabWidget->setTabText(0, group->name);
} else {
auto widget2 = new QWidget();
auto layout2 = new QVBoxLayout();
layout2->setContentsMargins(QMargins());
layout2->setSpacing(0);
widget2->setLayout(layout2);
ui->tabWidget->addTab(widget2, group->name);
}
ui->tabWidget->tabBar()->setTabData(index, gid);
index++;
}
// show after group changed
if (NekoGui::profileManager->CurrentGroup() == nullptr) {
NekoGui::dataStore->current_group = -1;
ui->tabWidget->setCurrentIndex(groupId2TabIndex(0));
show_group(NekoGui::profileManager->groupsTabOrder.count() > 0 ? NekoGui::profileManager->groupsTabOrder.first() : 0);
} else {
ui->tabWidget->setCurrentIndex(groupId2TabIndex(NekoGui::dataStore->current_group));
show_group(NekoGui::dataStore->current_group);
}
NekoGui::dataStore->refreshing_group_list = false;
}
void MainWindow::refresh_proxy_list(const int &id) {
refresh_proxy_list_impl(id, {});
}
void MainWindow::refresh_proxy_list_impl(const int &id, GroupSortAction groupSortAction) {
// id < 0 重绘
if (id < 0) {
// 清空数据
ui->proxyListTable->row2Id.clear();
ui->proxyListTable->setRowCount(0);
// 添加行
int row = -1;
for (const auto &[id, profile]: NekoGui::profileManager->profiles) {
if (NekoGui::dataStore->current_group != profile->gid) continue;
row++;
ui->proxyListTable->insertRow(row);
ui->proxyListTable->row2Id += id;
}
}
// 显示排序
if (id < 0) {
switch (groupSortAction.method) {
case GroupSortMethod::Raw: {
auto group = NekoGui::profileManager->CurrentGroup();
if (group == nullptr) return;
ui->proxyListTable->order = group->order;
break;
}
case GroupSortMethod::ById: {
// Clear Order
ui->proxyListTable->order.clear();
ui->proxyListTable->callback_save_order();
break;
}
case GroupSortMethod::ByAddress:
case GroupSortMethod::ByName:
case GroupSortMethod::ByLatency:
case GroupSortMethod::ByType: {
std::sort(ui->proxyListTable->order.begin(), ui->proxyListTable->order.end(),
[=](int a, int b) {
QString ms_a;
QString ms_b;
if (groupSortAction.method == GroupSortMethod::ByType) {
ms_a = NekoGui::profileManager->GetProfile(a)->bean->DisplayType();
ms_b = NekoGui::profileManager->GetProfile(b)->bean->DisplayType();
} else if (groupSortAction.method == GroupSortMethod::ByName) {
ms_a = NekoGui::profileManager->GetProfile(a)->bean->name;
ms_b = NekoGui::profileManager->GetProfile(b)->bean->name;
} else if (groupSortAction.method == GroupSortMethod::ByAddress) {
ms_a = NekoGui::profileManager->GetProfile(a)->bean->DisplayAddress();
ms_b = NekoGui::profileManager->GetProfile(b)->bean->DisplayAddress();
} else if (groupSortAction.method == GroupSortMethod::ByLatency) {
ms_a = NekoGui::profileManager->GetProfile(a)->full_test_report;
ms_b = NekoGui::profileManager->GetProfile(b)->full_test_report;
}
auto get_latency_for_sort = [](int id) {
auto i = NekoGui::profileManager->GetProfile(id)->latency;
if (i == 0) i = 100000;
if (i < 0) i = 99999;
return i;
};
if (groupSortAction.descending) {
if (groupSortAction.method == GroupSortMethod::ByLatency) {
if (ms_a.isEmpty() && ms_b.isEmpty()) {
// compare latency if full_test_report is empty
return get_latency_for_sort(a) > get_latency_for_sort(b);
}
}
return ms_a > ms_b;
} else {
if (groupSortAction.method == GroupSortMethod::ByLatency) {
auto int_a = NekoGui::profileManager->GetProfile(a)->latency;
auto int_b = NekoGui::profileManager->GetProfile(b)->latency;
if (ms_a.isEmpty() && ms_b.isEmpty()) {
// compare latency if full_test_report is empty
return get_latency_for_sort(a) < get_latency_for_sort(b);
}
}
return ms_a < ms_b;
}
});
break;
}
}
ui->proxyListTable->update_order(groupSortAction.save_sort);
}
// refresh data
refresh_proxy_list_impl_refresh_data(id);
}
void MainWindow::refresh_proxy_list_impl_refresh_data(const int &id) {
// 绘制或更新item(s)
for (int row = 0; row < ui->proxyListTable->rowCount(); row++) {
auto profileId = ui->proxyListTable->row2Id[row];
if (id >= 0 && profileId != id) continue; // refresh ONE item
auto profile = NekoGui::profileManager->GetProfile(profileId);
if (profile == nullptr) continue;
auto isRunning = profileId == NekoGui::dataStore->started_id;
auto f0 = std::make_unique<QTableWidgetItem>();
f0->setData(114514, profileId);
// Check state
auto check = f0->clone();
check->setText(isRunning ? "✓" : Int2String(row + 1));
ui->proxyListTable->setVerticalHeaderItem(row, check);
// C0: Type
auto f = f0->clone();
f->setText(profile->bean->DisplayType());
if (isRunning) f->setForeground(palette().link());
ui->proxyListTable->setItem(row, 0, f);
// C1: Address+Port
f = f0->clone();
f->setText(profile->bean->DisplayAddress());
if (isRunning) f->setForeground(palette().link());
ui->proxyListTable->setItem(row, 1, f);
// C2: Name
f = f0->clone();
f->setText(profile->bean->name);
if (isRunning) f->setForeground(palette().link());
ui->proxyListTable->setItem(row, 2, f);
// C3: Test Result
f = f0->clone();
if (profile->full_test_report.isEmpty()) {
auto color = profile->DisplayLatencyColor();
if (color.isValid()) f->setForeground(color);
f->setText(profile->DisplayLatency());
} else {
f->setText(profile->full_test_report);
}
ui->proxyListTable->setItem(row, 3, f);
// C4: Traffic
f = f0->clone();
f->setText(profile->traffic_data->DisplayTraffic());
ui->proxyListTable->setItem(row, 4, f);
}
}
// table菜单相关
void MainWindow::on_proxyListTable_itemDoubleClicked(QTableWidgetItem *item) {
auto id = item->data(114514).toInt();
if (select_mode) {
emit profile_selected(id);
select_mode = false;
refresh_status();
return;
}
auto dialog = new DialogEditProfile("", id, this);
connect(dialog, &QDialog::finished, dialog, &QDialog::deleteLater);
}
void MainWindow::on_menu_add_from_input_triggered() {
auto dialog = new DialogEditProfile("socks", NekoGui::dataStore->current_group, this);
connect(dialog, &QDialog::finished, dialog, &QDialog::deleteLater);
}
void MainWindow::on_menu_add_from_clipboard_triggered() {
auto clipboard = QApplication::clipboard()->text();
NekoGui_sub::groupUpdater->AsyncUpdate(clipboard);
}
void MainWindow::on_menu_clone_triggered() {
auto ents = get_now_selected_list();
if (ents.isEmpty()) return;
auto btn = QMessageBox::question(this, tr("Clone"), tr("Clone %1 item(s)").arg(ents.count()));
if (btn != QMessageBox::Yes) return;
QStringList sls;
for (const auto &ent: ents) {
sls << ent->bean->ToNekorayShareLink(ent->type);
}
NekoGui_sub::groupUpdater->AsyncUpdate(sls.join("\n"));
}
void MainWindow::on_menu_move_triggered() {
auto ents = get_now_selected_list();
if (ents.isEmpty()) return;
auto items = QStringList{};
for (auto gid: NekoGui::profileManager->groupsTabOrder) {
auto group = NekoGui::profileManager->GetGroup(gid);
if (group == nullptr) continue;
items += Int2String(gid) + " " + group->name;
}
bool ok;
auto a = QInputDialog::getItem(nullptr,
tr("Move"),
tr("Move %1 item(s)").arg(ents.count()),
items, 0, false, &ok);
if (!ok) return;
auto gid = SubStrBefore(a, " ").toInt();
for (const auto &ent: ents) {
NekoGui::profileManager->MoveProfile(ent, gid);
}
refresh_proxy_list();
}
void MainWindow::on_menu_delete_triggered() {
auto ents = get_now_selected_list();
if (ents.count() == 0) return;
if (QMessageBox::question(this, tr("Confirmation"), QString(tr("Remove %1 item(s) ?")).arg(ents.count())) ==
QMessageBox::StandardButton::Yes) {
for (const auto &ent: ents) {
NekoGui::profileManager->DeleteProfile(ent->id);
}
refresh_proxy_list();
}
}
void MainWindow::on_menu_reset_traffic_triggered() {
auto ents = get_now_selected_list();
if (ents.count() == 0) return;
for (const auto &ent: ents) {
ent->traffic_data->Reset();
ent->Save();
refresh_proxy_list(ent->id);
}
}
void MainWindow::on_menu_profile_debug_info_triggered() {
auto ents = get_now_selected_list();
if (ents.count() != 1) return;
auto btn = QMessageBox::information(this, software_name, ents.first()->ToJsonBytes(), "OK", "Edit", "Reload", 0, 0);
if (btn == 1) {
QDesktopServices::openUrl(QUrl::fromLocalFile(QFileInfo(QString("profiles/%1.json").arg(ents.first()->id)).absoluteFilePath()));
} else if (btn == 2) {
NekoGui::dataStore->Load();
NekoGui::profileManager->LoadManager();
refresh_proxy_list();
}
}
void MainWindow::on_menu_copy_links_triggered() {
if (ui->masterLogBrowser->hasFocus()) {
ui->masterLogBrowser->copy();
return;
}
auto ents = get_now_selected_list();
QStringList links;
for (const auto &ent: ents) {
links += ent->bean->ToShareLink();
}
if (links.length() == 0) return;
QApplication::clipboard()->setText(links.join("\n"));
show_log_impl(tr("Copied %1 item(s)").arg(links.length()));
}
void MainWindow::on_menu_copy_links_nkr_triggered() {
auto ents = get_now_selected_list();
QStringList links;
for (const auto &ent: ents) {
links += ent->bean->ToNekorayShareLink(ent->type);
}
if (links.length() == 0) return;
QApplication::clipboard()->setText(links.join("\n"));
show_log_impl(tr("Copied %1 item(s)").arg(links.length()));
}
void MainWindow::on_menu_export_config_triggered() {
auto ents = get_now_selected_list();
if (ents.count() != 1) return;
auto ent = ents.first();
if (ent->bean->DisplayCoreType() != software_core_name) return;
auto result = BuildConfig(ent, false, true);
QString config_core = QJsonObject2QString(result->coreConfig, true);
QApplication::clipboard()->setText(config_core);
QMessageBox msg(QMessageBox::Information, tr("Config copied"), config_core);
msg.addButton("Copy core config", QMessageBox::YesRole);
msg.addButton("Copy test config", QMessageBox::NoRole);
msg.addButton(QMessageBox::Ok);
msg.setEscapeButton(QMessageBox::Ok);
msg.setDefaultButton(QMessageBox::Ok);
auto ret = msg.exec();
if (ret == 2) {
result = BuildConfig(ent, false, false);
config_core = QJsonObject2QString(result->coreConfig, false);
QApplication::clipboard()->setText(config_core);
} else if (ret == 3) {
result = BuildConfig(ent, true, false);
config_core = QJsonObject2QString(result->coreConfig, false);
QApplication::clipboard()->setText(config_core);
}
}
void MainWindow::display_qr_link(bool nkrFormat) {
auto ents = get_now_selected_list();
if (ents.count() != 1) return;
class W : public QDialog {
public:
QLabel *l = nullptr;
QCheckBox *cb = nullptr;
//
QPlainTextEdit *l2 = nullptr;
QImage im;
//
QString link;
QString link_nk;
void show_qr(const QSize &size) const {
auto side = size.height() - 20 - l2->size().height() - cb->size().height();
l->setPixmap(QPixmap::fromImage(im.scaled(side, side, Qt::KeepAspectRatio, Qt::FastTransformation),
Qt::MonoOnly));
l->resize(side, side);
}
void refresh(bool is_nk) {
auto link_display = is_nk ? link_nk : link;
l2->setPlainText(link_display);
constexpr qint32 qr_padding = 2;
//
try {
qrcodegen::QrCode qr = qrcodegen::QrCode::encodeText(link_display.toUtf8().data(), qrcodegen::QrCode::Ecc::MEDIUM);
qint32 sz = qr.getSize();
im = QImage(sz + qr_padding * 2, sz + qr_padding * 2, QImage::Format_RGB32);
QRgb black = qRgb(0, 0, 0);
QRgb white = qRgb(255, 255, 255);
im.fill(white);
for (int y = 0; y < sz; y++)
for (int x = 0; x < sz; x++)
if (qr.getModule(x, y))
im.setPixel(x + qr_padding, y + qr_padding, black);
show_qr(size());
} catch (const std::exception &ex) {
QMessageBox::warning(nullptr, "error", ex.what());
}
}
W(const QString &link_, const QString &link_nk_) {
link = link_;
link_nk = link_nk_;
//
setLayout(new QVBoxLayout);
setMinimumSize(256, 256);
QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
sizePolicy.setHeightForWidth(true);
setSizePolicy(sizePolicy);
//
l = new QLabel();
l->setMinimumSize(256, 256);
l->setMargin(6);
l->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
l->setScaledContents(true);
layout()->addWidget(l);
cb = new QCheckBox;
cb->setText("Neko Links");
layout()->addWidget(cb);
l2 = new QPlainTextEdit();
l2->setReadOnly(true);
layout()->addWidget(l2);
//
connect(cb, &QCheckBox::toggled, this, &W::refresh);
refresh(false);
}
void resizeEvent(QResizeEvent *resizeEvent) override {
show_qr(resizeEvent->size());
}
};
auto link = ents.first()->bean->ToShareLink();
auto link_nk = ents.first()->bean->ToNekorayShareLink(ents.first()->type);
auto w = new W(link, link_nk);
w->setWindowTitle(ents.first()->bean->DisplayTypeAndName());
w->exec();
w->deleteLater();
}
void MainWindow::on_menu_scan_qr_triggered() {
#ifndef NKR_NO_ZXING
using namespace ZXingQt;
hide();
QThread::sleep(1);
auto screen = QGuiApplication::primaryScreen();
auto geom = screen->geometry();
auto qpx = screen->grabWindow(0, geom.x(), geom.y(), geom.width(), geom.height());
show();
auto hints = DecodeHints()
.setFormats(BarcodeFormat::QRCode)
.setTryRotate(false)
.setBinarizer(Binarizer::FixedThreshold);
auto result = ReadBarcode(qpx.toImage(), hints);
const auto &text = result.text();
if (text.isEmpty()) {
MessageBoxInfo(software_name, tr("QR Code not found"));
} else {
show_log_impl("QR Code Result:\n" + text);
NekoGui_sub::groupUpdater->AsyncUpdate(text);
}
#endif
}
void MainWindow::on_menu_clear_test_result_triggered() {
for (const auto &profile: get_selected_or_group()) {
profile->latency = 0;
profile->full_test_report = "";
profile->Save();
}
refresh_proxy_list();
}
void MainWindow::on_menu_select_all_triggered() {
if (ui->masterLogBrowser->hasFocus()) {
ui->masterLogBrowser->selectAll();
return;
}
ui->proxyListTable->selectAll();
}
void MainWindow::on_menu_delete_repeat_triggered() {
QList<std::shared_ptr<NekoGui::ProxyEntity>> out;
QList<std::shared_ptr<NekoGui::ProxyEntity>> out_del;
NekoGui::ProfileFilter::Uniq(NekoGui::profileManager->CurrentGroup()->Profiles(), out, true, false);
NekoGui::ProfileFilter::OnlyInSrc_ByPointer(NekoGui::profileManager->CurrentGroup()->Profiles(), out, out_del);
int remove_display_count = 0;
QString remove_display;
for (const auto &ent: out_del) {
remove_display += ent->bean->DisplayTypeAndName() + "\n";
if (++remove_display_count == 20) {
remove_display += "...";
break;
}
}
if (out_del.length() > 0 &&
QMessageBox::question(this, tr("Confirmation"), tr("Remove %1 item(s) ?").arg(out_del.length()) + "\n" + remove_display) == QMessageBox::StandardButton::Yes) {
for (const auto &ent: out_del) {
NekoGui::profileManager->DeleteProfile(ent->id);
}
refresh_proxy_list();
}
}
bool mw_sub_updating = false;
void MainWindow::on_menu_update_subscription_triggered() {
auto group = NekoGui::profileManager->CurrentGroup();
if (group->url.isEmpty()) return;
if (mw_sub_updating) return;
mw_sub_updating = true;
NekoGui_sub::groupUpdater->AsyncUpdate(group->url, group->id, [&] { mw_sub_updating = false; });
}
void MainWindow::on_menu_remove_unavailable_triggered() {
QList<std::shared_ptr<NekoGui::ProxyEntity>> out_del;
for (const auto &[_, profile]: NekoGui::profileManager->profiles) {
if (NekoGui::dataStore->current_group != profile->gid) continue;
if (profile->latency < 0) out_del += profile;
}
int remove_display_count = 0;
QString remove_display;
for (const auto &ent: out_del) {
remove_display += ent->bean->DisplayTypeAndName() + "\n";
if (++remove_display_count == 20) {
remove_display += "...";
break;
}
}
if (out_del.length() > 0 &&
QMessageBox::question(this, tr("Confirmation"), tr("Remove %1 item(s) ?").arg(out_del.length()) + "\n" + remove_display) == QMessageBox::StandardButton::Yes) {
for (const auto &ent: out_del) {
NekoGui::profileManager->DeleteProfile(ent->id);
}
refresh_proxy_list();
}
}
void MainWindow::on_menu_resolve_domain_triggered() {
auto profiles = get_selected_or_group();
if (profiles.isEmpty()) return;
if (QMessageBox::question(this,
tr("Confirmation"),
tr("Resolving domain to IP, if support.")) != QMessageBox::StandardButton::Yes) {
return;
}
if (mw_sub_updating) return;
mw_sub_updating = true;
NekoGui::dataStore->resolve_count = profiles.count();
for (const auto &profile: profiles) {
profile->bean->ResolveDomainToIP([=] {
profile->Save();
if (--NekoGui::dataStore->resolve_count != 0) return;
refresh_proxy_list();
mw_sub_updating = false;
});
}
}
void MainWindow::on_proxyListTable_customContextMenuRequested(const QPoint &pos) {
ui->menu_server->popup(ui->proxyListTable->viewport()->mapToGlobal(pos)); // 弹出菜单
}
QList<std::shared_ptr<NekoGui::ProxyEntity>> MainWindow::get_now_selected_list() {
auto items = ui->proxyListTable->selectedItems();
QList<std::shared_ptr<NekoGui::ProxyEntity>> list;
for (auto item: items) {
auto id = item->data(114514).toInt();
auto ent = NekoGui::profileManager->GetProfile(id);
if (ent != nullptr && !list.contains(ent)) list += ent;
}
return list;
}
QList<std::shared_ptr<NekoGui::ProxyEntity>> MainWindow::get_selected_or_group() {
auto selected_or_group = ui->menu_server->property("selected_or_group").toInt();
QList<std::shared_ptr<NekoGui::ProxyEntity>> profiles;
if (selected_or_group > 0) {
profiles = get_now_selected_list();
if (profiles.isEmpty() && selected_or_group == 2) profiles = NekoGui::profileManager->CurrentGroup()->ProfilesWithOrder();
} else {
profiles = NekoGui::profileManager->CurrentGroup()->ProfilesWithOrder();
}
return profiles;
}
void MainWindow::keyPressEvent(QKeyEvent *event) {
switch (event->key()) {
case Qt::Key_Escape:
// take over by shortcut_esc
break;
case Qt::Key_Enter:
neko_start();
break;
default:
QMainWindow::keyPressEvent(event);
}
}
// Log
inline void FastAppendTextDocument(const QString &message, QTextDocument *doc) {
QTextCursor cursor(doc);
cursor.movePosition(QTextCursor::End);
cursor.beginEditBlock();
cursor.insertBlock();
cursor.insertText(message);
cursor.endEditBlock();
}
void MainWindow::show_log_impl(const QString &log) {
auto lines = SplitLines(log.trimmed());
if (lines.isEmpty()) return;
QStringList newLines;
auto log_ignore = NekoGui::dataStore->log_ignore;
for (const auto &line: lines) {
bool showThisLine = true;
for (const auto &str: log_ignore) {
if (line.contains(str)) {
showThisLine = false;
break;
}
}
if (showThisLine) newLines << line;
}
if (newLines.isEmpty()) return;
FastAppendTextDocument(newLines.join("\n"), qvLogDocument);
// qvLogDocument->setPlainText(qvLogDocument->toPlainText() + log);
// From https://gist.github.com/jemyzhang/7130092
auto block = qvLogDocument->begin();
while (block.isValid()) {
if (qvLogDocument->blockCount() > NekoGui::dataStore->max_log_line) {
QTextCursor cursor(block);
block = block.next();
cursor.select(QTextCursor::BlockUnderCursor);
cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
cursor.removeSelectedText();
continue;
}
break;
}
}
#define ADD_TO_CURRENT_ROUTE(a, b) \
NekoGui::dataStore->routing->a = (SplitLines(NekoGui::dataStore->routing->a) << (b)).join("\n"); \
NekoGui::dataStore->routing->Save();
void MainWindow::on_masterLogBrowser_customContextMenuRequested(const QPoint &pos) {
QMenu *menu = ui->masterLogBrowser->createStandardContextMenu();
auto sep = new QAction(this);
sep->setSeparator(true);
menu->addAction(sep);
auto action_add_ignore = new QAction(this);
action_add_ignore->setText(tr("Set ignore keyword"));
connect(action_add_ignore, &QAction::triggered, this, [=] {
auto list = NekoGui::dataStore->log_ignore;
auto newStr = ui->masterLogBrowser->textCursor().selectedText().trimmed();
if (!newStr.isEmpty()) list << newStr;
bool ok;
newStr = QInputDialog::getMultiLineText(GetMessageBoxParent(), tr("Set ignore keyword"), tr("Set the following keywords to ignore?\nSplit by line."), list.join("\n"), &ok);
if (ok) {
NekoGui::dataStore->log_ignore = SplitLines(newStr);
NekoGui::dataStore->Save();
}
});
menu->addAction(action_add_ignore);
auto action_add_route = new QAction(this);
action_add_route->setText(tr("Save as route"));
connect(action_add_route, &QAction::triggered, this, [=] {
auto newStr = ui->masterLogBrowser->textCursor().selectedText().trimmed();
if (newStr.isEmpty()) return;
//
bool ok;
newStr = QInputDialog::getText(GetMessageBoxParent(), tr("Save as route"), tr("Edit"), {}, newStr, &ok).trimmed();
if (!ok) return;
if (newStr.isEmpty()) return;
//
auto select = IsIpAddress(newStr) ? 0 : 3;
QStringList items = {"proxyIP", "bypassIP", "blockIP", "proxyDomain", "bypassDomain", "blockDomain"};
auto item = QInputDialog::getItem(GetMessageBoxParent(), tr("Save as route"),
tr("Save \"%1\" as a routing rule?").arg(newStr),
items, select, false, &ok);
if (ok) {
auto index = items.indexOf(item);
switch (index) {
case 0:
ADD_TO_CURRENT_ROUTE(proxy_ip, newStr);
break;
case 1:
ADD_TO_CURRENT_ROUTE(direct_ip, newStr);
break;
case 2:
ADD_TO_CURRENT_ROUTE(block_ip, newStr);
break;
case 3:
ADD_TO_CURRENT_ROUTE(proxy_domain, newStr);
break;
case 4:
ADD_TO_CURRENT_ROUTE(direct_domain, newStr);
break;
case 5:
ADD_TO_CURRENT_ROUTE(block_domain, newStr);
break;
default:
break;
}
MW_dialog_message("", "UpdateDataStore,RouteChanged");
}
});
menu->addAction(action_add_route);
auto action_clear = new QAction(this);
action_clear->setText(tr("Clear"));
connect(action_clear, &QAction::triggered, this, [=] {
qvLogDocument->clear();
ui->masterLogBrowser->clear();
});
menu->addAction(action_clear);
menu->exec(ui->masterLogBrowser->viewport()->mapToGlobal(pos)); // 弹出菜单
}
// eventFilter
bool MainWindow::eventFilter(QObject *obj, QEvent *event) {
if (event->type() == QEvent::MouseButtonPress) {
auto mouseEvent = dynamic_cast<QMouseEvent *>(event);
if (obj == ui->label_running && mouseEvent->button() == Qt::LeftButton && running != nullptr) {
speedtest_current();
return true;
} else if (obj == ui->label_inbound && mouseEvent->button() == Qt::LeftButton) {
on_menu_basic_settings_triggered();
return true;
}
} else if (event->type() == QEvent::MouseButtonDblClick) {
if (obj == ui->splitter) {
auto size = ui->splitter->size();
ui->splitter->setSizes({size.height() / 2, size.height() / 2});
}
}
return QMainWindow::eventFilter(obj, event);
}
// profile selector
void MainWindow::start_select_mode(QObject *context, const std::function<void(int)> &callback) {
select_mode = true;
connectOnce(this, &MainWindow::profile_selected, context, callback);
refresh_status();
}
// 连接列表
inline QJsonArray last_arr; // format is nekoray_connections_json
void MainWindow::refresh_connection_list(const QJsonArray &arr) {
if (last_arr == arr) {
return;
}
last_arr = arr;
if (NekoGui::dataStore->flag_debug) qDebug() << arr;
ui->tableWidget_conn->setRowCount(0);
int row = -1;
for (const auto &_item: arr) {
auto item = _item.toObject();
if (NekoGui::dataStore->ignoreConnTag.contains(item["Tag"].toString())) continue;
row++;
ui->tableWidget_conn->insertRow(row);
auto f0 = std::make_unique<QTableWidgetItem>();
f0->setData(114514, item["ID"].toInt());
// C0: Status
auto c0 = new QLabel;
auto start_t = item["Start"].toInt();
auto end_t = item["End"].toInt();
// icon
auto outboundTag = item["Tag"].toString();
if (outboundTag == "block") {
c0->setPixmap(Icon::GetMaterialIcon("cancel"));
} else {
if (end_t > 0) {
c0->setPixmap(Icon::GetMaterialIcon("history"));
} else {
c0->setPixmap(Icon::GetMaterialIcon("swap-vertical"));
}
}
c0->setAlignment(Qt::AlignCenter);
c0->setToolTip(tr("Start: %1\nEnd: %2").arg(DisplayTime(start_t), end_t > 0 ? DisplayTime(end_t) : ""));
ui->tableWidget_conn->setCellWidget(row, 0, c0);
// C1: Outbound
auto f = f0->clone();
f->setToolTip("");
f->setText(outboundTag);
ui->tableWidget_conn->setItem(row, 1, f);
// C2: Destination
f = f0->clone();
QString target1 = item["Dest"].toString();
QString target2 = item["RDest"].toString();
if (target2.isEmpty() || target1 == target2) {
target2 = "";
}
f->setText("[" + target1 + "] " + target2);
ui->tableWidget_conn->setItem(row, 2, f);
}
}
// Hotkey
#ifndef NKR_NO_QHOTKEY
#include <QHotkey>
inline QList<std::shared_ptr<QHotkey>> RegisteredHotkey;
void MainWindow::RegisterHotkey(bool unregister) {
while (!RegisteredHotkey.isEmpty()) {
auto hk = RegisteredHotkey.takeFirst();
hk->deleteLater();
}
if (unregister) return;
QStringList regstr{
NekoGui::dataStore->hotkey_mainwindow,
NekoGui::dataStore->hotkey_group,
NekoGui::dataStore->hotkey_route,
NekoGui::dataStore->hotkey_system_proxy_menu,
};
for (const auto &key: regstr) {
if (key.isEmpty()) continue;
if (regstr.count(key) > 1) return; // Conflict hotkey
}
for (const auto &key: regstr) {
QKeySequence k(key);
if (k.isEmpty()) continue;
auto hk = std::make_shared<QHotkey>(k, true);
if (hk->isRegistered()) {
RegisteredHotkey += hk;
connect(hk.get(), &QHotkey::activated, this, [=] { HotkeyEvent(key); });
} else {
hk->deleteLater();
}
}
}
void MainWindow::HotkeyEvent(const QString &key) {
if (key.isEmpty()) return;
runOnUiThread([=] {
if (key == NekoGui::dataStore->hotkey_mainwindow) {
tray->activated(QSystemTrayIcon::ActivationReason::Trigger);
} else if (key == NekoGui::dataStore->hotkey_group) {
on_menu_manage_groups_triggered();
} else if (key == NekoGui::dataStore->hotkey_route) {
on_menu_routing_settings_triggered();
} else if (key == NekoGui::dataStore->hotkey_system_proxy_menu) {
ui->menu_spmode->popup(QCursor::pos());
}
});
}
#else
void MainWindow::RegisterHotkey(bool unregister) {}
void MainWindow::HotkeyEvent(const QString &key) {}
#endif
// VPN Launcher
bool MainWindow::StartVPNProcess() {
//
if (vpn_pid != 0) {
return true;
}
//
auto configPath = NekoGui::WriteVPNSingBoxConfig();
auto scriptPath = NekoGui::WriteVPNLinuxScript(configPath);
//
#ifdef Q_OS_WIN
runOnNewThread([=] {
vpn_pid = 1; // TODO get pid?
WinCommander::runProcessElevated(QApplication::applicationDirPath() + "/nekobox_core.exe",
{"--disable-color", "run", "-c", configPath}, "",
NekoGui::dataStore->vpn_hide_console ? WinCommander::SW_HIDE : WinCommander::SW_SHOWMINIMIZED); // blocking
vpn_pid = 0;
runOnUiThread([=] { neko_set_spmode_vpn(false); });
});
#else
//
auto vpn_process = new QProcess;
QProcess::connect(vpn_process, &QProcess::stateChanged, this, [=](QProcess::ProcessState state) {
if (state == QProcess::NotRunning) {
vpn_pid = 0;
vpn_process->deleteLater();
GetMainWindow()->neko_set_spmode_vpn(false);
}
});
//
vpn_process->setProcessChannelMode(QProcess::ForwardedChannels);
#ifdef Q_OS_MACOS
vpn_process->start("osascript", {"-e", QString("do shell script \"%1\" with administrator privileges")
.arg("bash " + scriptPath)});
#else
vpn_process->start("pkexec", {"bash", scriptPath});
#endif
vpn_process->waitForStarted();
vpn_pid = vpn_process->processId(); // actually it's pkexec or bash PID
#endif
return true;
}
bool MainWindow::StopVPNProcess(bool unconditional) {
if (unconditional || vpn_pid != 0) {
bool ok;
core_process->processId();
#ifdef Q_OS_WIN
auto ret = WinCommander::runProcessElevated("taskkill", {"/IM", "nekobox_core.exe",
"/FI",
"PID ne " + Int2String(core_process->processId())});
ok = ret == 0;
#else
QProcess p;
#ifdef Q_OS_MACOS
p.start("osascript", {"-e", QString("do shell script \"%1\" with administrator privileges")
.arg("pkill -2 -U 0 nekobox_core")});
#else
if (unconditional) {
p.start("pkexec", {"killall", "-2", "nekobox_core"});
} else {
p.start("pkexec", {"pkill", "-2", "-P", Int2String(vpn_pid)});
}
#endif
p.waitForFinished();
ok = p.exitCode() == 0;
#endif
if (!unconditional) {
ok ? vpn_pid = 0 : MessageBoxWarning(tr("Error"), tr("Failed to stop Tun process"));
}
return ok;
}
return true;
}
| 70,639
|
C++
|
.cpp
| 1,659
| 33.432188
| 187
| 0.588226
|
MatsuriDayo/nekoray
| 12,410
| 1,179
| 73
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.