diff --git a/.gitignore b/.gitignore index ad4d030..077294b 100644 --- a/.gitignore +++ b/.gitignore @@ -3,11 +3,10 @@ ################################################################################ /.vs -/NetTunnelApp/bin -/NetTunnelApp/obj/ -/NetTunnelSDK/x64/ +bin/ +obj/ +x64/ /x64/ -/TestNetTunnelSDK/x64/Debug +Debug/ /packages/System.Buffers.4.5.1 -/Installer/Debug -/InstallTunnelSDK/Debug +/packages/DllExport.1.6.4 diff --git a/InstallTunnelSDK/InstallTunnelSDK.vdproj b/InstallTunnelSDK/InstallTunnelSDK.vdproj index 040ab4c..947da65 100644 --- a/InstallTunnelSDK/InstallTunnelSDK.vdproj +++ b/InstallTunnelSDK/InstallTunnelSDK.vdproj @@ -99,6 +99,12 @@ } "Entry" { + "MsmKey" = "8:_6A1A279D341B4A5D87C6D56C726E2979" + "OwnerKey" = "8:_UNDEFINED" + "MsmSig" = "8:_UNDEFINED" + } + "Entry" + { "MsmKey" = "8:_6A8B2CA20D527217332BB0170E559DB9" "OwnerKey" = "8:_00EB5BF3E5624995855CCF580A8AD1D5" "MsmSig" = "8:_UNDEFINED" @@ -184,12 +190,6 @@ "Entry" { "MsmKey" = "8:_UNDEFINED" - "OwnerKey" = "8:_513E5CF8D0F56603CEA37562D0DCB474" - "MsmSig" = "8:_UNDEFINED" - } - "Entry" - { - "MsmKey" = "8:_UNDEFINED" "OwnerKey" = "8:_10E071CF096B417C925C5E27E36CE39A" "MsmSig" = "8:_UNDEFINED" } @@ -223,6 +223,12 @@ "OwnerKey" = "8:_061110FCF275ABD7AB2CF878EE47397D" "MsmSig" = "8:_UNDEFINED" } + "Entry" + { + "MsmKey" = "8:_UNDEFINED" + "OwnerKey" = "8:_513E5CF8D0F56603CEA37562D0DCB474" + "MsmSig" = "8:_UNDEFINED" + } } "Configurations" { @@ -241,6 +247,22 @@ "PrivateKeyFile" = "8:" "TimeStampServer" = "8:" "InstallerBootstrapper" = "3:2" + "BootstrapperCfg:{63ACBE69-63AA-4F98-B2B6-99F9E24495F2}" + { + "Enabled" = "11:TRUE" + "PromptEnabled" = "11:TRUE" + "PrerequisitesLocation" = "2:1" + "Url" = "8:" + "ComponentsUrl" = "8:" + "Items" + { + "{EDC2488A-8267-493A-A98E-7D9C3B36CDF3}:.NETFramework,Version=v4.7.2" + { + "Name" = "8:Microsoft .NET Framework 4.7.2 (x86 and x64)" + "ProductCode" = "8:.NETFramework,Version=v4.7.2" + } + } + } } "Release" { @@ -257,6 +279,14 @@ "PrivateKeyFile" = "8:" "TimeStampServer" = "8:" "InstallerBootstrapper" = "3:2" + "BootstrapperCfg:{63ACBE69-63AA-4F98-B2B6-99F9E24495F2}" + { + "Enabled" = "11:TRUE" + "PromptEnabled" = "11:TRUE" + "PrerequisitesLocation" = "2:1" + "Url" = "8:" + "ComponentsUrl" = "8:" + } } } "Deployable" @@ -459,6 +489,26 @@ "IsDependency" = "11:TRUE" "IsolateTo" = "8:" } + "{1FB2D0AE-D3B9-43D4-B9DD-F88EC61E35DE}:_6A1A279D341B4A5D87C6D56C726E2979" + { + "SourcePath" = "8:..\\NetTunnelSDK\\resource\\iconsTray.ico" + "TargetName" = "8:iconsTray.ico" + "Tag" = "8:" + "Folder" = "8:_A69AEF7ED77C4BB28FA87F3D7B5FF39A" + "Condition" = "8:" + "Transitive" = "11:FALSE" + "Vital" = "11:TRUE" + "ReadOnly" = "11:FALSE" + "Hidden" = "11:FALSE" + "System" = "11:FALSE" + "Permanent" = "11:FALSE" + "SharedLegacy" = "11:FALSE" + "PackageAs" = "3:1" + "Register" = "3:1" + "Exclude" = "11:FALSE" + "IsDependency" = "11:FALSE" + "IsolateTo" = "8:" + } "{1FB2D0AE-D3B9-43D4-B9DD-F88EC61E35DE}:_6A8B2CA20D527217332BB0170E559DB9" { "SourcePath" = "8:ucrtbased.dll" @@ -515,7 +565,7 @@ "SharedLegacy" = "11:FALSE" "PackageAs" = "3:1" "Register" = "3:1" - "Exclude" = "11:FALSE" + "Exclude" = "11:TRUE" "IsDependency" = "11:TRUE" "IsolateTo" = "8:" } @@ -535,7 +585,7 @@ "SharedLegacy" = "11:FALSE" "PackageAs" = "3:1" "Register" = "3:1" - "Exclude" = "11:FALSE" + "Exclude" = "11:TRUE" "IsDependency" = "11:TRUE" "IsolateTo" = "8:" } @@ -689,7 +739,7 @@ "Name" = "8:Microsoft Visual Studio" "ProductName" = "8:SCC" "ProductCode" = "8:{FC04A2D1-FDD4-485A-88CC-67543D0B07FC}" - "PackageCode" = "8:{18F34BAE-0E72-485B-A6EB-9A62761CD03B}" + "PackageCode" = "8:{E72A3533-046D-464B-A2A8-C1326AC51F4F}" "UpgradeCode" = "8:{E4E3F1C5-78D9-4F56-AA5F-2C68C839E21E}" "AspNetVersion" = "8:" "RestartWWWService" = "11:FALSE" @@ -706,7 +756,7 @@ "Keywords" = "8:" "ARPCOMMENTS" = "8:" "ARPURLINFOABOUT" = "8:" - "ARPPRODUCTICON" = "8:" + "ARPPRODUCTICON" = "8:_6A1A279D341B4A5D87C6D56C726E2979" "ARPIconIndex" = "3:0" "SearchPath" = "8:" "UseSystemSearchPath" = "11:TRUE" diff --git a/NetTunnelApp/MainForm.Designer.cs b/NetTunnelApp/MainForm.Designer.cs index 2d91858..279b0bb 100644 --- a/NetTunnelApp/MainForm.Designer.cs +++ b/NetTunnelApp/MainForm.Designer.cs @@ -50,15 +50,18 @@ this.menuControlHeartStart = new System.Windows.Forms.ToolStripMenuItem(); this.menuControlHeartStop = new System.Windows.Forms.ToolStripMenuItem(); this.menuMainSet = new System.Windows.Forms.ToolStripMenuItem(); - this.menuSetModeShareNet = new System.Windows.Forms.ToolStripMenuItem(); - this.menuSetModeShareServer = new System.Windows.Forms.ToolStripMenuItem(); this.menuSetMode = new System.Windows.Forms.ToolStripMenuItem(); this.menuSetModeClient = new System.Windows.Forms.ToolStripMenuItem(); this.menuSetModeServer = new System.Windows.Forms.ToolStripMenuItem(); + this.menuSetModeShareNet = new System.Windows.Forms.ToolStripMenuItem(); + this.menuSetModeShareServer = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.menuSetVPN = new System.Windows.Forms.ToolStripMenuItem(); this.menuSetVPNPath = new System.Windows.Forms.ToolStripMenuItem(); this.menuSetExitToTray = new System.Windows.Forms.ToolStripMenuItem(); + this.menuSetShareMode = new System.Windows.Forms.ToolStripMenuItem(); + this.menuSetShareModeICS = new System.Windows.Forms.ToolStripMenuItem(); + this.menuSetShareModeNAT = new System.Windows.Forms.ToolStripMenuItem(); this.menuMainHelp = new System.Windows.Forms.ToolStripMenuItem(); this.statusMain = new System.Windows.Forms.StatusStrip(); this.tbMain = new System.Windows.Forms.ToolStrip(); @@ -71,9 +74,6 @@ this.trapMenuSysInterface = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.trapMenuExit = new System.Windows.Forms.ToolStripMenuItem(); - this.menuControlNetMode = new System.Windows.Forms.ToolStripMenuItem(); - this.menuControlNetModePrivate = new System.Windows.Forms.ToolStripMenuItem(); - this.menuControlNetModePublic = new System.Windows.Forms.ToolStripMenuItem(); this.menuMain.SuspendLayout(); this.trapMenuMain.SuspendLayout(); this.SuspendLayout(); @@ -157,8 +157,7 @@ this.menuControlSetCliParams, this.toolStripSeparator2, this.menuControlService, - this.menuControlHeart, - this.menuControlNetMode}); + this.menuControlHeart}); this.menuControl.Name = "menuControl"; this.menuControl.Size = new System.Drawing.Size(60, 21); this.menuControl.Text = "操作(&C)"; @@ -166,27 +165,27 @@ // menuControlRefInterface // this.menuControlRefInterface.Name = "menuControlRefInterface"; - this.menuControlRefInterface.Size = new System.Drawing.Size(192, 22); + this.menuControlRefInterface.Size = new System.Drawing.Size(180, 22); this.menuControlRefInterface.Text = "获取网络接口(&I)"; this.menuControlRefInterface.Click += new System.EventHandler(this.menuControlRefInterface_Click); // // menuControlEnv // this.menuControlEnv.Name = "menuControlEnv"; - this.menuControlEnv.Size = new System.Drawing.Size(192, 22); + this.menuControlEnv.Size = new System.Drawing.Size(180, 22); this.menuControlEnv.Text = "运行环境检测(&T)"; // // menuControlSetCliParams // this.menuControlSetCliParams.Name = "menuControlSetCliParams"; - this.menuControlSetCliParams.Size = new System.Drawing.Size(192, 22); + this.menuControlSetCliParams.Size = new System.Drawing.Size(180, 22); this.menuControlSetCliParams.Text = "设置隧道参数(&N)"; this.menuControlSetCliParams.Click += new System.EventHandler(this.menuControlSetCliParams_Click); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; - this.toolStripSeparator2.Size = new System.Drawing.Size(189, 6); + this.toolStripSeparator2.Size = new System.Drawing.Size(177, 6); // // menuControlService // @@ -194,7 +193,7 @@ this.menuControlSvrStart, this.menuControlSvrStop}); this.menuControlService.Name = "menuControlService"; - this.menuControlService.Size = new System.Drawing.Size(192, 22); + this.menuControlService.Size = new System.Drawing.Size(180, 22); this.menuControlService.Text = "隧道服务管理(&V)"; // // menuControlSvrStart @@ -217,20 +216,20 @@ this.menuControlHeartStart, this.menuControlHeartStop}); this.menuControlHeart.Name = "menuControlHeart"; - this.menuControlHeart.Size = new System.Drawing.Size(192, 22); + this.menuControlHeart.Size = new System.Drawing.Size(180, 22); this.menuControlHeart.Text = "心跳服务管理(&H)"; // // menuControlHeartStart // this.menuControlHeartStart.Name = "menuControlHeartStart"; - this.menuControlHeartStart.Size = new System.Drawing.Size(180, 22); + this.menuControlHeartStart.Size = new System.Drawing.Size(148, 22); this.menuControlHeartStart.Text = "启动心跳服务"; this.menuControlHeartStart.Click += new System.EventHandler(this.menuControlHeartStart_Click); // // menuControlHeartStop // this.menuControlHeartStop.Name = "menuControlHeartStop"; - this.menuControlHeartStop.Size = new System.Drawing.Size(180, 22); + this.menuControlHeartStop.Size = new System.Drawing.Size(148, 22); this.menuControlHeartStop.Text = "停止心跳服务"; this.menuControlHeartStop.Click += new System.EventHandler(this.menuControlHeartStop_Click); // @@ -242,23 +241,12 @@ this.menuSetModeShareServer, this.toolStripSeparator1, this.menuSetVPN, - this.menuSetExitToTray}); + this.menuSetExitToTray, + this.menuSetShareMode}); this.menuMainSet.Name = "menuMainSet"; this.menuMainSet.Size = new System.Drawing.Size(59, 21); this.menuMainSet.Text = "设置(&S)"; // - // menuSetModeShareNet - // - this.menuSetModeShareNet.Name = "menuSetModeShareNet"; - this.menuSetModeShareNet.Size = new System.Drawing.Size(180, 22); - this.menuSetModeShareNet.Text = "共享网络"; - // - // menuSetModeShareServer - // - this.menuSetModeShareServer.Name = "menuSetModeShareServer"; - this.menuSetModeShareServer.Size = new System.Drawing.Size(180, 22); - this.menuSetModeShareServer.Text = "云电脑服务器"; - // // menuSetMode // this.menuSetMode.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { @@ -284,6 +272,18 @@ this.menuSetModeServer.Text = "服务端"; this.menuSetModeServer.Click += new System.EventHandler(this.menuSetModeServer_Click); // + // menuSetModeShareNet + // + this.menuSetModeShareNet.Name = "menuSetModeShareNet"; + this.menuSetModeShareNet.Size = new System.Drawing.Size(180, 22); + this.menuSetModeShareNet.Text = "共享网络"; + // + // menuSetModeShareServer + // + this.menuSetModeShareServer.Name = "menuSetModeShareServer"; + this.menuSetModeShareServer.Size = new System.Drawing.Size(180, 22); + this.menuSetModeShareServer.Text = "云电脑服务器"; + // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; @@ -300,7 +300,7 @@ // menuSetVPNPath // this.menuSetVPNPath.Name = "menuSetVPNPath"; - this.menuSetVPNPath.Size = new System.Drawing.Size(180, 22); + this.menuSetVPNPath.Size = new System.Drawing.Size(124, 22); this.menuSetVPNPath.Text = "安装路径"; this.menuSetVPNPath.Click += new System.EventHandler(this.menuSetVPNPath_Click); // @@ -312,6 +312,31 @@ this.menuSetExitToTray.Size = new System.Drawing.Size(180, 22); this.menuSetExitToTray.Text = "退出时最小化(&M)"; // + // menuSetShareMode + // + this.menuSetShareMode.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.menuSetShareModeICS, + this.menuSetShareModeNAT}); + this.menuSetShareMode.Name = "menuSetShareMode"; + this.menuSetShareMode.Size = new System.Drawing.Size(180, 22); + this.menuSetShareMode.Text = "网络共享模式"; + // + // menuSetShareModeICS + // + this.menuSetShareModeICS.Checked = true; + this.menuSetShareModeICS.CheckState = System.Windows.Forms.CheckState.Checked; + this.menuSetShareModeICS.Name = "menuSetShareModeICS"; + this.menuSetShareModeICS.Size = new System.Drawing.Size(194, 22); + this.menuSetShareModeICS.Text = "Intelnet连接共享(ICS)"; + this.menuSetShareModeICS.Click += new System.EventHandler(this.menuSetShareModeICS_Click); + // + // menuSetShareModeNAT + // + this.menuSetShareModeNAT.Name = "menuSetShareModeNAT"; + this.menuSetShareModeNAT.Size = new System.Drawing.Size(194, 22); + this.menuSetShareModeNAT.Text = "网络地址转换(NAT)"; + this.menuSetShareModeNAT.Click += new System.EventHandler(this.menuSetShareModeNAT_Click); + // // menuMainHelp // this.menuMainHelp.Name = "menuMainHelp"; @@ -358,67 +383,46 @@ this.toolStripSeparator3, this.trapMenuExit}); this.trapMenuMain.Name = "trapMenuMain"; - this.trapMenuMain.Size = new System.Drawing.Size(181, 126); + this.trapMenuMain.Size = new System.Drawing.Size(137, 104); this.trapMenuMain.UseWaitCursor = true; // // trapMenuShowMainWnd // this.trapMenuShowMainWnd.Name = "trapMenuShowMainWnd"; - this.trapMenuShowMainWnd.Size = new System.Drawing.Size(180, 22); + this.trapMenuShowMainWnd.Size = new System.Drawing.Size(136, 22); this.trapMenuShowMainWnd.Text = "显示主界面"; this.trapMenuShowMainWnd.Click += new System.EventHandler(this.trapMenuShowMainWnd_Click); // // trapMenuHideMain // this.trapMenuHideMain.Name = "trapMenuHideMain"; - this.trapMenuHideMain.Size = new System.Drawing.Size(180, 22); + this.trapMenuHideMain.Size = new System.Drawing.Size(136, 22); this.trapMenuHideMain.Text = "隐藏主界面"; this.trapMenuHideMain.Click += new System.EventHandler(this.trapMenuHideMain_Click); // // toolStripSeparator5 // this.toolStripSeparator5.Name = "toolStripSeparator5"; - this.toolStripSeparator5.Size = new System.Drawing.Size(177, 6); + this.toolStripSeparator5.Size = new System.Drawing.Size(133, 6); // // trapMenuSysInterface // this.trapMenuSysInterface.Name = "trapMenuSysInterface"; - this.trapMenuSysInterface.Size = new System.Drawing.Size(180, 22); + this.trapMenuSysInterface.Size = new System.Drawing.Size(136, 22); this.trapMenuSysInterface.Text = "共享网络"; // // toolStripSeparator3 // this.toolStripSeparator3.Name = "toolStripSeparator3"; - this.toolStripSeparator3.Size = new System.Drawing.Size(177, 6); + this.toolStripSeparator3.Size = new System.Drawing.Size(133, 6); // // trapMenuExit // this.trapMenuExit.Name = "trapMenuExit"; - this.trapMenuExit.Size = new System.Drawing.Size(180, 22); + this.trapMenuExit.Size = new System.Drawing.Size(136, 22); this.trapMenuExit.Text = "退出程序"; this.trapMenuExit.Click += new System.EventHandler(this.trapMenuExit_Click); // - // menuControlNetMode - // - this.menuControlNetMode.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.menuControlNetModePrivate, - this.menuControlNetModePublic}); - this.menuControlNetMode.Name = "menuControlNetMode"; - this.menuControlNetMode.Size = new System.Drawing.Size(192, 22); - this.menuControlNetMode.Text = "隧道网络模式设置(&M)"; - // - // menuControlNetModePrivate - // - this.menuControlNetModePrivate.Name = "menuControlNetModePrivate"; - this.menuControlNetModePrivate.Size = new System.Drawing.Size(180, 22); - this.menuControlNetModePrivate.Text = "专用网络 (Private)"; - // - // menuControlNetModePublic - // - this.menuControlNetModePublic.Name = "menuControlNetModePublic"; - this.menuControlNetModePublic.Size = new System.Drawing.Size(180, 22); - this.menuControlNetModePublic.Text = "公共网络 (Public)"; - // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); @@ -486,9 +490,9 @@ private System.Windows.Forms.ToolStripMenuItem menuControlHeart; private System.Windows.Forms.ToolStripMenuItem menuControlHeartStart; private System.Windows.Forms.ToolStripMenuItem menuControlHeartStop; - private System.Windows.Forms.ToolStripMenuItem menuControlNetMode; - private System.Windows.Forms.ToolStripMenuItem menuControlNetModePrivate; - private System.Windows.Forms.ToolStripMenuItem menuControlNetModePublic; + private System.Windows.Forms.ToolStripMenuItem menuSetShareMode; + private System.Windows.Forms.ToolStripMenuItem menuSetShareModeICS; + private System.Windows.Forms.ToolStripMenuItem menuSetShareModeNAT; } } diff --git a/NetTunnelApp/MainForm.cs b/NetTunnelApp/MainForm.cs index 1f154df..dd57ef0 100644 --- a/NetTunnelApp/MainForm.cs +++ b/NetTunnelApp/MainForm.cs @@ -63,8 +63,8 @@ public partial class MainForm : Form var path = Environment.CurrentDirectory + "\\tunnelsdk_" + string.Format("{0:yyyyMMdd}", DateTime.Now) + ".log"; - NetTunnelLib.InitTunnelSDKLog(path, LogLevel.LOG_DEBUG); - NetTunnelLib.TunnelSDKInitEnv(Environment.CurrentDirectory, "http://xajhuang.com:9276", menuSetModeServer.Checked); + //NetTunnelLib.InitTunnelSDKLog(path, LogLevel.LOG_DEBUG); + NetTunnelLib.TunnelSDKInitEnv(Environment.CurrentDirectory, "http://xajhuang.com:9276", path, LogLevel.LOG_DEBUG, menuSetModeServer.Checked); GetCurrentNetCard(); @@ -227,32 +227,14 @@ public partial class MainForm : Form private void menuSetModeClient_Click(object sender, EventArgs e) { - var o = (ToolStripMenuItem)sender; - if (o.Checked) - { - o.Checked = false; - menuSetModeServer.Checked = true; - } - else - { - o.Checked = true; - menuSetModeServer.Checked = false; - } + menuSetModeClient.Checked = true; + menuSetModeServer.Checked = false; } private void menuSetModeServer_Click(object sender, EventArgs e) { - var o = (ToolStripMenuItem)sender; - if (o.Checked) - { - o.Checked = false; - menuSetModeClient.Checked = true; - } - else - { - o.Checked = true; - menuSetModeClient.Checked = false; - } + menuSetModeServer.Checked = true; + menuSetModeClient.Checked = false; } private void MainForm_SizeChanged(object sender, EventArgs e) @@ -375,7 +357,7 @@ public partial class MainForm : Form return; } - IPNetwork ipnetwork = IPNetwork.Parse(c?.IpAddr, c?.NetMask); + IPNetwork ipnetwork = IPNetwork.Parse("172.18.2.152", "255.255.255.0"); //IPNetwork cliNetwork = IPNetwork.Parse(_userConfig.cliAddress); //MessageBox.Show(ipnetwork.Value); @@ -462,4 +444,18 @@ public partial class MainForm : Form MessageBox.Show("Error: " + ret.ToString()); } } + + private void menuSetShareModeICS_Click(object sender, EventArgs e) + { + menuSetShareModeNAT.Checked = false; + menuSetShareModeICS.Checked = true; + NetTunnelLib.SetCurrentNetShareMode(NET_SHARE_MODE.ICS_SHARE_MODE); + } + + private void menuSetShareModeNAT_Click(object sender, EventArgs e) + { + menuSetShareModeICS.Checked = false; + menuSetShareModeNAT.Checked = true; + NetTunnelLib.SetCurrentNetShareMode(NET_SHARE_MODE.NAT_SHARE_MODE); + } } \ No newline at end of file diff --git a/NetTunnelApp/NetTunnelLib.cs b/NetTunnelApp/NetTunnelLib.cs index fa81701..b38e355 100644 --- a/NetTunnelApp/NetTunnelLib.cs +++ b/NetTunnelApp/NetTunnelLib.cs @@ -4,7 +4,7 @@ using System.Text; namespace NetTunnelApp; -public delegate void HeartCallBack(string msg, uint timeStamp); +public delegate void HeartCallBack(string msg, uint timeStamp); public enum ProtoCryptoType { @@ -26,6 +26,15 @@ public enum LogLevel LOG_OFF } +public enum NET_SHARE_MODE +{ + ///< Internet Share Mode(ICS) 模式 + ICS_SHARE_MODE = 0, + + ///< Net Address Translation(NAT) 模式 + NAT_SHARE_MODE = 1 +}; + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct VirtualMathineConfig { @@ -164,7 +173,8 @@ public struct WgCliConfig public class NetTunnelLib { [DllImport("NetTunnelSDK.dll", CallingConvention = CallingConvention.Cdecl)] - public static extern int TunnelSDKInitEnv(String workDir, String svrUrl, bool isWorkServer); + public static extern int TunnelSDKInitEnv(String workDir, String svrUrl, String pLogFile, LogLevel level, + bool isWorkServer); [DllImport("NetTunnelSDK.dll", CallingConvention = CallingConvention.Cdecl)] public static extern void TunnelSDKUnInit(); @@ -172,9 +182,6 @@ public class NetTunnelLib [DllImport("NetTunnelSDK.dll", CallingConvention = CallingConvention.Cdecl)] public static extern int SetProtocolEncryptType(ProtoCryptoType type, String pProKey); - [DllImport("NetTunnelSDK.dll", CallingConvention = CallingConvention.Cdecl)] - public static extern void InitTunnelSDKLog(String pProKey, LogLevel level); - [DllImport("NetTunnelSDK.dll", CallingConvention = CallingConvention.Cdecl)] public static extern int FindWireguardExe(StringBuilder lpString, int maxSize); @@ -210,7 +217,8 @@ public class NetTunnelLib public static extern int RemoteCtrlSvrCfgUserTunnel(int vmid, String cliNetwork); [DllImport("NetTunnelSDK.dll", CallingConvention = CallingConvention.Cdecl)] - public static extern int SetTunnelConfigure(String cliPrivateKey, String svrPublicKey, String svrNetwork, String cliNetwork, String svrAddr); + public static extern int SetTunnelConfigure(String cliPrivateKey, String svrPublicKey, String svrNetwork, + String cliNetwork, String svrAddr); [DllImport("NetTunnelSDK.dll", CallingConvention = CallingConvention.Cdecl)] public static extern int RemoteWireGuardControl(bool startOrStop); @@ -221,6 +229,12 @@ public class NetTunnelLib [DllImport("NetTunnelSDK.dll", CallingConvention = CallingConvention.Cdecl)] public static extern int RemoteHeartControl(bool startOrStop, HeartCallBack cb); + [DllImport("NetTunnelSDK.dll", CallingConvention = CallingConvention.Cdecl)] + public static extern NET_SHARE_MODE GetCurrentNetShareMode(); + + [DllImport("NetTunnelSDK.dll", CallingConvention = CallingConvention.Cdecl)] + public static extern void SetCurrentNetShareMode(NET_SHARE_MODE shareMode); + //[DllImport("NetTunnelSDK.dll", CallingConvention = CallingConvention.Cdecl)] //public static extern int RunPipeCmd(String pszCmd, StringBuilder pszResultBuffer, int dwResultBufferSize); } \ No newline at end of file diff --git a/NetTunnelSDK/ControlService.cpp b/NetTunnelSDK/ControlService.cpp index 6ad222e..12a8fc3 100644 --- a/NetTunnelSDK/ControlService.cpp +++ b/NetTunnelSDK/ControlService.cpp @@ -5,6 +5,8 @@ #include "globalcfg.h" #include "httplib.h" +#include "misc.h" +#include "network.h" #include "protocol.h" #include "usrerr.h" #include "user.h" @@ -47,7 +49,8 @@ static void HttpResponseError(httplib::Response &pRes, int errCode, const TCHAR } int CreateControlService(PUSER_SERVER_CONFIG pSvr) { - static WGSERVER_CONFIG g_curCliConfig = {}; + static TCHAR g_CliNetwork[MAX_IP_LEN] = {}; + static WGSERVER_CONFIG g_curCliConfig = {}; static std::mutex g_InterfaceMutex; DWORD dwStatus = 0; @@ -144,6 +147,10 @@ int CreateControlService(PUSER_SERVER_CONFIG pSvr) { // 当前服务状态和需要执行的操作不同 if (isSvrStart != reqData.msgContent.isStart) { if (reqData.msgContent.isStart) { + IP_INFO cliInfo; + IP_INFO tunnelInfo; + int retry = 3; + // 启动服务 ret = WireGuardInstallDefaultServerService(true); if (ret != ERR_SUCCESS) { @@ -153,6 +160,39 @@ int CreateControlService(PUSER_SERVER_CONFIG pSvr) { g_InterfaceMutex.unlock(); return; } + // 添加路由 + if ((ret = GetIpV4InfoFromCIDR(g_CliNetwork, &cliInfo)) != ERR_SUCCESS) { + // 返回启动服务失败 + SPDLOG_ERROR(TEXT("GetIpV4InfoFromCIDR ({1}) error: {0}"), ret, g_CliNetwork); + HttpResponseError(res, ret, TEXT("Parse IpAddress error.")); + g_InterfaceMutex.unlock(); + return; + } + + if ((ret = GetIpV4InfoFromCIDR(g_UserSvrCfg.svrAddress, &tunnelInfo)) != ERR_SUCCESS) { + // 返回启动服务失败 + SPDLOG_ERROR(TEXT("GetIpV4InfoFromCIDR ({1}) error: {0}"), ret, g_UserSvrCfg.svrAddress); + HttpResponseError(res, ret, TEXT("Parse tunnel ip address error.")); + g_InterfaceMutex.unlock(); + return; + } + + do { + ret = AddRouteTable(cliInfo.ip, cliInfo.netmask, tunnelInfo.ip); + Sleep(1000); + } while (ret != ERR_SUCCESS && retry--); + + if (ret != ERR_SUCCESS) { + // 返回启动服务失败 + SPDLOG_ERROR(TEXT("Add Route {1}/{2} gateway {3} error: {0}"), + ret, + cliInfo.ip, + cliInfo.netmask, + tunnelInfo.ip); + HttpResponseError(res, ret, TEXT("Parse tunnel ip address error.")); + g_InterfaceMutex.unlock(); + return; + } } else { if ((ret = WireGuardUnInstallServerService(GetGlobalCfgInfo()->userCfg.userName)) != ERR_SUCCESS) { // 返回停止服务失败 @@ -208,6 +248,7 @@ int CreateControlService(PUSER_SERVER_CONFIG pSvr) { StringCbCopy(g_curCliConfig.Address, 32, g_UserSvrCfg.svrAddress); StringCbCopy(g_curCliConfig.PrivateKey, 64, g_UserSvrCfg.svrPrivateKey); StringCbCopy(g_curCliConfig.CliPubKey, 64, reqData.msgContent.cliPublicKey.c_str()); + StringCbCopy(g_CliNetwork, MAX_IP_LEN, reqData.msgContent.cliNetwork.c_str()); StringCbPrintf(g_curCliConfig.AllowNet, 256, TEXT("%s,%s"), @@ -233,7 +274,7 @@ int CreateControlService(PUSER_SERVER_CONFIG pSvr) { // 设置路由表 #endif - // 返回当前隧道信息 + // 返回当前隧道信息 rsp.msgContent.errCode = ERR_SUCCESS; rsp.msgContent.errMessage = TEXT("OK"); rsp.msgContent.svrNetwork = g_UserSvrCfg.svrAddress; diff --git a/NetTunnelSDK/NetTunnelSDK.vcxproj b/NetTunnelSDK/NetTunnelSDK.vcxproj index 87aa23e..0461a18 100644 --- a/NetTunnelSDK/NetTunnelSDK.vcxproj +++ b/NetTunnelSDK/NetTunnelSDK.vcxproj @@ -119,6 +119,7 @@ Windows true false + .\WinDivert\x64;%(AdditionalLibraryDirectories) copy /y $(TargetDir)*.dll $(SolutionDir)\NetTunnelApp\bin\$(ConfigurationName)\ @@ -160,6 +161,7 @@ + @@ -177,6 +179,7 @@ + NotUsing diff --git a/NetTunnelSDK/NetTunnelSDK.vcxproj.filters b/NetTunnelSDK/NetTunnelSDK.vcxproj.filters index 60d6eb2..3487057 100644 --- a/NetTunnelSDK/NetTunnelSDK.vcxproj.filters +++ b/NetTunnelSDK/NetTunnelSDK.vcxproj.filters @@ -78,6 +78,9 @@ 头文件\http + + 头文件 + @@ -119,6 +122,9 @@ 源文件 + + 源文件\network + diff --git a/NetTunnelSDK/ProxyService.cpp b/NetTunnelSDK/ProxyService.cpp new file mode 100644 index 0000000..825c01d --- /dev/null +++ b/NetTunnelSDK/ProxyService.cpp @@ -0,0 +1,377 @@ +#include "pch.h" +#include "WinDivert/include/windivert.h" + +#include +#include +#include "globalcfg.h" +#include "usrerr.h" + +#include + +#pragma comment(lib, "WinDivert.lib") + +typedef enum { + PROXY_TCP = 1 << 0, + PROXY_UDP = 1 << 1, +} PROXY_PORTO_TYPE; + +typedef struct { + bool isRunning; + HANDLE proxyThread; + HANDLE proxyHandle; + bool isExitSvr; +} UDP_PROXY_CTX, *PUDP_PROXY_CTX; + +typedef struct { + SOCKET proxySock; + SOCKET reservePortSock; + SOCKET altSock; + bool isRunning; + UINT16 proxyPort; + UINT16 altPort; + HANDLE proxyThread; + HANDLE proxyHandle; + bool isExitSvr; +} TCP_PROXY_CTX, *PTCP_PORXY_CTX; + +typedef struct { + int proType; + TCHAR streamFilter[1024]; + TCHAR targetIp[MAX_IP_LEN]; + UINT16 targetPort; + int vmId; + int svrId; + TCP_PROXY_CTX tcpCtx; + UDP_PROXY_CTX udpCtx; +} PROXY_INFO, *PPROXY_INFO; + +typedef struct { + SOCKET s; + PPROXY_INFO pCtx; + bool inbound; + in_addr dest; +} PROXY_CONNECTION_CONFIG, *PPROXY_CONNECTION_CONFIG; + +static std::unordered_map g_ProxyColleagues; + +static int NewAvaliableSocket(SOCKET *pSock, UINT16 *pPort) { + const int reusedAddr = 1; + sockaddr_in proxySvrAddr {}; + sockaddr_in bindAddr {}; + int ret; + int addrSize = sizeof(sockaddr_in); + const SOCKET sock = socket(AF_INET, SOCK_STREAM, 0); + + if (sock == INVALID_SOCKET) { + SPDLOG_ERROR(TEXT("Cretate TCP Socket error: {0}"), WSAGetLastError()); + return -ERR_SOCKET_BIND_PORT; + } + + if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&reusedAddr), sizeof(int)) == + SOCKET_ERROR) { + SPDLOG_ERROR(TEXT("Failed to set socket optino SO_REUSEADDR ({0}})"), WSAGetLastError()); + closesocket(sock); + return -ERR_SOCKET_SET_OPT; + } + + proxySvrAddr.sin_family = AF_INET; + proxySvrAddr.sin_addr.s_addr = htonl(INADDR_ANY); + proxySvrAddr.sin_port = htons(0); + + if (bind(sock, reinterpret_cast(&proxySvrAddr), sizeof(proxySvrAddr)) == SOCKET_ERROR) { + SPDLOG_ERROR(TEXT("Failed to bind socket ({0})"), WSAGetLastError()); + closesocket(sock); + return -ERR_SOCKET_BIND; + } + + if (getsockname(sock, reinterpret_cast(&bindAddr), &addrSize) != 0) { + SPDLOG_ERROR(TEXT("Failed to get socket bind port ({0})"), WSAGetLastError()); + closesocket(sock); + return -ERR_SOCKET_GET_OPT; + } + + *pSock = sock; + *pPort = ntohs(bindAddr.sin_port); + + return ERR_SUCCESS; +} + +static DWORD proxyForwardCb(LPVOID lpParameter) { + return 0; +} + +static DWORD proxyConnCb(LPVOID lpParameter) { + const auto p = static_cast(lpParameter); + sockaddr_in altAddr {}; + SOCKET altSock; + HANDLE thread; + SOCKET connSock = p->s; + in_addr dest = p->dest; + PPROXY_INFO pInfo = p->pCtx; + PPROXY_CONNECTION_CONFIG pCfgProxySvr, pCfgAltSvr; + + HeapFree(GetProcessHeap(), 0, p); + + altSock = socket(AF_INET, SOCK_STREAM, 0); + + if (altSock == INVALID_SOCKET) { + SPDLOG_ERROR(TEXT("Cretate TCP Socket error: {0}"), WSAGetLastError()); + closesocket(connSock); + return 0; + } + + memset(&altAddr, 0, sizeof(altAddr)); + altAddr.sin_family = AF_INET; + altAddr.sin_port = htons(pInfo->tcpCtx.altPort); + altAddr.sin_addr = dest; + + if (connect(altSock, reinterpret_cast(&altAddr), sizeof(altAddr)) == SOCKET_ERROR) { + SPDLOG_ERROR(TEXT("Failed to connect socket ({0})"), WSAGetLastError()); + closesocket(connSock); + closesocket(altSock); + return 0; + } + + pInfo->tcpCtx.altSock = altSock; + + pCfgProxySvr = static_cast( + HeapAlloc(GetProcessHeap(), 0, sizeof(PROXY_CONNECTION_CONFIG))); + + if (pCfgProxySvr == nullptr) { + SPDLOG_ERROR(TEXT("Malloc {0} bytes error."), sizeof(PROXY_CONNECTION_CONFIG)); + closesocket(connSock); + closesocket(altSock); + return 0; + } + + pCfgAltSvr = static_cast(HeapAlloc(GetProcessHeap(), 0, sizeof(PROXY_CONNECTION_CONFIG))); + + if (pCfgAltSvr == nullptr) { + SPDLOG_ERROR(TEXT("Malloc {0} bytes error."), sizeof(PROXY_CONNECTION_CONFIG)); + closesocket(connSock); + closesocket(altSock); + free(pCfgProxySvr); + return 0; + } + + thread = CreateThread(nullptr, // Thread attributes + 0, // Stack size (0 = use default) + proxyForwardCb, // Thread start address + pCfgProxySvr, // Parameter to pass to the thread + 0, // Creation flags + nullptr); // Thread id + + if (thread == nullptr) { + SPDLOG_ERROR(TEXT("Failed to create thread ({0})"), GetLastError()); + closesocket(connSock); + closesocket(altSock); + free(pCfgProxySvr); + free(pCfgAltSvr); + return 0; + } + + return 0; +} + +static int StartTcpProxyService(PPROXY_INFO pInfo) { + pInfo->tcpCtx.isExitSvr = false; + + if (listen(pInfo->tcpCtx.proxySock, SOMAXCONN) == SOCKET_ERROR) { + SPDLOG_ERROR(TEXT("Failed to listen socket ({0})"), WSAGetLastError()); + closesocket(pInfo->tcpCtx.proxySock); + return -ERR_SOCKET_LISTEN; + } + + pInfo->tcpCtx.proxyThread = CreateThread( + nullptr, // Thread attributes + 0, // Stack size (0 = use default) + [](LPVOID lpParameter) { + const auto p = static_cast(lpParameter); + + while (!p->tcpCtx.isExitSvr) { + PPROXY_CONNECTION_CONFIG pCfg; + sockaddr_in connAddr {}; + int size = sizeof(connAddr); + + SOCKET s = accept(p->tcpCtx.proxySock, reinterpret_cast(&connAddr), &size); + + if (s == INVALID_SOCKET) { + continue; + } + + pCfg = static_cast( + HeapAlloc(GetProcessHeap(), 0, sizeof(PROXY_CONNECTION_CONFIG))); + + if (pCfg) { + HANDLE thread; + pCfg->s = s; + pCfg->dest = connAddr.sin_addr; + pCfg->pCtx = p; + + thread = CreateThread(nullptr, + 0, + proxyConnCb, // Thread start address + pCfg, // Parameter to pass to the thread + 0, + nullptr); + + if (thread == nullptr) { + closesocket(s); + HeapFree(GetProcessHeap(), 0, pCfg); + continue; + } + + CloseHandle(thread); + } + } + + return static_cast(0); + }, // Thread start address + pInfo, // Parameter to pass to the thread + 0, // Creation flags + nullptr); // Thread id + + if (pInfo->tcpCtx.proxyThread == nullptr) { + SPDLOG_ERROR(TEXT("Create TCP Listen Thread Error ({0})"), GetLastError()); + return -ERR_CREATE_THREAD; + } +} + +int CreatePorxyService(int proType, const TCHAR *pTargetIp, int targetPort, int vmId, int svrId) { + //int CreatePorxyService() { + int ret; + static HANDLE hDriver; + PPROXY_INFO pInfo; + std::string key; + std::unordered_map::iterator iter; + + // 查找先前代理是否存在 + key = std::string(pTargetIp) + ":" + std::to_string(targetPort); + + if ((iter = g_ProxyColleagues.find(key)) != g_ProxyColleagues.end()) { + pInfo = iter->second; + // 如果配置完全相同则直接返回 + if (pInfo->vmId == vmId && pInfo->svrId == svrId && pInfo->proType == proType) { + return ERR_SUCCESS; + } else { + pInfo->vmId = vmId; + pInfo->svrId = svrId; + pInfo->proType = proType; + } + } else { + // 创建新的代理配置 + pInfo = static_cast(HeapAlloc(GetProcessHeap(), 0, sizeof(PROXY_INFO))); + + if (pInfo == nullptr) { + SPDLOG_ERROR(TEXT("Error allocating {0} bytes memory "), sizeof(PROXY_INFO)); + return -ERR_MALLOC_MEMORY; + } + + memset(pInfo, 0, sizeof(PROXY_INFO)); + } + + memset(pInfo->streamFilter, 0, 1024); + + // 重构过滤器 + if (pInfo->proType & PROXY_UDP) { + StringCbPrintf(pInfo->streamFilter, 1024, TEXT("(udp.DstPort == %d)"), targetPort); + //StringCbPrintf(pFilter, 1024, TEXT("tcp && remotePort == 9276")); + } + + if (pInfo->proType & PROXY_TCP) { + TCHAR tmpFilter[1024]; + + // 预先分配代理和转发 Socket + if ((ret = NewAvaliableSocket(&pInfo->tcpCtx.proxySock, &pInfo->tcpCtx.proxyPort)) != ERR_SUCCESS) { + return ret; + } + + if ((ret = NewAvaliableSocket(&pInfo->tcpCtx.reservePortSock, &pInfo->tcpCtx.altPort)) != ERR_SUCCESS) { + return ret; + } + + // 构建过滤器 + StringCbPrintf(tmpFilter, + 1024, + TEXT("(tcp.DstPort == %d or tcp.DstPort == %d or tcp.DstPort == %d or tcp.SrcPort == %d or " + "tcp.SrcPort == %d or tcp.SrcPort == %d)"), + targetPort, + pInfo->tcpCtx.proxyPort, + pInfo->tcpCtx.altPort, + targetPort, + pInfo->tcpCtx.proxyPort, + pInfo->tcpCtx.altPort); + + if (lstrlen(pInfo->streamFilter) > 0) { + StringCbCat(pInfo->streamFilter, 1024, TEXT(" or ")); + StringCbCat(pInfo->streamFilter, 1024, tmpFilter); + } else { + StringCbCopy(pInfo->streamFilter, 1024, tmpFilter); + } + } + + // 启动代理服务 + if ((ret = StartTcpProxyService(pInfo)) != ERR_SUCCESS) { + return ret; + } + + hDriver = WinDivertOpen(pInfo->streamFilter, WINDIVERT_LAYER_NETWORK, 0, 0); + + if (hDriver == INVALID_HANDLE_VALUE) { + //ERROR_INSUFFICIENT_BUFFER + SPDLOG_ERROR(TEXT("Open Driver With Filter \"{1}\" Error: {0}"), GetLastError(), pInfo->streamFilter); + return -ERR_SYS_CALL; + } + + CreateThread( + nullptr, // Thread attributes + 0, // Stack size (0 = use default) + [](LPVOID lpParameter) { + const HANDLE h = lpParameter; + unsigned char packet[0xFFFF]; + UINT packet_len; + WINDIVERT_ADDRESS addr; + + while (true) { + if (!WinDivertRecv(h, packet, 0xFFFF, &packet_len, &addr)) { + SPDLOG_ERROR(TEXT("failed to read packet ({0})"), GetLastError()); + continue; + } + + switch (addr.Event) { + case WINDIVERT_EVENT_SOCKET_BIND: + SPDLOG_ERROR("BIND"); + break; + case WINDIVERT_EVENT_SOCKET_LISTEN: + + SPDLOG_ERROR("LISTEN"); + break; + case WINDIVERT_EVENT_SOCKET_CONNECT: + + SPDLOG_ERROR("CONNECT: {0:x}, {1:x}", addr.Socket.EndpointId, addr.Socket.ParentEndpointId); + break; + case WINDIVERT_EVENT_SOCKET_ACCEPT: + + SPDLOG_ERROR("ACCEPT"); + break; + case WINDIVERT_EVENT_SOCKET_CLOSE: + + SPDLOG_ERROR("CLOSE: {0:x}, {1:x}", addr.Socket.EndpointId, addr.Socket.ParentEndpointId); + break; + default: + SPDLOG_ERROR(TEXT("***({0})"), static_cast(addr.Event)); + break; + } + + /*if (!WinDivertSendEx(h, packet, packet_len, nullptr, 0, &addr, sizeof(WINDIVERT_ADDRESS), nullptr)) { + SPDLOG_ERROR(TEXT("warning: failed to reinject packet ({0})\n"), GetLastError()); + }*/ + } + + return static_cast(0); + }, // Thread start address + hDriver, // Parameter to pass to the thread + 0, // Creation flags + nullptr); // Thread id + return 0; +} \ No newline at end of file diff --git a/NetTunnelSDK/UserManager.cpp b/NetTunnelSDK/UserManager.cpp index c03f0f2..3b14729 100644 --- a/NetTunnelSDK/UserManager.cpp +++ b/NetTunnelSDK/UserManager.cpp @@ -94,6 +94,13 @@ int RemoteWireGuardControl(bool isStart) { int LocalWireGuardControl(bool isStart, bool setPrivateMode) { int ret; bool chkStatus = false; + int ifInetlnetIndex, ifWireGuardIndex; + + // 获取 Intelnet 网络网卡 Index + if ((ret = GetInternetIfIndex(&ifInetlnetIndex)) != ERR_SUCCESS) { + SPDLOG_ERROR(TEXT("Call GetInternetIfIndex error: {0}"), ret); + return ret; + } // 判断先前是否启动过服务 if ((ret = IsWireGuardServerRunning(GetGlobalCfgInfo()->userCfg.userName, &chkStatus)) != ERR_SUCCESS) { @@ -101,6 +108,7 @@ int LocalWireGuardControl(bool isStart, bool setPrivateMode) { return ret; } + // 先停止以前启动的隧道服务 if (chkStatus) { if ((ret = WireGuardUnInstallServerService(GetGlobalCfgInfo()->userCfg.userName)) != ERR_SUCCESS) { // 返回停止服务失败 @@ -109,6 +117,20 @@ int LocalWireGuardControl(bool isStart, bool setPrivateMode) { } } + // 检查 Internet 网络共享状态 + if ((ret = GetNetIntelnetConnectionSharing(ifInetlnetIndex, &chkStatus)) != ERR_SUCCESS) { + SPDLOG_ERROR(TEXT("Call GetNetIntelnetConnectionSharing error: {0}"), ret); + return ret; + } + + // 关闭 Intelnet 网络连接共享 + if (chkStatus) { + if ((ret = SetNetIntelnetConnectionSharing(ifInetlnetIndex, false, false)) != ERR_SUCCESS) { + SPDLOG_ERROR(TEXT("Call SetNetIntelnetConnectionSharing error: {0}"), ret); + return ret; + } + } + if (isStart) { // 启动服务 ret = WireGuardInstallDefaultServerService(true); @@ -118,19 +140,78 @@ int LocalWireGuardControl(bool isStart, bool setPrivateMode) { return ret; } - if ((ret = GetNetConnectionNetworkCategory(GetGlobalCfgInfo()->userCfg.userName, &chkStatus)) != ERR_SUCCESS) { - SPDLOG_ERROR(TEXT("Call GetNetConnectionNetworkCategory error: {0}"), ret); - return ret; - } - - // 检查网卡模式是否和设定值一致 - if (setPrivateMode != chkStatus) { - if ((ret = SetNetConnectionNetworkCategory(GetGlobalCfgInfo()->userCfg.userName, setPrivateMode)) != + if (GetCurrentNetShareMode() == ICS_SHARE_MODE) { + // 获取 WireGuard 隧道网络网卡 Index + if ((ret = GetInterfaceIfIndexByName(GetGlobalCfgInfo()->userCfg.userName, &ifWireGuardIndex)) != ERR_SUCCESS) { - SPDLOG_ERROR(TEXT("Call SetNetConnectionNetworkCategory error: {0}"), ret); + SPDLOG_ERROR(TEXT("Call GetInterfaceIfIndexByName error: {0}"), ret); + return ret; + } + + // 启动 WireGard 网络 ICS 服务为私有网络 + if ((ret = SetNetIntelnetConnectionSharing(ifWireGuardIndex, true, true)) != ERR_SUCCESS) { + SPDLOG_ERROR(TEXT("Call SetNetIntelnetConnectionSharing error: {0}"), ret); + return ret; + } + + // 启动 Intelnet 网络 ICS 服务为公共网络 + if ((ret = SetNetIntelnetConnectionSharing(ifInetlnetIndex, true, false)) != ERR_SUCCESS) { + SPDLOG_ERROR(TEXT("Call SetNetIntelnetConnectionSharing error: {0}"), ret); + return ret; + } + + // 校验 ICS 共享状态 + // 检查 WireGuard 网络共享状态 + if ((ret = GetNetIntelnetConnectionSharing(ifWireGuardIndex, &chkStatus)) != ERR_SUCCESS) { + SPDLOG_ERROR(TEXT("Call GetNetIntelnetConnectionSharing error: {0}"), ret); + return ret; + } + + if (!chkStatus) { + SPDLOG_ERROR(TEXT("WireGuard network ICS error")); + return -ERR_NET_WIREGUARD_ICS; + } + + // 检查 WireGuard 网络共享状态 + if ((ret = GetNetIntelnetConnectionSharing(ifInetlnetIndex, &chkStatus)) != ERR_SUCCESS) { + SPDLOG_ERROR(TEXT("Call GetNetIntelnetConnectionSharing error: {0}"), ret); + return ret; + } + + if (!chkStatus) { + SPDLOG_ERROR(TEXT("Internet network ICS error")); + return -ERR_NET_WIREGUARD_ICS; + } + + SPDLOG_INFO(TEXT("Net Share Service Work now on ICS mode: {0}"), GetGlobalCfgInfo()->userCfg.userName); + } else if (GetCurrentNetShareMode() == NAT_SHARE_MODE) { + IP_INFO ipInfo; + TCHAR ipNat[MAX_IP_LEN]; + GetIpV4InfoFromCIDR(GetGlobalCfgInfo()->userCfg.cliConfig.cliAddress, &ipInfo); + StringCbPrintf(ipNat, MAX_IP_LEN, TEXT("%s/%d"), ipInfo.hostmax, ipInfo.prefix); + + // 检查 WireGuard 网络共享状态 + if ((ret = SetNATRule(GetGlobalCfgInfo()->userCfg.userName, ipNat)) != ERR_SUCCESS) { + SPDLOG_ERROR(TEXT("Call GetNetIntelnetConnectionSharing error: {0}"), ret); + return ret; + } + + SPDLOG_INFO(TEXT("Net Share Service Work now on NAT mode: {0}_nat --> {1}"), + GetGlobalCfgInfo()->userCfg.userName, + ipNat); + } else { + SPDLOG_ERROR(TEXT("Not support Net Share Type: {0}"), static_cast(GetCurrentNetShareMode())); + return -ERR_UN_SUPPORT; + } + } else { + if (GetCurrentNetShareMode() == NAT_SHARE_MODE) { + // 检查 WireGuard 网络共享状态 + if ((ret = RemoveNATRule(GetGlobalCfgInfo()->userCfg.userName)) != ERR_SUCCESS) { + SPDLOG_ERROR(TEXT("Call RemoveNATRule error: {0}"), ret); return ret; } } + SPDLOG_INFO(TEXT("Net Share Service Stoped: {0}"), GetGlobalCfgInfo()->userCfg.userName); } return ERR_SUCCESS; @@ -176,6 +257,13 @@ int RemoteCtrlSvrCfgUserTunnel(int vmId, const TCHAR *pCliNetwork) { pUserCfg->cliAddress, rsp.msgContent.svrNetwork.c_str(), pUserCfg->pVMConfig[i].scgTunnelGw); + + if (ret != ERR_SUCCESS) { + SPDLOG_ERROR(TEXT("SetTunnelConfigure Error: {0}"), ret); + return ret; + } + + GetGlobalCfgInfo()->curConnVmId = vmId; return ERR_SUCCESS; } } @@ -191,6 +279,7 @@ int SetTunnelConfigure(const TCHAR *pCliPrivateKey, const TCHAR *pSvrEndPoint) { int ret; bool isSvrStart = false; + int ifInetlnetIndex; IP_INFO tunnelInfo = {}; IP_INFO svrInfo = {}; WGCLIENT_CONFIG cliCfg = {}; @@ -245,6 +334,38 @@ int SetTunnelConfigure(const TCHAR *pCliPrivateKey, } } + // 获取 Intelnet 网络网卡 Index + if ((ret = GetInternetIfIndex(&ifInetlnetIndex)) != ERR_SUCCESS) { + SPDLOG_ERROR(TEXT("Call GetInternetIfIndex error: {0}"), ret); + return ret; + } + + if (GetCurrentNetShareMode() == ICS_SHARE_MODE) { + // 检查 Internet 网络共享状态 + if ((ret = GetNetIntelnetConnectionSharing(ifInetlnetIndex, &isSvrStart)) != ERR_SUCCESS) { + SPDLOG_ERROR(TEXT("Call GetNetIntelnetConnectionSharing error: {0}"), ret); + return ret; + } + + // 关闭 Intelnet 网络连接共享 + if (isSvrStart) { + if ((ret = SetNetIntelnetConnectionSharing(ifInetlnetIndex, false, false)) != ERR_SUCCESS) { + SPDLOG_ERROR(TEXT("Call SetNetIntelnetConnectionSharing error: {0}"), ret); + return ret; + } + } + } + +#if 0 + if (GetCurrentNetShareMode() == NAT_SHARE_MODE) { + // 清理旧的 NAT 配置 + if ((ret = RemoveNATRule(GetGlobalCfgInfo()->userCfg.userName)) != ERR_SUCCESS) { + SPDLOG_ERROR(TEXT("Call GetNetIntelnetConnectionSharing error: {0}"), ret); + return ret; + } + } +#endif + ret = GetIpV4InfoFromCIDR(pSvrTunnelAddr, &tunnelInfo); if (ret != ERR_SUCCESS) { diff --git a/NetTunnelSDK/WinDivert/include/windivert.h b/NetTunnelSDK/WinDivert/include/windivert.h new file mode 100644 index 0000000..fc63adf --- /dev/null +++ b/NetTunnelSDK/WinDivert/include/windivert.h @@ -0,0 +1,630 @@ +/* + * windivert.h + * (C) 2019, all rights reserved, + * + * This file is part of WinDivert. + * + * WinDivert is free software: you can redistribute it and/or modify it under + * the terms of the GNU Lesser 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 Lesser General Public + * License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + * + * WinDivert 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 2 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, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +#ifndef __WINDIVERT_H +#define __WINDIVERT_H + +#ifndef WINDIVERT_KERNEL +#include +#endif /* WINDIVERT_KERNEL */ + +#ifndef WINDIVERTEXPORT +#define WINDIVERTEXPORT extern __declspec(dllimport) +#endif /* WINDIVERTEXPORT */ + +#ifdef __MINGW32__ +#define __in +#define __in_opt +#define __out +#define __out_opt +#define __inout +#define __inout_opt +#include +#define INT8 int8_t +#define UINT8 uint8_t +#define INT16 int16_t +#define UINT16 uint16_t +#define INT32 int32_t +#define UINT32 uint32_t +#define INT64 int64_t +#define UINT64 uint64_t +#endif /* __MINGW32__ */ + +#ifdef __cplusplus +extern "C" { +#endif + +/****************************************************************************/ +/* WINDIVERT API */ +/****************************************************************************/ + +/* + * WinDivert layers. + */ +typedef enum +{ + WINDIVERT_LAYER_NETWORK = 0, /* Network layer. */ + WINDIVERT_LAYER_NETWORK_FORWARD = 1,/* Network layer (forwarded packets) */ + WINDIVERT_LAYER_FLOW = 2, /* Flow layer. */ + WINDIVERT_LAYER_SOCKET = 3, /* Socket layer. */ + WINDIVERT_LAYER_REFLECT = 4, /* Reflect layer. */ +} WINDIVERT_LAYER, *PWINDIVERT_LAYER; + +/* + * WinDivert NETWORK and NETWORK_FORWARD layer data. + */ +typedef struct +{ + UINT32 IfIdx; /* Packet's interface index. */ + UINT32 SubIfIdx; /* Packet's sub-interface index. */ +} WINDIVERT_DATA_NETWORK, *PWINDIVERT_DATA_NETWORK; + +/* + * WinDivert FLOW layer data. + */ +typedef struct +{ + UINT64 EndpointId; /* Endpoint ID. */ + UINT64 ParentEndpointId; /* Parent endpoint ID. */ + UINT32 ProcessId; /* Process ID. */ + UINT32 LocalAddr[4]; /* Local address. */ + UINT32 RemoteAddr[4]; /* Remote address. */ + UINT16 LocalPort; /* Local port. */ + UINT16 RemotePort; /* Remote port. */ + UINT8 Protocol; /* Protocol. */ +} WINDIVERT_DATA_FLOW, *PWINDIVERT_DATA_FLOW; + +/* + * WinDivert SOCKET layer data. + */ +typedef struct +{ + UINT64 EndpointId; /* Endpoint ID. */ + UINT64 ParentEndpointId; /* Parent Endpoint ID. */ + UINT32 ProcessId; /* Process ID. */ + UINT32 LocalAddr[4]; /* Local address. */ + UINT32 RemoteAddr[4]; /* Remote address. */ + UINT16 LocalPort; /* Local port. */ + UINT16 RemotePort; /* Remote port. */ + UINT8 Protocol; /* Protocol. */ +} WINDIVERT_DATA_SOCKET, *PWINDIVERT_DATA_SOCKET; + +/* + * WinDivert REFLECTION layer data. + */ +typedef struct +{ + INT64 Timestamp; /* Handle open time. */ + UINT32 ProcessId; /* Handle process ID. */ + WINDIVERT_LAYER Layer; /* Handle layer. */ + UINT64 Flags; /* Handle flags. */ + INT16 Priority; /* Handle priority. */ +} WINDIVERT_DATA_REFLECT, *PWINDIVERT_DATA_REFLECT; + +/* + * WinDivert address. + */ +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable: 4201) +#endif +typedef struct +{ + INT64 Timestamp; /* Packet's timestamp. */ + UINT32 Layer:8; /* Packet's layer. */ + UINT32 Event:8; /* Packet event. */ + UINT32 Sniffed:1; /* Packet was sniffed? */ + UINT32 Outbound:1; /* Packet is outound? */ + UINT32 Loopback:1; /* Packet is loopback? */ + UINT32 Impostor:1; /* Packet is impostor? */ + UINT32 IPv6:1; /* Packet is IPv6? */ + UINT32 IPChecksum:1; /* Packet has valid IPv4 checksum? */ + UINT32 TCPChecksum:1; /* Packet has valid TCP checksum? */ + UINT32 UDPChecksum:1; /* Packet has valid UDP checksum? */ + UINT32 Reserved1:8; + UINT32 Reserved2; + union + { + WINDIVERT_DATA_NETWORK Network; /* Network layer data. */ + WINDIVERT_DATA_FLOW Flow; /* Flow layer data. */ + WINDIVERT_DATA_SOCKET Socket; /* Socket layer data. */ + WINDIVERT_DATA_REFLECT Reflect; /* Reflect layer data. */ + UINT8 Reserved3[64]; + }; +} WINDIVERT_ADDRESS, *PWINDIVERT_ADDRESS; +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +/* + * WinDivert events. + */ +typedef enum +{ + WINDIVERT_EVENT_NETWORK_PACKET = 0, /* Network packet. */ + WINDIVERT_EVENT_FLOW_ESTABLISHED = 1, + /* Flow established. */ + WINDIVERT_EVENT_FLOW_DELETED = 2, /* Flow deleted. */ + WINDIVERT_EVENT_SOCKET_BIND = 3, /* Socket bind. */ + WINDIVERT_EVENT_SOCKET_CONNECT = 4, /* Socket connect. */ + WINDIVERT_EVENT_SOCKET_LISTEN = 5, /* Socket listen. */ + WINDIVERT_EVENT_SOCKET_ACCEPT = 6, /* Socket accept. */ + WINDIVERT_EVENT_SOCKET_CLOSE = 7, /* Socket close. */ + WINDIVERT_EVENT_REFLECT_OPEN = 8, /* WinDivert handle opened. */ + WINDIVERT_EVENT_REFLECT_CLOSE = 9, /* WinDivert handle closed. */ +} WINDIVERT_EVENT, *PWINDIVERT_EVENT; + +/* + * WinDivert flags. + */ +#define WINDIVERT_FLAG_SNIFF 0x0001 +#define WINDIVERT_FLAG_DROP 0x0002 +#define WINDIVERT_FLAG_RECV_ONLY 0x0004 +#define WINDIVERT_FLAG_READ_ONLY WINDIVERT_FLAG_RECV_ONLY +#define WINDIVERT_FLAG_SEND_ONLY 0x0008 +#define WINDIVERT_FLAG_WRITE_ONLY WINDIVERT_FLAG_SEND_ONLY +#define WINDIVERT_FLAG_NO_INSTALL 0x0010 +#define WINDIVERT_FLAG_FRAGMENTS 0x0020 + +/* + * WinDivert parameters. + */ +typedef enum +{ + WINDIVERT_PARAM_QUEUE_LENGTH = 0, /* Packet queue length. */ + WINDIVERT_PARAM_QUEUE_TIME = 1, /* Packet queue time. */ + WINDIVERT_PARAM_QUEUE_SIZE = 2, /* Packet queue size. */ + WINDIVERT_PARAM_VERSION_MAJOR = 3, /* Driver version (major). */ + WINDIVERT_PARAM_VERSION_MINOR = 4, /* Driver version (minor). */ +} WINDIVERT_PARAM, *PWINDIVERT_PARAM; +#define WINDIVERT_PARAM_MAX WINDIVERT_PARAM_VERSION_MINOR + +/* + * WinDivert shutdown parameter. + */ +typedef enum +{ + WINDIVERT_SHUTDOWN_RECV = 0x1, /* Shutdown recv. */ + WINDIVERT_SHUTDOWN_SEND = 0x2, /* Shutdown send. */ + WINDIVERT_SHUTDOWN_BOTH = 0x3, /* Shutdown recv and send. */ +} WINDIVERT_SHUTDOWN, *PWINDIVERT_SHUTDOWN; +#define WINDIVERT_SHUTDOWN_MAX WINDIVERT_SHUTDOWN_BOTH + +#ifndef WINDIVERT_KERNEL + +/* + * Open a WinDivert handle. + */ +WINDIVERTEXPORT HANDLE WinDivertOpen( + __in const char *filter, + __in WINDIVERT_LAYER layer, + __in INT16 priority, + __in UINT64 flags); + +/* + * Receive (read) a packet from a WinDivert handle. + */ +WINDIVERTEXPORT BOOL WinDivertRecv( + __in HANDLE handle, + __out_opt VOID *pPacket, + __in UINT packetLen, + __out_opt UINT *pRecvLen, + __out_opt WINDIVERT_ADDRESS *pAddr); + +/* + * Receive (read) a packet from a WinDivert handle. + */ +WINDIVERTEXPORT BOOL WinDivertRecvEx( + __in HANDLE handle, + __out_opt VOID *pPacket, + __in UINT packetLen, + __out_opt UINT *pRecvLen, + __in UINT64 flags, + __out WINDIVERT_ADDRESS *pAddr, + __inout_opt UINT *pAddrLen, + __inout_opt LPOVERLAPPED lpOverlapped); + +/* + * Send (write/inject) a packet to a WinDivert handle. + */ +WINDIVERTEXPORT BOOL WinDivertSend( + __in HANDLE handle, + __in const VOID *pPacket, + __in UINT packetLen, + __out_opt UINT *pSendLen, + __in const WINDIVERT_ADDRESS *pAddr); + +/* + * Send (write/inject) a packet to a WinDivert handle. + */ +WINDIVERTEXPORT BOOL WinDivertSendEx( + __in HANDLE handle, + __in const VOID *pPacket, + __in UINT packetLen, + __out_opt UINT *pSendLen, + __in UINT64 flags, + __in const WINDIVERT_ADDRESS *pAddr, + __in UINT addrLen, + __inout_opt LPOVERLAPPED lpOverlapped); + +/* + * Shutdown a WinDivert handle. + */ +WINDIVERTEXPORT BOOL WinDivertShutdown( + __in HANDLE handle, + __in WINDIVERT_SHUTDOWN how); + +/* + * Close a WinDivert handle. + */ +WINDIVERTEXPORT BOOL WinDivertClose( + __in HANDLE handle); + +/* + * Set a WinDivert handle parameter. + */ +WINDIVERTEXPORT BOOL WinDivertSetParam( + __in HANDLE handle, + __in WINDIVERT_PARAM param, + __in UINT64 value); + +/* + * Get a WinDivert handle parameter. + */ +WINDIVERTEXPORT BOOL WinDivertGetParam( + __in HANDLE handle, + __in WINDIVERT_PARAM param, + __out UINT64 *pValue); + +#endif /* WINDIVERT_KERNEL */ + +/* + * WinDivert constants. + */ +#define WINDIVERT_PRIORITY_HIGHEST 30000 +#define WINDIVERT_PRIORITY_LOWEST (-WINDIVERT_PRIORITY_HIGHEST) +#define WINDIVERT_PARAM_QUEUE_LENGTH_DEFAULT 4096 +#define WINDIVERT_PARAM_QUEUE_LENGTH_MIN 32 +#define WINDIVERT_PARAM_QUEUE_LENGTH_MAX 16384 +#define WINDIVERT_PARAM_QUEUE_TIME_DEFAULT 2000 /* 2s */ +#define WINDIVERT_PARAM_QUEUE_TIME_MIN 100 /* 100ms */ +#define WINDIVERT_PARAM_QUEUE_TIME_MAX 16000 /* 16s */ +#define WINDIVERT_PARAM_QUEUE_SIZE_DEFAULT 4194304 /* 4MB */ +#define WINDIVERT_PARAM_QUEUE_SIZE_MIN 65535 /* 64KB */ +#define WINDIVERT_PARAM_QUEUE_SIZE_MAX 33554432 /* 32MB */ +#define WINDIVERT_BATCH_MAX 0xFF /* 255 */ +#define WINDIVERT_MTU_MAX (40 + 0xFFFF) + +/****************************************************************************/ +/* WINDIVERT HELPER API */ +/****************************************************************************/ + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable: 4214) +#endif + +/* + * IPv4/IPv6/ICMP/ICMPv6/TCP/UDP header definitions. + */ +typedef struct +{ + UINT8 HdrLength:4; + UINT8 Version:4; + UINT8 TOS; + UINT16 Length; + UINT16 Id; + UINT16 FragOff0; + UINT8 TTL; + UINT8 Protocol; + UINT16 Checksum; + UINT32 SrcAddr; + UINT32 DstAddr; +} WINDIVERT_IPHDR, *PWINDIVERT_IPHDR; + +#define WINDIVERT_IPHDR_GET_FRAGOFF(hdr) \ + (((hdr)->FragOff0) & 0xFF1F) +#define WINDIVERT_IPHDR_GET_MF(hdr) \ + ((((hdr)->FragOff0) & 0x0020) != 0) +#define WINDIVERT_IPHDR_GET_DF(hdr) \ + ((((hdr)->FragOff0) & 0x0040) != 0) +#define WINDIVERT_IPHDR_GET_RESERVED(hdr) \ + ((((hdr)->FragOff0) & 0x0080) != 0) + +#define WINDIVERT_IPHDR_SET_FRAGOFF(hdr, val) \ + do \ + { \ + (hdr)->FragOff0 = (((hdr)->FragOff0) & 0x00E0) | \ + ((val) & 0xFF1F); \ + } \ + while (FALSE) +#define WINDIVERT_IPHDR_SET_MF(hdr, val) \ + do \ + { \ + (hdr)->FragOff0 = (((hdr)->FragOff0) & 0xFFDF) | \ + (((val) & 0x0001) << 5); \ + } \ + while (FALSE) +#define WINDIVERT_IPHDR_SET_DF(hdr, val) \ + do \ + { \ + (hdr)->FragOff0 = (((hdr)->FragOff0) & 0xFFBF) | \ + (((val) & 0x0001) << 6); \ + } \ + while (FALSE) +#define WINDIVERT_IPHDR_SET_RESERVED(hdr, val) \ + do \ + { \ + (hdr)->FragOff0 = (((hdr)->FragOff0) & 0xFF7F) | \ + (((val) & 0x0001) << 7); \ + } \ + while (FALSE) + +typedef struct +{ + UINT8 TrafficClass0:4; + UINT8 Version:4; + UINT8 FlowLabel0:4; + UINT8 TrafficClass1:4; + UINT16 FlowLabel1; + UINT16 Length; + UINT8 NextHdr; + UINT8 HopLimit; + UINT32 SrcAddr[4]; + UINT32 DstAddr[4]; +} WINDIVERT_IPV6HDR, *PWINDIVERT_IPV6HDR; + +#define WINDIVERT_IPV6HDR_GET_TRAFFICCLASS(hdr) \ + ((((hdr)->TrafficClass0) << 4) | ((hdr)->TrafficClass1)) +#define WINDIVERT_IPV6HDR_GET_FLOWLABEL(hdr) \ + ((((UINT32)(hdr)->FlowLabel0) << 16) | ((UINT32)(hdr)->FlowLabel1)) + +#define WINDIVERT_IPV6HDR_SET_TRAFFICCLASS(hdr, val) \ + do \ + { \ + (hdr)->TrafficClass0 = ((UINT8)(val) >> 4); \ + (hdr)->TrafficClass1 = (UINT8)(val); \ + } \ + while (FALSE) +#define WINDIVERT_IPV6HDR_SET_FLOWLABEL(hdr, val) \ + do \ + { \ + (hdr)->FlowLabel0 = (UINT8)((val) >> 16); \ + (hdr)->FlowLabel1 = (UINT16)(val); \ + } \ + while (FALSE) + +typedef struct +{ + UINT8 Type; + UINT8 Code; + UINT16 Checksum; + UINT32 Body; +} WINDIVERT_ICMPHDR, *PWINDIVERT_ICMPHDR; + +typedef struct +{ + UINT8 Type; + UINT8 Code; + UINT16 Checksum; + UINT32 Body; +} WINDIVERT_ICMPV6HDR, *PWINDIVERT_ICMPV6HDR; + +typedef struct +{ + UINT16 SrcPort; + UINT16 DstPort; + UINT32 SeqNum; + UINT32 AckNum; + UINT16 Reserved1:4; + UINT16 HdrLength:4; + UINT16 Fin:1; + UINT16 Syn:1; + UINT16 Rst:1; + UINT16 Psh:1; + UINT16 Ack:1; + UINT16 Urg:1; + UINT16 Reserved2:2; + UINT16 Window; + UINT16 Checksum; + UINT16 UrgPtr; +} WINDIVERT_TCPHDR, *PWINDIVERT_TCPHDR; + +typedef struct +{ + UINT16 SrcPort; + UINT16 DstPort; + UINT16 Length; + UINT16 Checksum; +} WINDIVERT_UDPHDR, *PWINDIVERT_UDPHDR; + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +/* + * Flags for WinDivertHelperCalcChecksums() + */ +#define WINDIVERT_HELPER_NO_IP_CHECKSUM 1 +#define WINDIVERT_HELPER_NO_ICMP_CHECKSUM 2 +#define WINDIVERT_HELPER_NO_ICMPV6_CHECKSUM 4 +#define WINDIVERT_HELPER_NO_TCP_CHECKSUM 8 +#define WINDIVERT_HELPER_NO_UDP_CHECKSUM 16 + +#ifndef WINDIVERT_KERNEL + +/* + * Hash a packet. + */ +WINDIVERTEXPORT UINT64 WinDivertHelperHashPacket( + __in const VOID *pPacket, + __in UINT packetLen, + __in UINT64 seed +#ifdef __cplusplus + = 0 +#endif +); + +/* + * Parse IPv4/IPv6/ICMP/ICMPv6/TCP/UDP headers from a raw packet. + */ +WINDIVERTEXPORT BOOL WinDivertHelperParsePacket( + __in const VOID *pPacket, + __in UINT packetLen, + __out_opt PWINDIVERT_IPHDR *ppIpHdr, + __out_opt PWINDIVERT_IPV6HDR *ppIpv6Hdr, + __out_opt UINT8 *pProtocol, + __out_opt PWINDIVERT_ICMPHDR *ppIcmpHdr, + __out_opt PWINDIVERT_ICMPV6HDR *ppIcmpv6Hdr, + __out_opt PWINDIVERT_TCPHDR *ppTcpHdr, + __out_opt PWINDIVERT_UDPHDR *ppUdpHdr, + __out_opt PVOID *ppData, + __out_opt UINT *pDataLen, + __out_opt PVOID *ppNext, + __out_opt UINT *pNextLen); + +/* + * Parse an IPv4 address. + */ +WINDIVERTEXPORT BOOL WinDivertHelperParseIPv4Address( + __in const char *addrStr, + __out_opt UINT32 *pAddr); + +/* + * Parse an IPv6 address. + */ +WINDIVERTEXPORT BOOL WinDivertHelperParseIPv6Address( + __in const char *addrStr, + __out_opt UINT32 *pAddr); + +/* + * Format an IPv4 address. + */ +WINDIVERTEXPORT BOOL WinDivertHelperFormatIPv4Address( + __in UINT32 addr, + __out char *buffer, + __in UINT bufLen); + +/* + * Format an IPv6 address. + */ +WINDIVERTEXPORT BOOL WinDivertHelperFormatIPv6Address( + __in const UINT32 *pAddr, + __out char *buffer, + __in UINT bufLen); + +/* + * Calculate IPv4/IPv6/ICMP/ICMPv6/TCP/UDP checksums. + */ +WINDIVERTEXPORT BOOL WinDivertHelperCalcChecksums( + __inout VOID *pPacket, + __in UINT packetLen, + __out_opt WINDIVERT_ADDRESS *pAddr, + __in UINT64 flags); + +/* + * Decrement the TTL/HopLimit. + */ +WINDIVERTEXPORT BOOL WinDivertHelperDecrementTTL( + __inout VOID *pPacket, + __in UINT packetLen); + +/* + * Compile the given filter string. + */ +WINDIVERTEXPORT BOOL WinDivertHelperCompileFilter( + __in const char *filter, + __in WINDIVERT_LAYER layer, + __out_opt char *object, + __in UINT objLen, + __out_opt const char **errorStr, + __out_opt UINT *errorPos); + +/* + * Evaluate the given filter string. + */ +WINDIVERTEXPORT BOOL WinDivertHelperEvalFilter( + __in const char *filter, + __in const VOID *pPacket, + __in UINT packetLen, + __in const WINDIVERT_ADDRESS *pAddr); + +/* + * Format the given filter string. + */ +WINDIVERTEXPORT BOOL WinDivertHelperFormatFilter( + __in const char *filter, + __in WINDIVERT_LAYER layer, + __out char *buffer, + __in UINT bufLen); + +/* + * Byte ordering. + */ +WINDIVERTEXPORT UINT16 WinDivertHelperNtohs( + __in UINT16 x); +WINDIVERTEXPORT UINT16 WinDivertHelperHtons( + __in UINT16 x); +WINDIVERTEXPORT UINT32 WinDivertHelperNtohl( + __in UINT32 x); +WINDIVERTEXPORT UINT32 WinDivertHelperHtonl( + __in UINT32 x); +WINDIVERTEXPORT UINT64 WinDivertHelperNtohll( + __in UINT64 x); +WINDIVERTEXPORT UINT64 WinDivertHelperHtonll( + __in UINT64 x); +WINDIVERTEXPORT void WinDivertHelperNtohIPv6Address( + __in const UINT *inAddr, + __out UINT *outAddr); +WINDIVERTEXPORT void WinDivertHelperHtonIPv6Address( + __in const UINT *inAddr, + __out UINT *outAddr); + +/* + * Old names to be removed in the next version. + */ +WINDIVERTEXPORT void WinDivertHelperNtohIpv6Address( + __in const UINT *inAddr, + __out UINT *outAddr); +WINDIVERTEXPORT void WinDivertHelperHtonIpv6Address( + __in const UINT *inAddr, + __out UINT *outAddr); + +#endif /* WINDIVERT_KERNEL */ + +#ifdef __cplusplus +} +#endif + +#endif /* __WINDIVERT_H */ diff --git a/NetTunnelSDK/WinDivert/x86/WinDivert.dll b/NetTunnelSDK/WinDivert/x86/WinDivert.dll new file mode 100644 index 0000000..b9602c0 Binary files /dev/null and b/NetTunnelSDK/WinDivert/x86/WinDivert.dll differ diff --git a/NetTunnelSDK/WinDivert/x86/WinDivert.lib b/NetTunnelSDK/WinDivert/x86/WinDivert.lib new file mode 100644 index 0000000..1ec1139 Binary files /dev/null and b/NetTunnelSDK/WinDivert/x86/WinDivert.lib differ diff --git a/NetTunnelSDK/WinDivert/x86/WinDivert32.sys b/NetTunnelSDK/WinDivert/x86/WinDivert32.sys new file mode 100644 index 0000000..d06738c Binary files /dev/null and b/NetTunnelSDK/WinDivert/x86/WinDivert32.sys differ diff --git a/NetTunnelSDK/WinDivert/x86/WinDivert64.sys b/NetTunnelSDK/WinDivert/x86/WinDivert64.sys new file mode 100644 index 0000000..218ccaf Binary files /dev/null and b/NetTunnelSDK/WinDivert/x86/WinDivert64.sys differ diff --git a/NetTunnelSDK/dllmain.cpp b/NetTunnelSDK/dllmain.cpp index 08d5d62..cdc86ee 100644 --- a/NetTunnelSDK/dllmain.cpp +++ b/NetTunnelSDK/dllmain.cpp @@ -19,8 +19,7 @@ BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserv break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: - case DLL_PROCESS_DETACH: - TunnelSDKUnInit(); + case DLL_PROCESS_DETACH: CoFreeUnusedLibraries(); break; default: diff --git a/NetTunnelSDK/globalcfg.h b/NetTunnelSDK/globalcfg.h index f2f571d..7f4fe1b 100644 --- a/NetTunnelSDK/globalcfg.h +++ b/NetTunnelSDK/globalcfg.h @@ -74,6 +74,7 @@ typedef struct { TCHAR systemDirectory[MAX_PATH]; ///< 操作系统目录 TCHAR workDirectory[MAX_PATH]; ///< SDK 当前工作目录 bool isWorkServer; ///< SDK 当前模式 客户端/服务端 + bool usedSCGProxy; ///< 是否启动 SCG 代理 PROTO_CRYPTO_TYPE proCryptoType; ///< 协议加密类型 TCHAR proKeyBuf[256]; ///< 协议加密秘钥 BOOL enableLog; ///< 是否启用日志 @@ -83,6 +84,7 @@ typedef struct { WGINTERFACE_CFG wgServerCfg; ///< wireguard 服务端网络接口配置 WGINTERFACE_CFG wgClientCfg; ///< wireguard 客户端网络接口配置 USER_CONFIG userCfg; ///< 用户配置项 + int curConnVmId; ///< 当前连接的VM } SDK_CONFIG, *PSDK_CONFIG; #ifdef __cplusplus // If used by C++ code, diff --git a/NetTunnelSDK/httplib.h b/NetTunnelSDK/httplib.h index 9753439..bfa8b56 100644 --- a/NetTunnelSDK/httplib.h +++ b/NetTunnelSDK/httplib.h @@ -95,10 +95,8 @@ #endif #ifndef CPPHTTPLIB_THREAD_POOL_COUNT -#define CPPHTTPLIB_THREAD_POOL_COUNT \ - ((std::max)(8u, std::thread::hardware_concurrency() > 0 \ - ? std::thread::hardware_concurrency() - 1 \ - : 0)) +#define CPPHTTPLIB_THREAD_POOL_COUNT \ + ((std::max)(8u, std::thread::hardware_concurrency() > 0 ? std::thread::hardware_concurrency() - 1 : 0)) #endif #ifndef CPPHTTPLIB_RECV_FLAGS @@ -120,11 +118,11 @@ #ifdef _WIN32 #ifndef _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS -#endif //_CRT_SECURE_NO_WARNINGS +#endif //_CRT_SECURE_NO_WARNINGS #ifndef _CRT_NONSTDC_NO_DEPRECATE #define _CRT_NONSTDC_NO_DEPRECATE -#endif //_CRT_NONSTDC_NO_DEPRECATE +#endif //_CRT_NONSTDC_NO_DEPRECATE #if defined(_MSC_VER) #if _MSC_VER < 1900 @@ -138,19 +136,19 @@ using ssize_t = __int64; #else using ssize_t = long; #endif -#endif // _MSC_VER +#endif // _MSC_VER #ifndef S_ISREG #define S_ISREG(m) (((m)&S_IFREG) == S_IFREG) -#endif // S_ISREG +#endif // S_ISREG #ifndef S_ISDIR #define S_ISDIR(m) (((m)&S_IFDIR) == S_IFDIR) -#endif // S_ISDIR +#endif // S_ISDIR #ifndef NOMINMAX #define NOMINMAX -#endif // NOMINMAX +#endif // NOMINMAX #include #include @@ -162,14 +160,14 @@ using ssize_t = long; #ifndef strcasecmp #define strcasecmp _stricmp -#endif // strcasecmp +#endif // strcasecmp using socket_t = SOCKET; #ifdef CPPHTTPLIB_USE_POLL #define poll(fds, nfds, timeout) WSAPoll(fds, nfds, timeout) #endif -#else // not _WIN32 +#else // not _WIN32 #include #if !defined(_AIX) && !defined(__MVS__) @@ -202,7 +200,7 @@ using socket_t = int; #ifndef INVALID_SOCKET #define INVALID_SOCKET (-1) #endif -#endif //_WIN32 +#endif //_WIN32 #include #include @@ -253,8 +251,8 @@ using socket_t = int; #if TARGET_OS_OSX #include #include -#endif // TARGET_OS_OSX -#endif // _WIN32 +#endif // TARGET_OS_OSX +#endif // _WIN32 #include #include @@ -292,6 +290,8 @@ namespace httplib { namespace detail { +typedef void (*POSTSOCKETCONNECTCB)(socket_t sock); + /* * Backport std::make_unique from C++14. * @@ -300,63 +300,66 @@ namespace detail { * */ -template -typename std::enable_if::value, std::unique_ptr>::type -make_unique(Args &&...args) { - return std::unique_ptr(new T(std::forward(args)...)); +template +typename std::enable_if::value, std::unique_ptr>::type make_unique(Args &&...args) { + return std::unique_ptr(new T(std::forward(args)...)); } -template -typename std::enable_if::value, std::unique_ptr>::type -make_unique(std::size_t n) { - typedef typename std::remove_extent::type RT; - return std::unique_ptr(new RT[n]); +template +typename std::enable_if::value, std::unique_ptr>::type make_unique(std::size_t n) { + typedef typename std::remove_extent::type RT; + return std::unique_ptr(new RT[n]); } struct ci { - bool operator()(const std::string &s1, const std::string &s2) const { - return std::lexicographical_compare(s1.begin(), s1.end(), s2.begin(), - s2.end(), - [](unsigned char c1, unsigned char c2) { - return ::tolower(c1) < ::tolower(c2); - }); - } + bool operator()(const std::string &s1, const std::string &s2) const { + return std::lexicographical_compare( + s1.begin(), + s1.end(), + s2.begin(), + s2.end(), + [](unsigned char c1, unsigned char c2) { return ::tolower(c1) < ::tolower(c2); }); + } }; // This is based on // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189". struct scope_exit { - explicit scope_exit(std::function &&f) - : exit_function(std::move(f)), execute_on_destruction{true} {} + explicit scope_exit(std::function &&f) : exit_function(std::move(f)), execute_on_destruction {true} { + } - scope_exit(scope_exit &&rhs) - : exit_function(std::move(rhs.exit_function)), - execute_on_destruction{rhs.execute_on_destruction} { - rhs.release(); - } + scope_exit(scope_exit &&rhs) + : exit_function(std::move(rhs.exit_function)), + execute_on_destruction {rhs.execute_on_destruction} { + rhs.release(); + } - ~scope_exit() { - if (execute_on_destruction) { this->exit_function(); } - } + ~scope_exit() { + if (execute_on_destruction) { + this->exit_function(); + } + } - void release() { this->execute_on_destruction = false; } + void release() { + this->execute_on_destruction = false; + } private: - scope_exit(const scope_exit &) = delete; - void operator=(const scope_exit &) = delete; - scope_exit &operator=(scope_exit &&) = delete; + scope_exit(const scope_exit &) = delete; + void operator=(const scope_exit &) = delete; + scope_exit &operator=(scope_exit &&) = delete; - std::function exit_function; - bool execute_on_destruction; + std::function exit_function; + bool execute_on_destruction; }; -} // namespace detail +} // namespace detail using Headers = std::multimap; using Params = std::multimap; -using Match = std::smatch; +using Match = std::smatch; using Progress = std::function; @@ -364,302 +367,302 @@ struct Response; using ResponseHandler = std::function; struct MultipartFormData { - std::string name; - std::string content; - std::string filename; - std::string content_type; + std::string name; + std::string content; + std::string filename; + std::string content_type; }; + using MultipartFormDataItems = std::vector; -using MultipartFormDataMap = std::multimap; +using MultipartFormDataMap = std::multimap; class DataSink { public: - DataSink() : os(&sb_), sb_(*this) {} - - DataSink(const DataSink &) = delete; - DataSink &operator=(const DataSink &) = delete; - DataSink(DataSink &&) = delete; - DataSink &operator=(DataSink &&) = delete; - - std::function write; - std::function done; - std::function done_with_trailer; - std::ostream os; - -private: - class data_sink_streambuf : public std::streambuf { - public: - explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {} - - protected: - std::streamsize xsputn(const char *s, std::streamsize n) { - sink_.write(s, static_cast(n)); - return n; + DataSink() : os(&sb_), sb_(*this) { } - private: - DataSink &sink_; - }; + DataSink(const DataSink &) = delete; + DataSink &operator=(const DataSink &) = delete; + DataSink(DataSink &&) = delete; + DataSink &operator=(DataSink &&) = delete; - data_sink_streambuf sb_; + std::function write; + std::function done; + std::function done_with_trailer; + std::ostream os; + +private: + class data_sink_streambuf : public std::streambuf { + public: + explicit data_sink_streambuf(DataSink &sink) : sink_(sink) { + } + + protected: + std::streamsize xsputn(const char *s, std::streamsize n) { + sink_.write(s, static_cast(n)); + return n; + } + + private: + DataSink &sink_; + }; + + data_sink_streambuf sb_; }; -using ContentProvider = - std::function; +using ContentProvider = std::function; -using ContentProviderWithoutLength = - std::function; +using ContentProviderWithoutLength = std::function; using ContentProviderResourceReleaser = std::function; struct MultipartFormDataProvider { - std::string name; - ContentProviderWithoutLength provider; - std::string filename; - std::string content_type; + std::string name; + ContentProviderWithoutLength provider; + std::string filename; + std::string content_type; }; + using MultipartFormDataProviderItems = std::vector; -using ContentReceiverWithProgress = - std::function; +using ContentReceiverWithProgress = std::function< + bool(const char *data, size_t data_length, uint64_t offset, uint64_t total_length)>; -using ContentReceiver = - std::function; +using ContentReceiver = std::function; -using MultipartContentHeader = - std::function; +using MultipartContentHeader = std::function; class ContentReader { public: - using Reader = std::function; - using MultipartReader = std::function; + using Reader = std::function; + using MultipartReader = std::function; - ContentReader(Reader reader, MultipartReader multipart_reader) - : reader_(std::move(reader)), - multipart_reader_(std::move(multipart_reader)) {} + ContentReader(Reader reader, MultipartReader multipart_reader) + : reader_(std::move(reader)), + multipart_reader_(std::move(multipart_reader)) { + } - bool operator()(MultipartContentHeader header, - ContentReceiver receiver) const { - return multipart_reader_(std::move(header), std::move(receiver)); - } + bool operator()(MultipartContentHeader header, ContentReceiver receiver) const { + return multipart_reader_(std::move(header), std::move(receiver)); + } - bool operator()(ContentReceiver receiver) const { - return reader_(std::move(receiver)); - } + bool operator()(ContentReceiver receiver) const { + return reader_(std::move(receiver)); + } - Reader reader_; - MultipartReader multipart_reader_; + Reader reader_; + MultipartReader multipart_reader_; }; -using Range = std::pair; +using Range = std::pair; using Ranges = std::vector; struct Request { - std::string method; - std::string path; - Headers headers; - std::string body; + std::string method; + std::string path; + Headers headers; + std::string body; - std::string remote_addr; - int remote_port = -1; - std::string local_addr; - int local_port = -1; + std::string remote_addr; + int remote_port = -1; + std::string local_addr; + int local_port = -1; - // for server - std::string version; - std::string target; - Params params; - MultipartFormDataMap files; - Ranges ranges; - Match matches; - std::unordered_map path_params; + // for server + std::string version; + std::string target; + Params params; + MultipartFormDataMap files; + Ranges ranges; + Match matches; + std::unordered_map path_params; - // for client - ResponseHandler response_handler; - ContentReceiverWithProgress content_receiver; - Progress progress; + // for client + ResponseHandler response_handler; + ContentReceiverWithProgress content_receiver; + Progress progress; #ifdef CPPHTTPLIB_OPENSSL_SUPPORT - const SSL *ssl = nullptr; + const SSL *ssl = nullptr; #endif - bool has_header(const std::string &key) const; - std::string get_header_value(const std::string &key, size_t id = 0) const; - template - T get_header_value(const std::string &key, size_t id = 0) const; - size_t get_header_value_count(const std::string &key) const; - void set_header(const std::string &key, const std::string &val); + bool has_header(const std::string &key) const; + std::string get_header_value(const std::string &key, size_t id = 0) const; + template T get_header_value(const std::string &key, size_t id = 0) const; + size_t get_header_value_count(const std::string &key) const; + void set_header(const std::string &key, const std::string &val); - bool has_param(const std::string &key) const; - std::string get_param_value(const std::string &key, size_t id = 0) const; - size_t get_param_value_count(const std::string &key) const; + bool has_param(const std::string &key) const; + std::string get_param_value(const std::string &key, size_t id = 0) const; + size_t get_param_value_count(const std::string &key) const; - bool is_multipart_form_data() const; + bool is_multipart_form_data() const; - bool has_file(const std::string &key) const; - MultipartFormData get_file_value(const std::string &key) const; - std::vector get_file_values(const std::string &key) const; + bool has_file(const std::string &key) const; + MultipartFormData get_file_value(const std::string &key) const; + std::vector get_file_values(const std::string &key) const; - // private members... - size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT; - size_t content_length_ = 0; - ContentProvider content_provider_; - bool is_chunked_content_provider_ = false; - size_t authorization_count_ = 0; + // private members... + size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT; + size_t content_length_ = 0; + ContentProvider content_provider_; + bool is_chunked_content_provider_ = false; + size_t authorization_count_ = 0; }; struct Response { - std::string version; - int status = -1; - std::string reason; - Headers headers; - std::string body; - std::string location; // Redirect location + std::string version; + int status = -1; + std::string reason; + Headers headers; + std::string body; + std::string location; // Redirect location - bool has_header(const std::string &key) const; - std::string get_header_value(const std::string &key, size_t id = 0) const; - template - T get_header_value(const std::string &key, size_t id = 0) const; - size_t get_header_value_count(const std::string &key) const; - void set_header(const std::string &key, const std::string &val); + bool has_header(const std::string &key) const; + std::string get_header_value(const std::string &key, size_t id = 0) const; + template T get_header_value(const std::string &key, size_t id = 0) const; + size_t get_header_value_count(const std::string &key) const; + void set_header(const std::string &key, const std::string &val); - void set_redirect(const std::string &url, int status = 302); - void set_content(const char *s, size_t n, const std::string &content_type); - void set_content(const std::string &s, const std::string &content_type); + void set_redirect(const std::string &url, int status = 302); + void set_content(const char *s, size_t n, const std::string &content_type); + void set_content(const std::string &s, const std::string &content_type); - void set_content_provider( - size_t length, const std::string &content_type, ContentProvider provider, - ContentProviderResourceReleaser resource_releaser = nullptr); + void set_content_provider(size_t length, + const std::string &content_type, + ContentProvider provider, + ContentProviderResourceReleaser resource_releaser = nullptr); - void set_content_provider( - const std::string &content_type, ContentProviderWithoutLength provider, - ContentProviderResourceReleaser resource_releaser = nullptr); + void set_content_provider(const std::string &content_type, + ContentProviderWithoutLength provider, + ContentProviderResourceReleaser resource_releaser = nullptr); - void set_chunked_content_provider( - const std::string &content_type, ContentProviderWithoutLength provider, - ContentProviderResourceReleaser resource_releaser = nullptr); + void set_chunked_content_provider(const std::string &content_type, + ContentProviderWithoutLength provider, + ContentProviderResourceReleaser resource_releaser = nullptr); - Response() = default; - Response(const Response &) = default; - Response &operator=(const Response &) = default; - Response(Response &&) = default; - Response &operator=(Response &&) = default; - ~Response() { - if (content_provider_resource_releaser_) { - content_provider_resource_releaser_(content_provider_success_); + Response() = default; + Response(const Response &) = default; + Response &operator=(const Response &) = default; + Response(Response &&) = default; + Response &operator=(Response &&) = default; + + ~Response() { + if (content_provider_resource_releaser_) { + content_provider_resource_releaser_(content_provider_success_); + } } - } - // private members... - size_t content_length_ = 0; - ContentProvider content_provider_; - ContentProviderResourceReleaser content_provider_resource_releaser_; - bool is_chunked_content_provider_ = false; - bool content_provider_success_ = false; + // private members... + size_t content_length_ = 0; + ContentProvider content_provider_; + ContentProviderResourceReleaser content_provider_resource_releaser_; + bool is_chunked_content_provider_ = false; + bool content_provider_success_ = false; }; class Stream { public: - virtual ~Stream() = default; + virtual ~Stream() = default; - virtual bool is_readable() const = 0; - virtual bool is_writable() const = 0; + virtual bool is_readable() const = 0; + virtual bool is_writable() const = 0; - virtual ssize_t read(char *ptr, size_t size) = 0; - virtual ssize_t write(const char *ptr, size_t size) = 0; - virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0; - virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0; - virtual socket_t socket() const = 0; + virtual ssize_t read(char *ptr, size_t size) = 0; + virtual ssize_t write(const char *ptr, size_t size) = 0; + virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0; + virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0; + virtual socket_t socket() const = 0; - template - ssize_t write_format(const char *fmt, const Args &...args); - ssize_t write(const char *ptr); - ssize_t write(const std::string &s); + template ssize_t write_format(const char *fmt, const Args &...args); + ssize_t write(const char *ptr); + ssize_t write(const std::string &s); }; class TaskQueue { public: - TaskQueue() = default; - virtual ~TaskQueue() = default; + TaskQueue() = default; + virtual ~TaskQueue() = default; - virtual void enqueue(std::function fn) = 0; - virtual void shutdown() = 0; + virtual void enqueue(std::function fn) = 0; + virtual void shutdown() = 0; - virtual void on_idle() {} + virtual void on_idle() { + } }; class ThreadPool : public TaskQueue { public: - explicit ThreadPool(size_t n) : shutdown_(false) { - while (n) { - threads_.emplace_back(worker(*this)); - n--; - } - } - - ThreadPool(const ThreadPool &) = delete; - ~ThreadPool() override = default; - - void enqueue(std::function fn) override { - { - std::unique_lock lock(mutex_); - jobs_.push_back(std::move(fn)); + explicit ThreadPool(size_t n) : shutdown_(false) { + while (n) { + threads_.emplace_back(worker(*this)); + n--; + } } - cond_.notify_one(); - } + ThreadPool(const ThreadPool &) = delete; + ~ThreadPool() override = default; - void shutdown() override { - // Stop all worker threads... - { - std::unique_lock lock(mutex_); - shutdown_ = true; - } - - cond_.notify_all(); - - // Join... - for (auto &t : threads_) { - t.join(); - } - } - -private: - struct worker { - explicit worker(ThreadPool &pool) : pool_(pool) {} - - void operator()() { - for (;;) { - std::function fn; + void enqueue(std::function fn) override { { - std::unique_lock lock(pool_.mutex_); - - pool_.cond_.wait( - lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; }); - - if (pool_.shutdown_ && pool_.jobs_.empty()) { break; } - - fn = std::move(pool_.jobs_.front()); - pool_.jobs_.pop_front(); + std::unique_lock lock(mutex_); + jobs_.push_back(std::move(fn)); } - assert(true == static_cast(fn)); - fn(); - } + cond_.notify_one(); } - ThreadPool &pool_; - }; - friend struct worker; + void shutdown() override { + // Stop all worker threads... + { + std::unique_lock lock(mutex_); + shutdown_ = true; + } - std::vector threads_; - std::list> jobs_; + cond_.notify_all(); - bool shutdown_; + // Join... + for (auto &t : threads_) { + t.join(); + } + } - std::condition_variable cond_; - std::mutex mutex_; +private: + struct worker { + explicit worker(ThreadPool &pool) : pool_(pool) { + } + + void operator()() { + for (;;) { + std::function fn; + { + std::unique_lock lock(pool_.mutex_); + + pool_.cond_.wait(lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; }); + + if (pool_.shutdown_ && pool_.jobs_.empty()) { + break; + } + + fn = std::move(pool_.jobs_.front()); + pool_.jobs_.pop_front(); + } + + assert(true == static_cast(fn)); + fn(); + } + } + + ThreadPool &pool_; + }; + friend struct worker; + + std::vector threads_; + std::list> jobs_; + + bool shutdown_; + + std::condition_variable cond_; + std::mutex mutex_; }; using Logger = std::function; @@ -672,10 +675,10 @@ namespace detail { class MatcherBase { public: - virtual ~MatcherBase() = default; + virtual ~MatcherBase() = default; - // Match request path and populate its matches and - virtual bool match(Request &request) const = 0; + // Match request path and populate its matches and + virtual bool match(Request &request) const = 0; }; /** @@ -698,24 +701,24 @@ public: */ class PathParamsMatcher : public MatcherBase { public: - PathParamsMatcher(const std::string &pattern); + PathParamsMatcher(const std::string &pattern); - bool match(Request &request) const override; + bool match(Request &request) const override; private: - static constexpr char marker = ':'; - // Treat segment separators as the end of path parameter capture - // Does not need to handle query parameters as they are parsed before path - // matching - static constexpr char separator = '/'; + static constexpr char marker = ':'; + // Treat segment separators as the end of path parameter capture + // Does not need to handle query parameters as they are parsed before path + // matching + static constexpr char separator = '/'; - // Contains static path fragments to match against, excluding the '/' after - // path params - // Fragments are separated by path params - std::vector static_fragments_; - // Stores the names of the path parameters to be used as keys in the - // Request::path_params map - std::vector param_names_; + // Contains static path fragments to match against, excluding the '/' after + // path params + // Fragments are separated by path params + std::vector static_fragments_; + // Stores the names of the path parameters to be used as keys in the + // Request::path_params map + std::vector param_names_; }; /** @@ -728,229 +731,224 @@ private: */ class RegexMatcher : public MatcherBase { public: - RegexMatcher(const std::string &pattern) : regex_(pattern) {} + RegexMatcher(const std::string &pattern) : regex_(pattern) { + } - bool match(Request &request) const override; + bool match(Request &request) const override; private: - std::regex regex_; + std::regex regex_; }; -} // namespace detail +} // namespace detail class Server { public: - using Handler = std::function; + using Handler = std::function; - using ExceptionHandler = - std::function; + using ExceptionHandler = std::function; - enum class HandlerResponse { - Handled, - Unhandled, - }; - using HandlerWithResponse = - std::function; + enum class HandlerResponse { + Handled, + Unhandled, + }; + using HandlerWithResponse = std::function; - using HandlerWithContentReader = std::function; + using HandlerWithContentReader = std::function< + void(const Request &, Response &, const ContentReader &content_reader)>; - using Expect100ContinueHandler = - std::function; + using Expect100ContinueHandler = std::function; - Server(); + Server(); - virtual ~Server(); + virtual ~Server(); - virtual bool is_valid() const; + virtual bool is_valid() const; - Server &Get(const std::string &pattern, Handler handler); - Server &Post(const std::string &pattern, Handler handler); - Server &Post(const std::string &pattern, HandlerWithContentReader handler); - Server &Put(const std::string &pattern, Handler handler); - Server &Put(const std::string &pattern, HandlerWithContentReader handler); - Server &Patch(const std::string &pattern, Handler handler); - Server &Patch(const std::string &pattern, HandlerWithContentReader handler); - Server &Delete(const std::string &pattern, Handler handler); - Server &Delete(const std::string &pattern, HandlerWithContentReader handler); - Server &Options(const std::string &pattern, Handler handler); + Server &Get(const std::string &pattern, Handler handler); + Server &Post(const std::string &pattern, Handler handler); + Server &Post(const std::string &pattern, HandlerWithContentReader handler); + Server &Put(const std::string &pattern, Handler handler); + Server &Put(const std::string &pattern, HandlerWithContentReader handler); + Server &Patch(const std::string &pattern, Handler handler); + Server &Patch(const std::string &pattern, HandlerWithContentReader handler); + Server &Delete(const std::string &pattern, Handler handler); + Server &Delete(const std::string &pattern, HandlerWithContentReader handler); + Server &Options(const std::string &pattern, Handler handler); - bool set_base_dir(const std::string &dir, - const std::string &mount_point = std::string()); - bool set_mount_point(const std::string &mount_point, const std::string &dir, - Headers headers = Headers()); - bool remove_mount_point(const std::string &mount_point); - Server &set_file_extension_and_mimetype_mapping(const std::string &ext, - const std::string &mime); - Server &set_file_request_handler(Handler handler); + bool set_base_dir(const std::string &dir, const std::string &mount_point = std::string()); + bool set_mount_point(const std::string &mount_point, const std::string &dir, Headers headers = Headers()); + bool remove_mount_point(const std::string &mount_point); + Server &set_file_extension_and_mimetype_mapping(const std::string &ext, const std::string &mime); + Server &set_file_request_handler(Handler handler); - Server &set_error_handler(HandlerWithResponse handler); - Server &set_error_handler(Handler handler); - Server &set_exception_handler(ExceptionHandler handler); - Server &set_pre_routing_handler(HandlerWithResponse handler); - Server &set_post_routing_handler(Handler handler); + Server &set_error_handler(HandlerWithResponse handler); + Server &set_error_handler(Handler handler); + Server &set_exception_handler(ExceptionHandler handler); + Server &set_pre_routing_handler(HandlerWithResponse handler); + Server &set_post_routing_handler(Handler handler); - Server &set_expect_100_continue_handler(Expect100ContinueHandler handler); - Server &set_logger(Logger logger); + Server &set_expect_100_continue_handler(Expect100ContinueHandler handler); + Server &set_logger(Logger logger); - Server &set_address_family(int family); - Server &set_tcp_nodelay(bool on); - Server &set_socket_options(SocketOptions socket_options); + Server &set_address_family(int family); + Server &set_tcp_nodelay(bool on); + Server &set_socket_options(SocketOptions socket_options); - Server &set_default_headers(Headers headers); + Server &set_default_headers(Headers headers); - Server &set_keep_alive_max_count(size_t count); - Server &set_keep_alive_timeout(time_t sec); + Server &set_keep_alive_max_count(size_t count); + Server &set_keep_alive_timeout(time_t sec); - Server &set_read_timeout(time_t sec, time_t usec = 0); - template - Server &set_read_timeout(const std::chrono::duration &duration); + Server &set_read_timeout(time_t sec, time_t usec = 0); + template Server &set_read_timeout(const std::chrono::duration &duration); - Server &set_write_timeout(time_t sec, time_t usec = 0); - template - Server &set_write_timeout(const std::chrono::duration &duration); + Server &set_write_timeout(time_t sec, time_t usec = 0); + template Server &set_write_timeout(const std::chrono::duration &duration); - Server &set_idle_interval(time_t sec, time_t usec = 0); - template - Server &set_idle_interval(const std::chrono::duration &duration); + Server &set_idle_interval(time_t sec, time_t usec = 0); + template Server &set_idle_interval(const std::chrono::duration &duration); - Server &set_payload_max_length(size_t length); + Server &set_payload_max_length(size_t length); - bool bind_to_port(const std::string &host, int port, int socket_flags = 0); - int bind_to_any_port(const std::string &host, int socket_flags = 0); - bool listen_after_bind(); + bool bind_to_port(const std::string &host, int port, int socket_flags = 0); + int bind_to_any_port(const std::string &host, int socket_flags = 0); + bool listen_after_bind(); - bool listen(const std::string &host, int port, int socket_flags = 0); + bool listen(const std::string &host, int port, int socket_flags = 0); - bool is_running() const; - void wait_until_ready() const; - void stop(); + bool is_running() const; + void wait_until_ready() const; + void stop(); - std::function new_task_queue; + std::function new_task_queue; protected: - bool process_request(Stream &strm, bool close_connection, - bool &connection_closed, - const std::function &setup_request); + bool process_request(Stream &strm, + bool close_connection, + bool &connection_closed, + const std::function &setup_request); - std::atomic svr_sock_{INVALID_SOCKET}; - size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT; - time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND; - time_t read_timeout_sec_ = CPPHTTPLIB_READ_TIMEOUT_SECOND; - time_t read_timeout_usec_ = CPPHTTPLIB_READ_TIMEOUT_USECOND; - time_t write_timeout_sec_ = CPPHTTPLIB_WRITE_TIMEOUT_SECOND; - time_t write_timeout_usec_ = CPPHTTPLIB_WRITE_TIMEOUT_USECOND; - time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND; - time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND; - size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH; + std::atomic svr_sock_ {INVALID_SOCKET}; + size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT; + time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND; + time_t read_timeout_sec_ = CPPHTTPLIB_READ_TIMEOUT_SECOND; + time_t read_timeout_usec_ = CPPHTTPLIB_READ_TIMEOUT_USECOND; + time_t write_timeout_sec_ = CPPHTTPLIB_WRITE_TIMEOUT_SECOND; + time_t write_timeout_usec_ = CPPHTTPLIB_WRITE_TIMEOUT_USECOND; + time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND; + time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND; + size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH; private: - using Handlers = - std::vector, Handler>>; - using HandlersForContentReader = - std::vector, - HandlerWithContentReader>>; + using Handlers = std::vector, Handler>>; + using HandlersForContentReader = std::vector< + std::pair, HandlerWithContentReader>>; - static std::unique_ptr - make_matcher(const std::string &pattern); + static std::unique_ptr make_matcher(const std::string &pattern); - socket_t create_server_socket(const std::string &host, int port, - int socket_flags, - SocketOptions socket_options) const; - int bind_internal(const std::string &host, int port, int socket_flags); - bool listen_internal(); + socket_t create_server_socket(const std::string &host, + int port, + int socket_flags, + SocketOptions socket_options) const; + int bind_internal(const std::string &host, int port, int socket_flags); + bool listen_internal(); - bool routing(Request &req, Response &res, Stream &strm); - bool handle_file_request(const Request &req, Response &res, - bool head = false); - bool dispatch_request(Request &req, Response &res, const Handlers &handlers); - bool - dispatch_request_for_content_reader(Request &req, Response &res, - ContentReader content_reader, - const HandlersForContentReader &handlers); + bool routing(Request &req, Response &res, Stream &strm); + bool handle_file_request(const Request &req, Response &res, bool head = false); + bool dispatch_request(Request &req, Response &res, const Handlers &handlers); + bool dispatch_request_for_content_reader(Request &req, + Response &res, + ContentReader content_reader, + const HandlersForContentReader &handlers); - bool parse_request_line(const char *s, Request &req); - void apply_ranges(const Request &req, Response &res, - std::string &content_type, std::string &boundary); - bool write_response(Stream &strm, bool close_connection, const Request &req, - Response &res); - bool write_response_with_content(Stream &strm, bool close_connection, - const Request &req, Response &res); - bool write_response_core(Stream &strm, bool close_connection, - const Request &req, Response &res, - bool need_apply_ranges); - bool write_content_with_provider(Stream &strm, const Request &req, - Response &res, const std::string &boundary, - const std::string &content_type); - bool read_content(Stream &strm, Request &req, Response &res); - bool - read_content_with_content_receiver(Stream &strm, Request &req, Response &res, - ContentReceiver receiver, - MultipartContentHeader multipart_header, - ContentReceiver multipart_receiver); - bool read_content_core(Stream &strm, Request &req, Response &res, - ContentReceiver receiver, - MultipartContentHeader multipart_header, - ContentReceiver multipart_receiver); + bool parse_request_line(const char *s, Request &req); + void apply_ranges(const Request &req, Response &res, std::string &content_type, std::string &boundary); + bool write_response(Stream &strm, bool close_connection, const Request &req, Response &res); + bool write_response_with_content(Stream &strm, bool close_connection, const Request &req, Response &res); + bool write_response_core(Stream &strm, + bool close_connection, + const Request &req, + Response &res, + bool need_apply_ranges); + bool write_content_with_provider(Stream &strm, + const Request &req, + Response &res, + const std::string &boundary, + const std::string &content_type); + bool read_content(Stream &strm, Request &req, Response &res); + bool read_content_with_content_receiver(Stream &strm, + Request &req, + Response &res, + ContentReceiver receiver, + MultipartContentHeader multipart_header, + ContentReceiver multipart_receiver); + bool read_content_core(Stream &strm, + Request &req, + Response &res, + ContentReceiver receiver, + MultipartContentHeader multipart_header, + ContentReceiver multipart_receiver); - virtual bool process_and_close_socket(socket_t sock); + virtual bool process_and_close_socket(socket_t sock); - std::atomic is_running_{false}; - std::atomic done_{false}; + std::atomic is_running_ {false}; + std::atomic done_ {false}; - struct MountPointEntry { - std::string mount_point; - std::string base_dir; - Headers headers; - }; - std::vector base_dirs_; - std::map file_extension_and_mimetype_map_; - Handler file_request_handler_; + struct MountPointEntry { + std::string mount_point; + std::string base_dir; + Headers headers; + }; - Handlers get_handlers_; - Handlers post_handlers_; - HandlersForContentReader post_handlers_for_content_reader_; - Handlers put_handlers_; - HandlersForContentReader put_handlers_for_content_reader_; - Handlers patch_handlers_; - HandlersForContentReader patch_handlers_for_content_reader_; - Handlers delete_handlers_; - HandlersForContentReader delete_handlers_for_content_reader_; - Handlers options_handlers_; + std::vector base_dirs_; + std::map file_extension_and_mimetype_map_; + Handler file_request_handler_; - HandlerWithResponse error_handler_; - ExceptionHandler exception_handler_; - HandlerWithResponse pre_routing_handler_; - Handler post_routing_handler_; - Expect100ContinueHandler expect_100_continue_handler_; + Handlers get_handlers_; + Handlers post_handlers_; + HandlersForContentReader post_handlers_for_content_reader_; + Handlers put_handlers_; + HandlersForContentReader put_handlers_for_content_reader_; + Handlers patch_handlers_; + HandlersForContentReader patch_handlers_for_content_reader_; + Handlers delete_handlers_; + HandlersForContentReader delete_handlers_for_content_reader_; + Handlers options_handlers_; - Logger logger_; + HandlerWithResponse error_handler_; + ExceptionHandler exception_handler_; + HandlerWithResponse pre_routing_handler_; + Handler post_routing_handler_; + Expect100ContinueHandler expect_100_continue_handler_; - int address_family_ = AF_UNSPEC; - bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY; - SocketOptions socket_options_ = default_socket_options; + Logger logger_; - Headers default_headers_; + int address_family_ = AF_UNSPEC; + bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY; + SocketOptions socket_options_ = default_socket_options; + + Headers default_headers_; }; enum class Error { - Success = 0, - Unknown, - Connection, - BindIPAddress, - Read, - Write, - ExceedRedirectCount, - Canceled, - SSLConnection, - SSLLoadingCerts, - SSLServerVerification, - UnsupportedMultipartBoundaryChars, - Compression, - ConnectionTimeout, + Success = 0, + Unknown, + Connection, + BindIPAddress, + Read, + Write, + ExceedRedirectCount, + Canceled, + SSLConnection, + SSLLoadingCerts, + SSLServerVerification, + UnsupportedMultipartBoundaryChars, + Compression, + ConnectionTimeout, - // For internal use only - SSLPeerCouldBeClosed_, + // For internal use only + SSLPeerCouldBeClosed_, }; std::string to_string(const Error error); @@ -959,733 +957,804 @@ std::ostream &operator<<(std::ostream &os, const Error &obj); class Result { public: - Result() = default; - Result(std::unique_ptr &&res, Error err, - Headers &&request_headers = Headers{}) - : res_(std::move(res)), err_(err), - request_headers_(std::move(request_headers)) {} - // Response - operator bool() const { return res_ != nullptr; } - bool operator==(std::nullptr_t) const { return res_ == nullptr; } - bool operator!=(std::nullptr_t) const { return res_ != nullptr; } - const Response &value() const { return *res_; } - Response &value() { return *res_; } - const Response &operator*() const { return *res_; } - Response &operator*() { return *res_; } - const Response *operator->() const { return res_.get(); } - Response *operator->() { return res_.get(); } + Result() = default; - // Error - Error error() const { return err_; } + Result(std::unique_ptr &&res, Error err, Headers &&request_headers = Headers {}) + : res_(std::move(res)), + err_(err), + request_headers_(std::move(request_headers)) { + } - // Request Headers - bool has_request_header(const std::string &key) const; - std::string get_request_header_value(const std::string &key, - size_t id = 0) const; - template - T get_request_header_value(const std::string &key, size_t id = 0) const; - size_t get_request_header_value_count(const std::string &key) const; + // Response + operator bool() const { + return res_ != nullptr; + } + + bool operator==(std::nullptr_t) const { + return res_ == nullptr; + } + + bool operator!=(std::nullptr_t) const { + return res_ != nullptr; + } + + const Response &value() const { + return *res_; + } + + Response &value() { + return *res_; + } + + const Response &operator*() const { + return *res_; + } + + Response &operator*() { + return *res_; + } + + const Response *operator->() const { + return res_.get(); + } + + Response *operator->() { + return res_.get(); + } + + // Error + Error error() const { + return err_; + } + + // Request Headers + bool has_request_header(const std::string &key) const; + std::string get_request_header_value(const std::string &key, size_t id = 0) const; + template T get_request_header_value(const std::string &key, size_t id = 0) const; + size_t get_request_header_value_count(const std::string &key) const; private: - std::unique_ptr res_; - Error err_ = Error::Unknown; - Headers request_headers_; + std::unique_ptr res_; + Error err_ = Error::Unknown; + Headers request_headers_; }; class ClientImpl { public: - explicit ClientImpl(const std::string &host); + explicit ClientImpl(const std::string &host); - explicit ClientImpl(const std::string &host, int port); + explicit ClientImpl(const std::string &host, int port); - explicit ClientImpl(const std::string &host, int port, - const std::string &client_cert_path, - const std::string &client_key_path); + explicit ClientImpl(const std::string &host, + int port, + const std::string &client_cert_path, + const std::string &client_key_path); - virtual ~ClientImpl(); + virtual ~ClientImpl(); - virtual bool is_valid() const; + virtual bool is_valid() const; - Result Get(const std::string &path); - Result Get(const std::string &path, const Headers &headers); - Result Get(const std::string &path, Progress progress); - Result Get(const std::string &path, const Headers &headers, - Progress progress); - Result Get(const std::string &path, ContentReceiver content_receiver); - Result Get(const std::string &path, const Headers &headers, - ContentReceiver content_receiver); - Result Get(const std::string &path, ContentReceiver content_receiver, - Progress progress); - Result Get(const std::string &path, const Headers &headers, - ContentReceiver content_receiver, Progress progress); - Result Get(const std::string &path, ResponseHandler response_handler, - ContentReceiver content_receiver); - Result Get(const std::string &path, const Headers &headers, - ResponseHandler response_handler, - ContentReceiver content_receiver); - Result Get(const std::string &path, ResponseHandler response_handler, - ContentReceiver content_receiver, Progress progress); - Result Get(const std::string &path, const Headers &headers, - ResponseHandler response_handler, ContentReceiver content_receiver, - Progress progress); + Result Get(const std::string &path); + Result Get(const std::string &path, const Headers &headers); + Result Get(const std::string &path, Progress progress); + Result Get(const std::string &path, const Headers &headers, Progress progress); + Result Get(const std::string &path, ContentReceiver content_receiver); + Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver); + Result Get(const std::string &path, ContentReceiver content_receiver, Progress progress); + Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, Progress progress); + Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver); + Result Get(const std::string &path, + const Headers &headers, + ResponseHandler response_handler, + ContentReceiver content_receiver); + Result Get(const std::string &path, + ResponseHandler response_handler, + ContentReceiver content_receiver, + Progress progress); + Result Get(const std::string &path, + const Headers &headers, + ResponseHandler response_handler, + ContentReceiver content_receiver, + Progress progress); - Result Get(const std::string &path, const Params ¶ms, - const Headers &headers, Progress progress = nullptr); - Result Get(const std::string &path, const Params ¶ms, - const Headers &headers, ContentReceiver content_receiver, - Progress progress = nullptr); - Result Get(const std::string &path, const Params ¶ms, - const Headers &headers, ResponseHandler response_handler, - ContentReceiver content_receiver, Progress progress = nullptr); + Result Get(const std::string &path, const Params ¶ms, const Headers &headers, Progress progress = nullptr); + Result Get(const std::string &path, + const Params ¶ms, + const Headers &headers, + ContentReceiver content_receiver, + Progress progress = nullptr); + Result Get(const std::string &path, + const Params ¶ms, + const Headers &headers, + ResponseHandler response_handler, + ContentReceiver content_receiver, + Progress progress = nullptr); - Result Head(const std::string &path); - Result Head(const std::string &path, const Headers &headers); + Result Head(const std::string &path); + Result Head(const std::string &path, const Headers &headers); - Result Post(const std::string &path); - Result Post(const std::string &path, const Headers &headers); - Result Post(const std::string &path, const char *body, size_t content_length, - const std::string &content_type); - Result Post(const std::string &path, const Headers &headers, const char *body, - size_t content_length, const std::string &content_type); - Result Post(const std::string &path, const std::string &body, - const std::string &content_type); - Result Post(const std::string &path, const Headers &headers, - const std::string &body, const std::string &content_type); - Result Post(const std::string &path, size_t content_length, - ContentProvider content_provider, - const std::string &content_type); - Result Post(const std::string &path, - ContentProviderWithoutLength content_provider, - const std::string &content_type); - Result Post(const std::string &path, const Headers &headers, - size_t content_length, ContentProvider content_provider, - const std::string &content_type); - Result Post(const std::string &path, const Headers &headers, - ContentProviderWithoutLength content_provider, - const std::string &content_type); - Result Post(const std::string &path, const Params ¶ms); - Result Post(const std::string &path, const Headers &headers, - const Params ¶ms); - Result Post(const std::string &path, const MultipartFormDataItems &items); - Result Post(const std::string &path, const Headers &headers, - const MultipartFormDataItems &items); - Result Post(const std::string &path, const Headers &headers, - const MultipartFormDataItems &items, const std::string &boundary); - Result Post(const std::string &path, const Headers &headers, - const MultipartFormDataItems &items, - const MultipartFormDataProviderItems &provider_items); - - Result Put(const std::string &path); - Result Put(const std::string &path, const char *body, size_t content_length, - const std::string &content_type); - Result Put(const std::string &path, const Headers &headers, const char *body, - size_t content_length, const std::string &content_type); - Result Put(const std::string &path, const std::string &body, - const std::string &content_type); - Result Put(const std::string &path, const Headers &headers, - const std::string &body, const std::string &content_type); - Result Put(const std::string &path, size_t content_length, - ContentProvider content_provider, const std::string &content_type); - Result Put(const std::string &path, - ContentProviderWithoutLength content_provider, - const std::string &content_type); - Result Put(const std::string &path, const Headers &headers, - size_t content_length, ContentProvider content_provider, - const std::string &content_type); - Result Put(const std::string &path, const Headers &headers, - ContentProviderWithoutLength content_provider, - const std::string &content_type); - Result Put(const std::string &path, const Params ¶ms); - Result Put(const std::string &path, const Headers &headers, - const Params ¶ms); - Result Put(const std::string &path, const MultipartFormDataItems &items); - Result Put(const std::string &path, const Headers &headers, - const MultipartFormDataItems &items); - Result Put(const std::string &path, const Headers &headers, - const MultipartFormDataItems &items, const std::string &boundary); - Result Put(const std::string &path, const Headers &headers, - const MultipartFormDataItems &items, - const MultipartFormDataProviderItems &provider_items); - - Result Patch(const std::string &path); - Result Patch(const std::string &path, const char *body, size_t content_length, - const std::string &content_type); - Result Patch(const std::string &path, const Headers &headers, - const char *body, size_t content_length, - const std::string &content_type); - Result Patch(const std::string &path, const std::string &body, - const std::string &content_type); - Result Patch(const std::string &path, const Headers &headers, - const std::string &body, const std::string &content_type); - Result Patch(const std::string &path, size_t content_length, - ContentProvider content_provider, - const std::string &content_type); - Result Patch(const std::string &path, - ContentProviderWithoutLength content_provider, - const std::string &content_type); - Result Patch(const std::string &path, const Headers &headers, - size_t content_length, ContentProvider content_provider, - const std::string &content_type); - Result Patch(const std::string &path, const Headers &headers, - ContentProviderWithoutLength content_provider, - const std::string &content_type); - - Result Delete(const std::string &path); - Result Delete(const std::string &path, const Headers &headers); - Result Delete(const std::string &path, const char *body, - size_t content_length, const std::string &content_type); - Result Delete(const std::string &path, const Headers &headers, - const char *body, size_t content_length, + Result Post(const std::string &path); + Result Post(const std::string &path, const Headers &headers); + Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type); + Result Post(const std::string &path, + const Headers &headers, + const char *body, + size_t content_length, const std::string &content_type); - Result Delete(const std::string &path, const std::string &body, + Result Post(const std::string &path, const std::string &body, const std::string &content_type); + Result Post(const std::string &path, + const Headers &headers, + const std::string &body, const std::string &content_type); - Result Delete(const std::string &path, const Headers &headers, - const std::string &body, const std::string &content_type); + Result Post(const std::string &path, + size_t content_length, + ContentProvider content_provider, + const std::string &content_type); + Result Post(const std::string &path, + ContentProviderWithoutLength content_provider, + const std::string &content_type); + Result Post(const std::string &path, + const Headers &headers, + size_t content_length, + ContentProvider content_provider, + const std::string &content_type); + Result Post(const std::string &path, + const Headers &headers, + ContentProviderWithoutLength content_provider, + const std::string &content_type); + Result Post(const std::string &path, const Params ¶ms); + Result Post(const std::string &path, const Headers &headers, const Params ¶ms); + Result Post(const std::string &path, const MultipartFormDataItems &items); + Result Post(const std::string &path, const Headers &headers, const MultipartFormDataItems &items); + Result Post(const std::string &path, + const Headers &headers, + const MultipartFormDataItems &items, + const std::string &boundary); + Result Post(const std::string &path, + const Headers &headers, + const MultipartFormDataItems &items, + const MultipartFormDataProviderItems &provider_items); - Result Options(const std::string &path); - Result Options(const std::string &path, const Headers &headers); + Result Put(const std::string &path); + Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type); + Result Put(const std::string &path, + const Headers &headers, + const char *body, + size_t content_length, + const std::string &content_type); + Result Put(const std::string &path, const std::string &body, const std::string &content_type); + Result Put(const std::string &path, + const Headers &headers, + const std::string &body, + const std::string &content_type); + Result Put(const std::string &path, + size_t content_length, + ContentProvider content_provider, + const std::string &content_type); + Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type); + Result Put(const std::string &path, + const Headers &headers, + size_t content_length, + ContentProvider content_provider, + const std::string &content_type); + Result Put(const std::string &path, + const Headers &headers, + ContentProviderWithoutLength content_provider, + const std::string &content_type); + Result Put(const std::string &path, const Params ¶ms); + Result Put(const std::string &path, const Headers &headers, const Params ¶ms); + Result Put(const std::string &path, const MultipartFormDataItems &items); + Result Put(const std::string &path, const Headers &headers, const MultipartFormDataItems &items); + Result Put(const std::string &path, + const Headers &headers, + const MultipartFormDataItems &items, + const std::string &boundary); + Result Put(const std::string &path, + const Headers &headers, + const MultipartFormDataItems &items, + const MultipartFormDataProviderItems &provider_items); - bool send(Request &req, Response &res, Error &error); - Result send(const Request &req); + Result Patch(const std::string &path); + Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type); + Result Patch(const std::string &path, + const Headers &headers, + const char *body, + size_t content_length, + const std::string &content_type); + Result Patch(const std::string &path, const std::string &body, const std::string &content_type); + Result Patch(const std::string &path, + const Headers &headers, + const std::string &body, + const std::string &content_type); + Result Patch(const std::string &path, + size_t content_length, + ContentProvider content_provider, + const std::string &content_type); + Result Patch(const std::string &path, + ContentProviderWithoutLength content_provider, + const std::string &content_type); + Result Patch(const std::string &path, + const Headers &headers, + size_t content_length, + ContentProvider content_provider, + const std::string &content_type); + Result Patch(const std::string &path, + const Headers &headers, + ContentProviderWithoutLength content_provider, + const std::string &content_type); - void stop(); + Result Delete(const std::string &path); + Result Delete(const std::string &path, const Headers &headers); + Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type); + Result Delete(const std::string &path, + const Headers &headers, + const char *body, + size_t content_length, + const std::string &content_type); + Result Delete(const std::string &path, const std::string &body, const std::string &content_type); + Result Delete(const std::string &path, + const Headers &headers, + const std::string &body, + const std::string &content_type); - std::string host() const; - int port() const; + Result Options(const std::string &path); + Result Options(const std::string &path, const Headers &headers); - size_t is_socket_open() const; - socket_t socket() const; + bool send(Request &req, Response &res, Error &error); + Result send(const Request &req); - void set_hostname_addr_map(std::map addr_map); + void stop(); - void set_default_headers(Headers headers); + std::string host() const; + int port() const; - void set_address_family(int family); - void set_tcp_nodelay(bool on); - void set_socket_options(SocketOptions socket_options); + size_t is_socket_open() const; + socket_t socket() const; - void set_connection_timeout(time_t sec, time_t usec = 0); - template - void - set_connection_timeout(const std::chrono::duration &duration); + void set_hostname_addr_map(std::map addr_map); - void set_read_timeout(time_t sec, time_t usec = 0); - template - void set_read_timeout(const std::chrono::duration &duration); + void set_default_headers(Headers headers); - void set_write_timeout(time_t sec, time_t usec = 0); - template - void set_write_timeout(const std::chrono::duration &duration); + void set_address_family(int family); + void set_tcp_nodelay(bool on); + void set_socket_options(SocketOptions socket_options); - void set_basic_auth(const std::string &username, const std::string &password); - void set_bearer_token_auth(const std::string &token); + void set_connection_timeout(time_t sec, time_t usec = 0); + template void set_connection_timeout(const std::chrono::duration &duration); + + void set_read_timeout(time_t sec, time_t usec = 0); + template void set_read_timeout(const std::chrono::duration &duration); + + void set_write_timeout(time_t sec, time_t usec = 0); + template void set_write_timeout(const std::chrono::duration &duration); + + void set_basic_auth(const std::string &username, const std::string &password); + void set_bearer_token_auth(const std::string &token); #ifdef CPPHTTPLIB_OPENSSL_SUPPORT - void set_digest_auth(const std::string &username, - const std::string &password); + void set_digest_auth(const std::string &username, const std::string &password); #endif - void set_keep_alive(bool on); - void set_follow_location(bool on); + void set_keep_alive(bool on); + void set_follow_location(bool on); - void set_url_encode(bool on); + void set_url_encode(bool on); - void set_compress(bool on); + void set_compress(bool on); - void set_decompress(bool on); + void set_decompress(bool on); - void set_interface(const std::string &intf); + void set_interface(const std::string &intf); - void set_proxy(const std::string &host, int port); - void set_proxy_basic_auth(const std::string &username, - const std::string &password); - void set_proxy_bearer_token_auth(const std::string &token); + void set_proxy(const std::string &host, int port); + void set_proxy_basic_auth(const std::string &username, const std::string &password); + void set_proxy_bearer_token_auth(const std::string &token); + void set_post_connect_callback(detail::POSTSOCKETCONNECTCB cb); #ifdef CPPHTTPLIB_OPENSSL_SUPPORT - void set_proxy_digest_auth(const std::string &username, - const std::string &password); + void set_proxy_digest_auth(const std::string &username, const std::string &password); #endif #ifdef CPPHTTPLIB_OPENSSL_SUPPORT - void set_ca_cert_path(const std::string &ca_cert_file_path, - const std::string &ca_cert_dir_path = std::string()); - void set_ca_cert_store(X509_STORE *ca_cert_store); - X509_STORE *create_ca_cert_store(const char *ca_cert, std::size_t size); + void set_ca_cert_path(const std::string &ca_cert_file_path, const std::string &ca_cert_dir_path = std::string()); + void set_ca_cert_store(X509_STORE *ca_cert_store); + X509_STORE *create_ca_cert_store(const char *ca_cert, std::size_t size); #endif #ifdef CPPHTTPLIB_OPENSSL_SUPPORT - void enable_server_certificate_verification(bool enabled); + void enable_server_certificate_verification(bool enabled); #endif - void set_logger(Logger logger); + void set_logger(Logger logger); protected: - struct Socket { - socket_t sock = INVALID_SOCKET; + struct Socket { + socket_t sock = INVALID_SOCKET; #ifdef CPPHTTPLIB_OPENSSL_SUPPORT - SSL *ssl = nullptr; + SSL *ssl = nullptr; #endif - bool is_open() const { return sock != INVALID_SOCKET; } - }; + bool is_open() const { + return sock != INVALID_SOCKET; + } + }; - virtual bool create_and_connect_socket(Socket &socket, Error &error); + virtual bool create_and_connect_socket(Socket &socket, Error &error); - // All of: - // shutdown_ssl - // shutdown_socket - // close_socket - // should ONLY be called when socket_mutex_ is locked. - // Also, shutdown_ssl and close_socket should also NOT be called concurrently - // with a DIFFERENT thread sending requests using that socket. - virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully); - void shutdown_socket(Socket &socket); - void close_socket(Socket &socket); + // All of: + // shutdown_ssl + // shutdown_socket + // close_socket + // should ONLY be called when socket_mutex_ is locked. + // Also, shutdown_ssl and close_socket should also NOT be called concurrently + // with a DIFFERENT thread sending requests using that socket. + virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully); + void shutdown_socket(Socket &socket); + void close_socket(Socket &socket); - bool process_request(Stream &strm, Request &req, Response &res, - bool close_connection, Error &error); + bool process_request(Stream &strm, Request &req, Response &res, bool close_connection, Error &error); - bool write_content_with_provider(Stream &strm, const Request &req, - Error &error); + bool write_content_with_provider(Stream &strm, const Request &req, Error &error); - void copy_settings(const ClientImpl &rhs); + void copy_settings(const ClientImpl &rhs); - // Socket endpoint information - const std::string host_; - const int port_; - const std::string host_and_port_; + // Socket endpoint information + const std::string host_; + const int port_; + const std::string host_and_port_; - // Current open socket - Socket socket_; - mutable std::mutex socket_mutex_; - std::recursive_mutex request_mutex_; + // Current open socket + Socket socket_; + mutable std::mutex socket_mutex_; + std::recursive_mutex request_mutex_; - // These are all protected under socket_mutex - size_t socket_requests_in_flight_ = 0; - std::thread::id socket_requests_are_from_thread_ = std::thread::id(); - bool socket_should_be_closed_when_request_is_done_ = false; + // These are all protected under socket_mutex + size_t socket_requests_in_flight_ = 0; + std::thread::id socket_requests_are_from_thread_ = std::thread::id(); + bool socket_should_be_closed_when_request_is_done_ = false; - // Hostname-IP map - std::map addr_map_; + // Hostname-IP map + std::map addr_map_; - // Default headers - Headers default_headers_; + // Default headers + Headers default_headers_; - // Settings - std::string client_cert_path_; - std::string client_key_path_; + // Settings + std::string client_cert_path_; + std::string client_key_path_; - time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND; - time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND; - time_t read_timeout_sec_ = CPPHTTPLIB_READ_TIMEOUT_SECOND; - time_t read_timeout_usec_ = CPPHTTPLIB_READ_TIMEOUT_USECOND; - time_t write_timeout_sec_ = CPPHTTPLIB_WRITE_TIMEOUT_SECOND; - time_t write_timeout_usec_ = CPPHTTPLIB_WRITE_TIMEOUT_USECOND; + time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND; + time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND; + time_t read_timeout_sec_ = CPPHTTPLIB_READ_TIMEOUT_SECOND; + time_t read_timeout_usec_ = CPPHTTPLIB_READ_TIMEOUT_USECOND; + time_t write_timeout_sec_ = CPPHTTPLIB_WRITE_TIMEOUT_SECOND; + time_t write_timeout_usec_ = CPPHTTPLIB_WRITE_TIMEOUT_USECOND; - std::string basic_auth_username_; - std::string basic_auth_password_; - std::string bearer_token_auth_token_; + std::string basic_auth_username_; + std::string basic_auth_password_; + std::string bearer_token_auth_token_; #ifdef CPPHTTPLIB_OPENSSL_SUPPORT - std::string digest_auth_username_; - std::string digest_auth_password_; + std::string digest_auth_username_; + std::string digest_auth_password_; #endif - bool keep_alive_ = false; - bool follow_location_ = false; + bool keep_alive_ = false; + bool follow_location_ = false; - bool url_encode_ = true; + bool url_encode_ = true; - int address_family_ = AF_UNSPEC; - bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY; - SocketOptions socket_options_ = nullptr; + int address_family_ = AF_UNSPEC; + bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY; + SocketOptions socket_options_ = nullptr; - bool compress_ = false; - bool decompress_ = true; + bool compress_ = false; + bool decompress_ = true; - std::string interface_; + std::string interface_; - std::string proxy_host_; - int proxy_port_ = -1; + std::string proxy_host_; + int proxy_port_ = -1; - std::string proxy_basic_auth_username_; - std::string proxy_basic_auth_password_; - std::string proxy_bearer_token_auth_token_; + std::string proxy_basic_auth_username_; + std::string proxy_basic_auth_password_; + std::string proxy_bearer_token_auth_token_; #ifdef CPPHTTPLIB_OPENSSL_SUPPORT - std::string proxy_digest_auth_username_; - std::string proxy_digest_auth_password_; + std::string proxy_digest_auth_username_; + std::string proxy_digest_auth_password_; #endif #ifdef CPPHTTPLIB_OPENSSL_SUPPORT - std::string ca_cert_file_path_; - std::string ca_cert_dir_path_; + std::string ca_cert_file_path_; + std::string ca_cert_dir_path_; - X509_STORE *ca_cert_store_ = nullptr; + X509_STORE *ca_cert_store_ = nullptr; #endif #ifdef CPPHTTPLIB_OPENSSL_SUPPORT - bool server_certificate_verification_ = true; + bool server_certificate_verification_ = true; #endif - Logger logger_; + Logger logger_; + + detail::POSTSOCKETCONNECTCB _postConnCb = nullptr; private: - bool send_(Request &req, Response &res, Error &error); - Result send_(Request &&req); + bool send_(Request &req, Response &res, Error &error); + Result send_(Request &&req); - socket_t create_client_socket(Error &error) const; - bool read_response_line(Stream &strm, const Request &req, Response &res); - bool write_request(Stream &strm, Request &req, bool close_connection, - Error &error); - bool redirect(Request &req, Response &res, Error &error); - bool handle_request(Stream &strm, Request &req, Response &res, - bool close_connection, Error &error); - std::unique_ptr send_with_content_provider( - Request &req, const char *body, size_t content_length, - ContentProvider content_provider, - ContentProviderWithoutLength content_provider_without_length, - const std::string &content_type, Error &error); - Result send_with_content_provider( - const std::string &method, const std::string &path, - const Headers &headers, const char *body, size_t content_length, - ContentProvider content_provider, - ContentProviderWithoutLength content_provider_without_length, - const std::string &content_type); - ContentProviderWithoutLength get_multipart_content_provider( - const std::string &boundary, const MultipartFormDataItems &items, - const MultipartFormDataProviderItems &provider_items); + socket_t create_client_socket(Error &error) const; + bool read_response_line(Stream &strm, const Request &req, Response &res); + bool write_request(Stream &strm, Request &req, bool close_connection, Error &error); + bool redirect(Request &req, Response &res, Error &error); + bool handle_request(Stream &strm, Request &req, Response &res, bool close_connection, Error &error); + std::unique_ptr send_with_content_provider(Request &req, + const char *body, + size_t content_length, + ContentProvider content_provider, + ContentProviderWithoutLength content_provider_without_length, + const std::string &content_type, + Error &error); + Result send_with_content_provider(const std::string &method, + const std::string &path, + const Headers &headers, + const char *body, + size_t content_length, + ContentProvider content_provider, + ContentProviderWithoutLength content_provider_without_length, + const std::string &content_type); + ContentProviderWithoutLength get_multipart_content_provider(const std::string &boundary, + const MultipartFormDataItems &items, + const MultipartFormDataProviderItems &provider_items); - std::string adjust_host_string(const std::string &host) const; + std::string adjust_host_string(const std::string &host) const; - virtual bool process_socket(const Socket &socket, - std::function callback); - virtual bool is_ssl() const; + virtual bool process_socket(const Socket &socket, std::function callback); + virtual bool is_ssl() const; }; class Client { public: - // Universal interface - explicit Client(const std::string &scheme_host_port); + // Universal interface + explicit Client(const std::string &scheme_host_port); - explicit Client(const std::string &scheme_host_port, - const std::string &client_cert_path, - const std::string &client_key_path); + explicit Client(const std::string &scheme_host_port, + const std::string &client_cert_path, + const std::string &client_key_path); - // HTTP only interface - explicit Client(const std::string &host, int port); + // HTTP only interface + explicit Client(const std::string &host, int port); - explicit Client(const std::string &host, int port, - const std::string &client_cert_path, - const std::string &client_key_path); + explicit Client(const std::string &host, + int port, + const std::string &client_cert_path, + const std::string &client_key_path); - Client(Client &&) = default; + Client(Client &&) = default; - ~Client(); + ~Client(); - bool is_valid() const; + bool is_valid() const; - Result Get(const std::string &path); - Result Get(const std::string &path, const Headers &headers); - Result Get(const std::string &path, Progress progress); - Result Get(const std::string &path, const Headers &headers, - Progress progress); - Result Get(const std::string &path, ContentReceiver content_receiver); - Result Get(const std::string &path, const Headers &headers, - ContentReceiver content_receiver); - Result Get(const std::string &path, ContentReceiver content_receiver, - Progress progress); - Result Get(const std::string &path, const Headers &headers, - ContentReceiver content_receiver, Progress progress); - Result Get(const std::string &path, ResponseHandler response_handler, - ContentReceiver content_receiver); - Result Get(const std::string &path, const Headers &headers, - ResponseHandler response_handler, - ContentReceiver content_receiver); - Result Get(const std::string &path, const Headers &headers, - ResponseHandler response_handler, ContentReceiver content_receiver, - Progress progress); - Result Get(const std::string &path, ResponseHandler response_handler, - ContentReceiver content_receiver, Progress progress); + Result Get(const std::string &path); + Result Get(const std::string &path, const Headers &headers); + Result Get(const std::string &path, Progress progress); + Result Get(const std::string &path, const Headers &headers, Progress progress); + Result Get(const std::string &path, ContentReceiver content_receiver); + Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver); + Result Get(const std::string &path, ContentReceiver content_receiver, Progress progress); + Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, Progress progress); + Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver); + Result Get(const std::string &path, + const Headers &headers, + ResponseHandler response_handler, + ContentReceiver content_receiver); + Result Get(const std::string &path, + const Headers &headers, + ResponseHandler response_handler, + ContentReceiver content_receiver, + Progress progress); + Result Get(const std::string &path, + ResponseHandler response_handler, + ContentReceiver content_receiver, + Progress progress); - Result Get(const std::string &path, const Params ¶ms, - const Headers &headers, Progress progress = nullptr); - Result Get(const std::string &path, const Params ¶ms, - const Headers &headers, ContentReceiver content_receiver, - Progress progress = nullptr); - Result Get(const std::string &path, const Params ¶ms, - const Headers &headers, ResponseHandler response_handler, - ContentReceiver content_receiver, Progress progress = nullptr); + Result Get(const std::string &path, const Params ¶ms, const Headers &headers, Progress progress = nullptr); + Result Get(const std::string &path, + const Params ¶ms, + const Headers &headers, + ContentReceiver content_receiver, + Progress progress = nullptr); + Result Get(const std::string &path, + const Params ¶ms, + const Headers &headers, + ResponseHandler response_handler, + ContentReceiver content_receiver, + Progress progress = nullptr); - Result Head(const std::string &path); - Result Head(const std::string &path, const Headers &headers); + Result Head(const std::string &path); + Result Head(const std::string &path, const Headers &headers); - Result Post(const std::string &path); - Result Post(const std::string &path, const Headers &headers); - Result Post(const std::string &path, const char *body, size_t content_length, - const std::string &content_type); - Result Post(const std::string &path, const Headers &headers, const char *body, - size_t content_length, const std::string &content_type); - Result Post(const std::string &path, const std::string &body, - const std::string &content_type); - Result Post(const std::string &path, const Headers &headers, - const std::string &body, const std::string &content_type); - Result Post(const std::string &path, size_t content_length, - ContentProvider content_provider, - const std::string &content_type); - Result Post(const std::string &path, - ContentProviderWithoutLength content_provider, - const std::string &content_type); - Result Post(const std::string &path, const Headers &headers, - size_t content_length, ContentProvider content_provider, - const std::string &content_type); - Result Post(const std::string &path, const Headers &headers, - ContentProviderWithoutLength content_provider, - const std::string &content_type); - Result Post(const std::string &path, const Params ¶ms); - Result Post(const std::string &path, const Headers &headers, - const Params ¶ms); - Result Post(const std::string &path, const MultipartFormDataItems &items); - Result Post(const std::string &path, const Headers &headers, - const MultipartFormDataItems &items); - Result Post(const std::string &path, const Headers &headers, - const MultipartFormDataItems &items, const std::string &boundary); - Result Post(const std::string &path, const Headers &headers, - const MultipartFormDataItems &items, - const MultipartFormDataProviderItems &provider_items); - - Result Put(const std::string &path); - Result Put(const std::string &path, const char *body, size_t content_length, - const std::string &content_type); - Result Put(const std::string &path, const Headers &headers, const char *body, - size_t content_length, const std::string &content_type); - Result Put(const std::string &path, const std::string &body, - const std::string &content_type); - Result Put(const std::string &path, const Headers &headers, - const std::string &body, const std::string &content_type); - Result Put(const std::string &path, size_t content_length, - ContentProvider content_provider, const std::string &content_type); - Result Put(const std::string &path, - ContentProviderWithoutLength content_provider, - const std::string &content_type); - Result Put(const std::string &path, const Headers &headers, - size_t content_length, ContentProvider content_provider, - const std::string &content_type); - Result Put(const std::string &path, const Headers &headers, - ContentProviderWithoutLength content_provider, - const std::string &content_type); - Result Put(const std::string &path, const Params ¶ms); - Result Put(const std::string &path, const Headers &headers, - const Params ¶ms); - Result Put(const std::string &path, const MultipartFormDataItems &items); - Result Put(const std::string &path, const Headers &headers, - const MultipartFormDataItems &items); - Result Put(const std::string &path, const Headers &headers, - const MultipartFormDataItems &items, const std::string &boundary); - Result Put(const std::string &path, const Headers &headers, - const MultipartFormDataItems &items, - const MultipartFormDataProviderItems &provider_items); - - Result Patch(const std::string &path); - Result Patch(const std::string &path, const char *body, size_t content_length, - const std::string &content_type); - Result Patch(const std::string &path, const Headers &headers, - const char *body, size_t content_length, - const std::string &content_type); - Result Patch(const std::string &path, const std::string &body, - const std::string &content_type); - Result Patch(const std::string &path, const Headers &headers, - const std::string &body, const std::string &content_type); - Result Patch(const std::string &path, size_t content_length, - ContentProvider content_provider, - const std::string &content_type); - Result Patch(const std::string &path, - ContentProviderWithoutLength content_provider, - const std::string &content_type); - Result Patch(const std::string &path, const Headers &headers, - size_t content_length, ContentProvider content_provider, - const std::string &content_type); - Result Patch(const std::string &path, const Headers &headers, - ContentProviderWithoutLength content_provider, - const std::string &content_type); - - Result Delete(const std::string &path); - Result Delete(const std::string &path, const Headers &headers); - Result Delete(const std::string &path, const char *body, - size_t content_length, const std::string &content_type); - Result Delete(const std::string &path, const Headers &headers, - const char *body, size_t content_length, + Result Post(const std::string &path); + Result Post(const std::string &path, const Headers &headers); + Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type); + Result Post(const std::string &path, + const Headers &headers, + const char *body, + size_t content_length, const std::string &content_type); - Result Delete(const std::string &path, const std::string &body, + Result Post(const std::string &path, const std::string &body, const std::string &content_type); + Result Post(const std::string &path, + const Headers &headers, + const std::string &body, const std::string &content_type); - Result Delete(const std::string &path, const Headers &headers, - const std::string &body, const std::string &content_type); + Result Post(const std::string &path, + size_t content_length, + ContentProvider content_provider, + const std::string &content_type); + Result Post(const std::string &path, + ContentProviderWithoutLength content_provider, + const std::string &content_type); + Result Post(const std::string &path, + const Headers &headers, + size_t content_length, + ContentProvider content_provider, + const std::string &content_type); + Result Post(const std::string &path, + const Headers &headers, + ContentProviderWithoutLength content_provider, + const std::string &content_type); + Result Post(const std::string &path, const Params ¶ms); + Result Post(const std::string &path, const Headers &headers, const Params ¶ms); + Result Post(const std::string &path, const MultipartFormDataItems &items); + Result Post(const std::string &path, const Headers &headers, const MultipartFormDataItems &items); + Result Post(const std::string &path, + const Headers &headers, + const MultipartFormDataItems &items, + const std::string &boundary); + Result Post(const std::string &path, + const Headers &headers, + const MultipartFormDataItems &items, + const MultipartFormDataProviderItems &provider_items); - Result Options(const std::string &path); - Result Options(const std::string &path, const Headers &headers); + Result Put(const std::string &path); + Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type); + Result Put(const std::string &path, + const Headers &headers, + const char *body, + size_t content_length, + const std::string &content_type); + Result Put(const std::string &path, const std::string &body, const std::string &content_type); + Result Put(const std::string &path, + const Headers &headers, + const std::string &body, + const std::string &content_type); + Result Put(const std::string &path, + size_t content_length, + ContentProvider content_provider, + const std::string &content_type); + Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type); + Result Put(const std::string &path, + const Headers &headers, + size_t content_length, + ContentProvider content_provider, + const std::string &content_type); + Result Put(const std::string &path, + const Headers &headers, + ContentProviderWithoutLength content_provider, + const std::string &content_type); + Result Put(const std::string &path, const Params ¶ms); + Result Put(const std::string &path, const Headers &headers, const Params ¶ms); + Result Put(const std::string &path, const MultipartFormDataItems &items); + Result Put(const std::string &path, const Headers &headers, const MultipartFormDataItems &items); + Result Put(const std::string &path, + const Headers &headers, + const MultipartFormDataItems &items, + const std::string &boundary); + Result Put(const std::string &path, + const Headers &headers, + const MultipartFormDataItems &items, + const MultipartFormDataProviderItems &provider_items); - bool send(Request &req, Response &res, Error &error); - Result send(const Request &req); + Result Patch(const std::string &path); + Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type); + Result Patch(const std::string &path, + const Headers &headers, + const char *body, + size_t content_length, + const std::string &content_type); + Result Patch(const std::string &path, const std::string &body, const std::string &content_type); + Result Patch(const std::string &path, + const Headers &headers, + const std::string &body, + const std::string &content_type); + Result Patch(const std::string &path, + size_t content_length, + ContentProvider content_provider, + const std::string &content_type); + Result Patch(const std::string &path, + ContentProviderWithoutLength content_provider, + const std::string &content_type); + Result Patch(const std::string &path, + const Headers &headers, + size_t content_length, + ContentProvider content_provider, + const std::string &content_type); + Result Patch(const std::string &path, + const Headers &headers, + ContentProviderWithoutLength content_provider, + const std::string &content_type); - void stop(); + Result Delete(const std::string &path); + Result Delete(const std::string &path, const Headers &headers); + Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type); + Result Delete(const std::string &path, + const Headers &headers, + const char *body, + size_t content_length, + const std::string &content_type); + Result Delete(const std::string &path, const std::string &body, const std::string &content_type); + Result Delete(const std::string &path, + const Headers &headers, + const std::string &body, + const std::string &content_type); - std::string host() const; - int port() const; + Result Options(const std::string &path); + Result Options(const std::string &path, const Headers &headers); - size_t is_socket_open() const; - socket_t socket() const; + bool send(Request &req, Response &res, Error &error); + Result send(const Request &req); - void set_hostname_addr_map(std::map addr_map); + void stop(); - void set_default_headers(Headers headers); + std::string host() const; + int port() const; - void set_address_family(int family); - void set_tcp_nodelay(bool on); - void set_socket_options(SocketOptions socket_options); + size_t is_socket_open() const; + socket_t socket() const; - void set_connection_timeout(time_t sec, time_t usec = 0); - template - void - set_connection_timeout(const std::chrono::duration &duration); + void set_hostname_addr_map(std::map addr_map); - void set_read_timeout(time_t sec, time_t usec = 0); - template - void set_read_timeout(const std::chrono::duration &duration); + void set_default_headers(Headers headers); - void set_write_timeout(time_t sec, time_t usec = 0); - template - void set_write_timeout(const std::chrono::duration &duration); + void set_address_family(int family); + void set_tcp_nodelay(bool on); + void set_socket_options(SocketOptions socket_options); - void set_basic_auth(const std::string &username, const std::string &password); - void set_bearer_token_auth(const std::string &token); + void set_connection_timeout(time_t sec, time_t usec = 0); + template void set_connection_timeout(const std::chrono::duration &duration); + + void set_read_timeout(time_t sec, time_t usec = 0); + template void set_read_timeout(const std::chrono::duration &duration); + + void set_write_timeout(time_t sec, time_t usec = 0); + template void set_write_timeout(const std::chrono::duration &duration); + + void set_basic_auth(const std::string &username, const std::string &password); + void set_bearer_token_auth(const std::string &token); #ifdef CPPHTTPLIB_OPENSSL_SUPPORT - void set_digest_auth(const std::string &username, - const std::string &password); + void set_digest_auth(const std::string &username, const std::string &password); #endif - void set_keep_alive(bool on); - void set_follow_location(bool on); + void set_keep_alive(bool on); + void set_follow_location(bool on); - void set_url_encode(bool on); + void set_url_encode(bool on); - void set_compress(bool on); + void set_compress(bool on); - void set_decompress(bool on); + void set_decompress(bool on); - void set_interface(const std::string &intf); + void set_interface(const std::string &intf); - void set_proxy(const std::string &host, int port); - void set_proxy_basic_auth(const std::string &username, - const std::string &password); - void set_proxy_bearer_token_auth(const std::string &token); + void set_proxy(const std::string &host, int port); + void set_proxy_basic_auth(const std::string &username, const std::string &password); + void set_proxy_bearer_token_auth(const std::string &token); + void set_post_connect_cb(detail::POSTSOCKETCONNECTCB cb); #ifdef CPPHTTPLIB_OPENSSL_SUPPORT - void set_proxy_digest_auth(const std::string &username, - const std::string &password); + void set_proxy_digest_auth(const std::string &username, const std::string &password); #endif #ifdef CPPHTTPLIB_OPENSSL_SUPPORT - void enable_server_certificate_verification(bool enabled); + void enable_server_certificate_verification(bool enabled); #endif - void set_logger(Logger logger); + void set_logger(Logger logger); - // SSL + // SSL #ifdef CPPHTTPLIB_OPENSSL_SUPPORT - void set_ca_cert_path(const std::string &ca_cert_file_path, - const std::string &ca_cert_dir_path = std::string()); + void set_ca_cert_path(const std::string &ca_cert_file_path, const std::string &ca_cert_dir_path = std::string()); - void set_ca_cert_store(X509_STORE *ca_cert_store); - void load_ca_cert_store(const char *ca_cert, std::size_t size); + void set_ca_cert_store(X509_STORE *ca_cert_store); + void load_ca_cert_store(const char *ca_cert, std::size_t size); - long get_openssl_verify_result() const; + long get_openssl_verify_result() const; - SSL_CTX *ssl_context() const; + SSL_CTX *ssl_context() const; #endif private: - std::unique_ptr cli_; + std::unique_ptr cli_; #ifdef CPPHTTPLIB_OPENSSL_SUPPORT - bool is_ssl_ = false; + bool is_ssl_ = false; #endif }; #ifdef CPPHTTPLIB_OPENSSL_SUPPORT class SSLServer : public Server { public: - SSLServer(const char *cert_path, const char *private_key_path, - const char *client_ca_cert_file_path = nullptr, - const char *client_ca_cert_dir_path = nullptr, - const char *private_key_password = nullptr); + SSLServer(const char *cert_path, + const char *private_key_path, + const char *client_ca_cert_file_path = nullptr, + const char *client_ca_cert_dir_path = nullptr, + const char *private_key_password = nullptr); - SSLServer(X509 *cert, EVP_PKEY *private_key, - X509_STORE *client_ca_cert_store = nullptr); + SSLServer(X509 *cert, EVP_PKEY *private_key, X509_STORE *client_ca_cert_store = nullptr); - SSLServer( - const std::function &setup_ssl_ctx_callback); + SSLServer(const std::function &setup_ssl_ctx_callback); - ~SSLServer() override; + ~SSLServer() override; - bool is_valid() const override; + bool is_valid() const override; - SSL_CTX *ssl_context() const; + SSL_CTX *ssl_context() const; private: - bool process_and_close_socket(socket_t sock) override; + bool process_and_close_socket(socket_t sock) override; - SSL_CTX *ctx_; - std::mutex ctx_mutex_; + SSL_CTX *ctx_; + std::mutex ctx_mutex_; }; class SSLClient : public ClientImpl { public: - explicit SSLClient(const std::string &host); + explicit SSLClient(const std::string &host); - explicit SSLClient(const std::string &host, int port); + explicit SSLClient(const std::string &host, int port); - explicit SSLClient(const std::string &host, int port, - const std::string &client_cert_path, - const std::string &client_key_path); + explicit SSLClient(const std::string &host, + int port, + const std::string &client_cert_path, + const std::string &client_key_path); - explicit SSLClient(const std::string &host, int port, X509 *client_cert, - EVP_PKEY *client_key); + explicit SSLClient(const std::string &host, int port, X509 *client_cert, EVP_PKEY *client_key); - ~SSLClient() override; + ~SSLClient() override; - bool is_valid() const override; + bool is_valid() const override; - void set_ca_cert_store(X509_STORE *ca_cert_store); - void load_ca_cert_store(const char *ca_cert, std::size_t size); + void set_ca_cert_store(X509_STORE *ca_cert_store); + void load_ca_cert_store(const char *ca_cert, std::size_t size); - long get_openssl_verify_result() const; + long get_openssl_verify_result() const; - SSL_CTX *ssl_context() const; + SSL_CTX *ssl_context() const; private: - bool create_and_connect_socket(Socket &socket, Error &error) override; - void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override; - void shutdown_ssl_impl(Socket &socket, bool shutdown_socket); + bool create_and_connect_socket(Socket &socket, Error &error) override; + void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override; + void shutdown_ssl_impl(Socket &socket, bool shutdown_socket); - bool process_socket(const Socket &socket, - std::function callback) override; - bool is_ssl() const override; + bool process_socket(const Socket &socket, std::function callback) override; + bool is_ssl() const override; - bool connect_with_proxy(Socket &sock, Response &res, bool &success, - Error &error); - bool initialize_ssl(Socket &socket, Error &error); + bool connect_with_proxy(Socket &sock, Response &res, bool &success, Error &error); + bool initialize_ssl(Socket &socket, Error &error); - bool load_certs(); + bool load_certs(); - bool verify_host(X509 *server_cert) const; - bool verify_host_with_subject_alt_name(X509 *server_cert) const; - bool verify_host_with_common_name(X509 *server_cert) const; - bool check_host_name(const char *pattern, size_t pattern_len) const; + bool verify_host(X509 *server_cert) const; + bool verify_host_with_subject_alt_name(X509 *server_cert) const; + bool verify_host_with_common_name(X509 *server_cert) const; + bool check_host_name(const char *pattern, size_t pattern_len) const; - SSL_CTX *ctx_; - std::mutex ctx_mutex_; - std::once_flag initialize_cert_; + SSL_CTX *ctx_; + std::mutex ctx_mutex_; + std::once_flag initialize_cert_; - std::vector host_components_; + std::vector host_components_; - long verify_result_ = 0; + long verify_result_ = 0; - friend class ClientImpl; + friend class ClientImpl; }; #endif @@ -1695,184 +1764,171 @@ private: namespace detail { -template -inline void duration_to_sec_and_usec(const T &duration, U callback) { - auto sec = std::chrono::duration_cast(duration).count(); - auto usec = std::chrono::duration_cast( - duration - std::chrono::seconds(sec)) - .count(); - callback(static_cast(sec), static_cast(usec)); +template inline void duration_to_sec_and_usec(const T &duration, U callback) { + auto sec = std::chrono::duration_cast(duration).count(); + auto usec = std::chrono::duration_cast(duration - std::chrono::seconds(sec)).count(); + callback(static_cast(sec), static_cast(usec)); } -template +template inline T get_header_value(const Headers & /*headers*/, - const std::string & /*key*/, size_t /*id*/ = 0, - uint64_t /*def*/ = 0) {} - -template <> -inline uint64_t get_header_value(const Headers &headers, - const std::string &key, size_t id, - uint64_t def) { - auto rng = headers.equal_range(key); - auto it = rng.first; - std::advance(it, static_cast(id)); - if (it != rng.second) { - return std::strtoull(it->second.data(), nullptr, 10); - } - return def; + const std::string & /*key*/, + size_t /*id*/ = 0, + uint64_t /*def*/ = 0) { } -} // namespace detail - -template -inline T Request::get_header_value(const std::string &key, size_t id) const { - return detail::get_header_value(headers, key, id, 0); -} - -template -inline T Response::get_header_value(const std::string &key, size_t id) const { - return detail::get_header_value(headers, key, id, 0); -} - -template -inline ssize_t Stream::write_format(const char *fmt, const Args &...args) { - const auto bufsiz = 2048; - std::array buf{}; - - auto sn = snprintf(buf.data(), buf.size() - 1, fmt, args...); - if (sn <= 0) { return sn; } - - auto n = static_cast(sn); - - if (n >= buf.size() - 1) { - std::vector glowable_buf(buf.size()); - - while (n >= glowable_buf.size() - 1) { - glowable_buf.resize(glowable_buf.size() * 2); - n = static_cast( - snprintf(&glowable_buf[0], glowable_buf.size() - 1, fmt, args...)); +template<> +inline uint64_t get_header_value(const Headers &headers, const std::string &key, size_t id, uint64_t def) { + auto rng = headers.equal_range(key); + auto it = rng.first; + std::advance(it, static_cast(id)); + if (it != rng.second) { + return std::strtoull(it->second.data(), nullptr, 10); + } + return def; +} + +} // namespace detail + +template inline T Request::get_header_value(const std::string &key, size_t id) const { + return detail::get_header_value(headers, key, id, 0); +} + +template inline T Response::get_header_value(const std::string &key, size_t id) const { + return detail::get_header_value(headers, key, id, 0); +} + +template inline ssize_t Stream::write_format(const char *fmt, const Args &...args) { + const auto bufsiz = 2048; + std::array buf {}; + + auto sn = snprintf(buf.data(), buf.size() - 1, fmt, args...); + if (sn <= 0) { + return sn; + } + + auto n = static_cast(sn); + + if (n >= buf.size() - 1) { + std::vector glowable_buf(buf.size()); + + while (n >= glowable_buf.size() - 1) { + glowable_buf.resize(glowable_buf.size() * 2); + n = static_cast(snprintf(&glowable_buf[0], glowable_buf.size() - 1, fmt, args...)); + } + return write(&glowable_buf[0], n); + } else { + return write(buf.data(), n); } - return write(&glowable_buf[0], n); - } else { - return write(buf.data(), n); - } } inline void default_socket_options(socket_t sock) { - int yes = 1; + int yes = 1; #ifdef _WIN32 - setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, - reinterpret_cast(&yes), sizeof(yes)); - setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, - reinterpret_cast(&yes), sizeof(yes)); + setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&yes), sizeof(yes)); + setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, reinterpret_cast(&yes), sizeof(yes)); #else #ifdef SO_REUSEPORT - setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, - reinterpret_cast(&yes), sizeof(yes)); + setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, reinterpret_cast(&yes), sizeof(yes)); #else - setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, - reinterpret_cast(&yes), sizeof(yes)); + setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&yes), sizeof(yes)); #endif #endif } -template -inline Server & -Server::set_read_timeout(const std::chrono::duration &duration) { - detail::duration_to_sec_and_usec( - duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); }); - return *this; +template +inline Server &Server::set_read_timeout(const std::chrono::duration &duration) { + detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); }); + return *this; } -template -inline Server & -Server::set_write_timeout(const std::chrono::duration &duration) { - detail::duration_to_sec_and_usec( - duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); }); - return *this; +template +inline Server &Server::set_write_timeout(const std::chrono::duration &duration) { + detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); }); + return *this; } -template -inline Server & -Server::set_idle_interval(const std::chrono::duration &duration) { - detail::duration_to_sec_and_usec( - duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); }); - return *this; +template +inline Server &Server::set_idle_interval(const std::chrono::duration &duration) { + detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); }); + return *this; } inline std::string to_string(const Error error) { - switch (error) { - case Error::Success: return "Success (no error)"; - case Error::Connection: return "Could not establish connection"; - case Error::BindIPAddress: return "Failed to bind IP address"; - case Error::Read: return "Failed to read connection"; - case Error::Write: return "Failed to write connection"; - case Error::ExceedRedirectCount: return "Maximum redirect count exceeded"; - case Error::Canceled: return "Connection handling canceled"; - case Error::SSLConnection: return "SSL connection failed"; - case Error::SSLLoadingCerts: return "SSL certificate loading failed"; - case Error::SSLServerVerification: return "SSL server verification failed"; - case Error::UnsupportedMultipartBoundaryChars: - return "Unsupported HTTP multipart boundary characters"; - case Error::Compression: return "Compression failed"; - case Error::ConnectionTimeout: return "Connection timed out"; - case Error::Unknown: return "Unknown"; - default: break; - } + switch (error) { + case Error::Success: + return "Success (no error)"; + case Error::Connection: + return "Could not establish connection"; + case Error::BindIPAddress: + return "Failed to bind IP address"; + case Error::Read: + return "Failed to read connection"; + case Error::Write: + return "Failed to write connection"; + case Error::ExceedRedirectCount: + return "Maximum redirect count exceeded"; + case Error::Canceled: + return "Connection handling canceled"; + case Error::SSLConnection: + return "SSL connection failed"; + case Error::SSLLoadingCerts: + return "SSL certificate loading failed"; + case Error::SSLServerVerification: + return "SSL server verification failed"; + case Error::UnsupportedMultipartBoundaryChars: + return "Unsupported HTTP multipart boundary characters"; + case Error::Compression: + return "Compression failed"; + case Error::ConnectionTimeout: + return "Connection timed out"; + case Error::Unknown: + return "Unknown"; + default: + break; + } - return "Invalid"; + return "Invalid"; } inline std::ostream &operator<<(std::ostream &os, const Error &obj) { - os << to_string(obj); - os << " (" << static_cast::type>(obj) << ')'; - return os; + os << to_string(obj); + os << " (" << static_cast::type>(obj) << ')'; + return os; } -template -inline T Result::get_request_header_value(const std::string &key, - size_t id) const { - return detail::get_header_value(request_headers_, key, id, 0); +template inline T Result::get_request_header_value(const std::string &key, size_t id) const { + return detail::get_header_value(request_headers_, key, id, 0); } -template -inline void ClientImpl::set_connection_timeout( - const std::chrono::duration &duration) { - detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) { - set_connection_timeout(sec, usec); - }); +template +inline void ClientImpl::set_connection_timeout(const std::chrono::duration &duration) { + detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) { set_connection_timeout(sec, usec); }); } -template -inline void ClientImpl::set_read_timeout( - const std::chrono::duration &duration) { - detail::duration_to_sec_and_usec( - duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); }); +template +inline void ClientImpl::set_read_timeout(const std::chrono::duration &duration) { + detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); }); } -template -inline void ClientImpl::set_write_timeout( - const std::chrono::duration &duration) { - detail::duration_to_sec_and_usec( - duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); }); +template +inline void ClientImpl::set_write_timeout(const std::chrono::duration &duration) { + detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); }); } -template -inline void Client::set_connection_timeout( - const std::chrono::duration &duration) { - cli_->set_connection_timeout(duration); +template +inline void Client::set_connection_timeout(const std::chrono::duration &duration) { + cli_->set_connection_timeout(duration); } -template -inline void -Client::set_read_timeout(const std::chrono::duration &duration) { - cli_->set_read_timeout(duration); +template +inline void Client::set_read_timeout(const std::chrono::duration &duration) { + cli_->set_read_timeout(duration); } -template -inline void -Client::set_write_timeout(const std::chrono::duration &duration) { - cli_->set_write_timeout(duration); +template +inline void Client::set_write_timeout(const std::chrono::duration &duration) { + cli_->set_write_timeout(duration); } /* @@ -1888,10 +1944,9 @@ std::string append_query_params(const std::string &path, const Params ¶ms); std::pair make_range_header(Ranges ranges); -std::pair -make_basic_authentication_header(const std::string &username, - const std::string &password, - bool is_proxy = false); +std::pair make_basic_authentication_header(const std::string &username, + const std::string &password, + bool is_proxy = false); namespace detail { @@ -1903,30 +1958,37 @@ void read_file(const std::string &path, std::string &out); std::string trim_copy(const std::string &s); -void split(const char *b, const char *e, char d, - std::function fn); +void split(const char *b, const char *e, char d, std::function fn); -bool process_client_socket(socket_t sock, time_t read_timeout_sec, - time_t read_timeout_usec, time_t write_timeout_sec, - time_t write_timeout_usec, +bool process_client_socket(socket_t sock, + time_t read_timeout_sec, + time_t read_timeout_usec, + time_t write_timeout_sec, + time_t write_timeout_usec, std::function callback); -socket_t create_client_socket( - const std::string &host, const std::string &ip, int port, - int address_family, bool tcp_nodelay, SocketOptions socket_options, - time_t connection_timeout_sec, time_t connection_timeout_usec, - time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec, - time_t write_timeout_usec, const std::string &intf, Error &error); +socket_t create_client_socket(const std::string &host, + const std::string &ip, + int port, + int address_family, + bool tcp_nodelay, + SocketOptions socket_options, + time_t connection_timeout_sec, + time_t connection_timeout_usec, + time_t read_timeout_sec, + time_t read_timeout_usec, + time_t write_timeout_sec, + time_t write_timeout_usec, + const std::string &intf, + Error &error); -const char *get_header_value(const Headers &headers, const std::string &key, - size_t id = 0, const char *def = nullptr); +const char *get_header_value(const Headers &headers, const std::string &key, size_t id = 0, const char *def = nullptr); std::string params_to_query_str(const Params ¶ms); void parse_query_text(const std::string &s, Params ¶ms); -bool parse_multipart_boundary(const std::string &content_type, - std::string &boundary); +bool parse_multipart_boundary(const std::string &content_type, std::string &boundary); bool parse_range_header(const std::string &s, Ranges &ranges); @@ -1936,114 +1998,111 @@ ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags); ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags); -enum class EncodingType { None = 0, Gzip, Brotli }; +enum class EncodingType { + None = 0, + Gzip, + Brotli +}; EncodingType encoding_type(const Request &req, const Response &res); class BufferStream : public Stream { public: - BufferStream() = default; - ~BufferStream() override = default; + BufferStream() = default; + ~BufferStream() override = default; - bool is_readable() const override; - bool is_writable() const override; - ssize_t read(char *ptr, size_t size) override; - ssize_t write(const char *ptr, size_t size) override; - void get_remote_ip_and_port(std::string &ip, int &port) const override; - void get_local_ip_and_port(std::string &ip, int &port) const override; - socket_t socket() const override; + bool is_readable() const override; + bool is_writable() const override; + ssize_t read(char *ptr, size_t size) override; + ssize_t write(const char *ptr, size_t size) override; + void get_remote_ip_and_port(std::string &ip, int &port) const override; + void get_local_ip_and_port(std::string &ip, int &port) const override; + socket_t socket() const override; - const std::string &get_buffer() const; + const std::string &get_buffer() const; private: - std::string buffer; - size_t position = 0; + std::string buffer; + size_t position = 0; }; class compressor { public: - virtual ~compressor() = default; + virtual ~compressor() = default; - typedef std::function Callback; - virtual bool compress(const char *data, size_t data_length, bool last, - Callback callback) = 0; + typedef std::function Callback; + virtual bool compress(const char *data, size_t data_length, bool last, Callback callback) = 0; }; class decompressor { public: - virtual ~decompressor() = default; + virtual ~decompressor() = default; - virtual bool is_valid() const = 0; + virtual bool is_valid() const = 0; - typedef std::function Callback; - virtual bool decompress(const char *data, size_t data_length, - Callback callback) = 0; + typedef std::function Callback; + virtual bool decompress(const char *data, size_t data_length, Callback callback) = 0; }; class nocompressor : public compressor { public: - virtual ~nocompressor() = default; + virtual ~nocompressor() = default; - bool compress(const char *data, size_t data_length, bool /*last*/, - Callback callback) override; + bool compress(const char *data, size_t data_length, bool /*last*/, Callback callback) override; }; #ifdef CPPHTTPLIB_ZLIB_SUPPORT class gzip_compressor : public compressor { public: - gzip_compressor(); - ~gzip_compressor(); + gzip_compressor(); + ~gzip_compressor(); - bool compress(const char *data, size_t data_length, bool last, - Callback callback) override; + bool compress(const char *data, size_t data_length, bool last, Callback callback) override; private: - bool is_valid_ = false; - z_stream strm_; + bool is_valid_ = false; + z_stream strm_; }; class gzip_decompressor : public decompressor { public: - gzip_decompressor(); - ~gzip_decompressor(); + gzip_decompressor(); + ~gzip_decompressor(); - bool is_valid() const override; + bool is_valid() const override; - bool decompress(const char *data, size_t data_length, - Callback callback) override; + bool decompress(const char *data, size_t data_length, Callback callback) override; private: - bool is_valid_ = false; - z_stream strm_; + bool is_valid_ = false; + z_stream strm_; }; #endif #ifdef CPPHTTPLIB_BROTLI_SUPPORT class brotli_compressor : public compressor { public: - brotli_compressor(); - ~brotli_compressor(); + brotli_compressor(); + ~brotli_compressor(); - bool compress(const char *data, size_t data_length, bool last, - Callback callback) override; + bool compress(const char *data, size_t data_length, bool last, Callback callback) override; private: - BrotliEncoderState *state_ = nullptr; + BrotliEncoderState *state_ = nullptr; }; class brotli_decompressor : public decompressor { public: - brotli_decompressor(); - ~brotli_decompressor(); + brotli_decompressor(); + ~brotli_decompressor(); - bool is_valid() const override; + bool is_valid() const override; - bool decompress(const char *data, size_t data_length, - Callback callback) override; + bool decompress(const char *data, size_t data_length, Callback callback) override; private: - BrotliDecoderResult decoder_r; - BrotliDecoderState *decoder_s = nullptr; + BrotliDecoderResult decoder_r; + BrotliDecoderState *decoder_s = nullptr; }; #endif @@ -2051,24 +2110,23 @@ private: // to store data. The call can set memory on stack for performance. class stream_line_reader { public: - stream_line_reader(Stream &strm, char *fixed_buffer, - size_t fixed_buffer_size); - const char *ptr() const; - size_t size() const; - bool end_with_crlf() const; - bool getline(); + stream_line_reader(Stream &strm, char *fixed_buffer, size_t fixed_buffer_size); + const char *ptr() const; + size_t size() const; + bool end_with_crlf() const; + bool getline(); private: - void append(char c); + void append(char c); - Stream &strm_; - char *fixed_buffer_; - const size_t fixed_buffer_size_; - size_t fixed_buffer_used_size_ = 0; - std::string glowable_buffer_; + Stream &strm_; + char *fixed_buffer_; + const size_t fixed_buffer_size_; + size_t fixed_buffer_used_size_ = 0; + std::string glowable_buffer_; }; -} // namespace detail +} // namespace detail // ---------------------------------------------------------------------------- @@ -2079,729 +2137,790 @@ private: namespace detail { inline bool is_hex(char c, int &v) { - if (0x20 <= c && isdigit(c)) { - v = c - '0'; - return true; - } else if ('A' <= c && c <= 'F') { - v = c - 'A' + 10; - return true; - } else if ('a' <= c && c <= 'f') { - v = c - 'a' + 10; - return true; - } - return false; + if (0x20 <= c && isdigit(c)) { + v = c - '0'; + return true; + } else if ('A' <= c && c <= 'F') { + v = c - 'A' + 10; + return true; + } else if ('a' <= c && c <= 'f') { + v = c - 'a' + 10; + return true; + } + return false; } -inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt, - int &val) { - if (i >= s.size()) { return false; } - - val = 0; - for (; cnt; i++, cnt--) { - if (!s[i]) { return false; } - auto v = 0; - if (is_hex(s[i], v)) { - val = val * 16 + v; - } else { - return false; +inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt, int &val) { + if (i >= s.size()) { + return false; } - } - return true; + + val = 0; + for (; cnt; i++, cnt--) { + if (!s[i]) { + return false; + } + auto v = 0; + if (is_hex(s[i], v)) { + val = val * 16 + v; + } else { + return false; + } + } + return true; } inline std::string from_i_to_hex(size_t n) { - static const auto charset = "0123456789abcdef"; - std::string ret; - do { - ret = charset[n & 15] + ret; - n >>= 4; - } while (n > 0); - return ret; + static const auto charset = "0123456789abcdef"; + std::string ret; + do { + ret = charset[n & 15] + ret; + n >>= 4; + } while (n > 0); + return ret; } inline size_t to_utf8(int code, char *buff) { - if (code < 0x0080) { - buff[0] = (code & 0x7F); - return 1; - } else if (code < 0x0800) { - buff[0] = static_cast(0xC0 | ((code >> 6) & 0x1F)); - buff[1] = static_cast(0x80 | (code & 0x3F)); - return 2; - } else if (code < 0xD800) { - buff[0] = static_cast(0xE0 | ((code >> 12) & 0xF)); - buff[1] = static_cast(0x80 | ((code >> 6) & 0x3F)); - buff[2] = static_cast(0x80 | (code & 0x3F)); - return 3; - } else if (code < 0xE000) { // D800 - DFFF is invalid... - return 0; - } else if (code < 0x10000) { - buff[0] = static_cast(0xE0 | ((code >> 12) & 0xF)); - buff[1] = static_cast(0x80 | ((code >> 6) & 0x3F)); - buff[2] = static_cast(0x80 | (code & 0x3F)); - return 3; - } else if (code < 0x110000) { - buff[0] = static_cast(0xF0 | ((code >> 18) & 0x7)); - buff[1] = static_cast(0x80 | ((code >> 12) & 0x3F)); - buff[2] = static_cast(0x80 | ((code >> 6) & 0x3F)); - buff[3] = static_cast(0x80 | (code & 0x3F)); - return 4; - } + if (code < 0x0080) { + buff[0] = (code & 0x7F); + return 1; + } else if (code < 0x0800) { + buff[0] = static_cast(0xC0 | ((code >> 6) & 0x1F)); + buff[1] = static_cast(0x80 | (code & 0x3F)); + return 2; + } else if (code < 0xD800) { + buff[0] = static_cast(0xE0 | ((code >> 12) & 0xF)); + buff[1] = static_cast(0x80 | ((code >> 6) & 0x3F)); + buff[2] = static_cast(0x80 | (code & 0x3F)); + return 3; + } else if (code < 0xE000) { // D800 - DFFF is invalid... + return 0; + } else if (code < 0x10000) { + buff[0] = static_cast(0xE0 | ((code >> 12) & 0xF)); + buff[1] = static_cast(0x80 | ((code >> 6) & 0x3F)); + buff[2] = static_cast(0x80 | (code & 0x3F)); + return 3; + } else if (code < 0x110000) { + buff[0] = static_cast(0xF0 | ((code >> 18) & 0x7)); + buff[1] = static_cast(0x80 | ((code >> 12) & 0x3F)); + buff[2] = static_cast(0x80 | ((code >> 6) & 0x3F)); + buff[3] = static_cast(0x80 | (code & 0x3F)); + return 4; + } - // NOTREACHED - return 0; + // NOTREACHED + return 0; } // NOTE: This code came up with the following stackoverflow post: // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c inline std::string base64_encode(const std::string &in) { - static const auto lookup = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + static const auto lookup = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - std::string out; - out.reserve(in.size()); + std::string out; + out.reserve(in.size()); - auto val = 0; - auto valb = -6; + auto val = 0; + auto valb = -6; - for (auto c : in) { - val = (val << 8) + static_cast(c); - valb += 8; - while (valb >= 0) { - out.push_back(lookup[(val >> valb) & 0x3F]); - valb -= 6; + for (auto c : in) { + val = (val << 8) + static_cast(c); + valb += 8; + while (valb >= 0) { + out.push_back(lookup[(val >> valb) & 0x3F]); + valb -= 6; + } } - } - if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); } + if (valb > -6) { + out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); + } - while (out.size() % 4) { - out.push_back('='); - } + while (out.size() % 4) { + out.push_back('='); + } - return out; + return out; } inline bool is_file(const std::string &path) { #ifdef _WIN32 - return _access_s(path.c_str(), 0) == 0; + return _access_s(path.c_str(), 0) == 0; #else - struct stat st; - return stat(path.c_str(), &st) >= 0 && S_ISREG(st.st_mode); + struct stat st; + return stat(path.c_str(), &st) >= 0 && S_ISREG(st.st_mode); #endif } inline bool is_dir(const std::string &path) { - struct stat st; - return stat(path.c_str(), &st) >= 0 && S_ISDIR(st.st_mode); + struct stat st; + return stat(path.c_str(), &st) >= 0 && S_ISDIR(st.st_mode); } inline bool is_valid_path(const std::string &path) { - size_t level = 0; - size_t i = 0; - - // Skip slash - while (i < path.size() && path[i] == '/') { - i++; - } - - while (i < path.size()) { - // Read component - auto beg = i; - while (i < path.size() && path[i] != '/') { - i++; - } - - auto len = i - beg; - assert(len > 0); - - if (!path.compare(beg, len, ".")) { - ; - } else if (!path.compare(beg, len, "..")) { - if (level == 0) { return false; } - level--; - } else { - level++; - } + size_t level = 0; + size_t i = 0; // Skip slash while (i < path.size() && path[i] == '/') { - i++; + i++; } - } - return true; + while (i < path.size()) { + // Read component + auto beg = i; + while (i < path.size() && path[i] != '/') { + i++; + } + + auto len = i - beg; + assert(len > 0); + + if (!path.compare(beg, len, ".")) { + ; + } else if (!path.compare(beg, len, "..")) { + if (level == 0) { + return false; + } + level--; + } else { + level++; + } + + // Skip slash + while (i < path.size() && path[i] == '/') { + i++; + } + } + + return true; } inline std::string encode_query_param(const std::string &value) { - std::ostringstream escaped; - escaped.fill('0'); - escaped << std::hex; + std::ostringstream escaped; + escaped.fill('0'); + escaped << std::hex; - for (auto c : value) { - if (std::isalnum(static_cast(c)) || c == '-' || c == '_' || - c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || - c == ')') { - escaped << c; - } else { - escaped << std::uppercase; - escaped << '%' << std::setw(2) - << static_cast(static_cast(c)); - escaped << std::nouppercase; + for (auto c : value) { + if (std::isalnum(static_cast(c)) || c == '-' || c == '_' || c == '.' || c == '!' || c == '~' || + c == '*' || c == '\'' || c == '(' || c == ')') { + escaped << c; + } else { + escaped << std::uppercase; + escaped << '%' << std::setw(2) << static_cast(static_cast(c)); + escaped << std::nouppercase; + } } - } - return escaped.str(); + return escaped.str(); } inline std::string encode_url(const std::string &s) { - std::string result; - result.reserve(s.size()); + std::string result; + result.reserve(s.size()); - for (size_t i = 0; s[i]; i++) { - switch (s[i]) { - case ' ': result += "%20"; break; - case '+': result += "%2B"; break; - case '\r': result += "%0D"; break; - case '\n': result += "%0A"; break; - case '\'': result += "%27"; break; - case ',': result += "%2C"; break; - // case ':': result += "%3A"; break; // ok? probably... - case ';': result += "%3B"; break; - default: - auto c = static_cast(s[i]); - if (c >= 0x80) { - result += '%'; - char hex[4]; - auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c); - assert(len == 2); - result.append(hex, static_cast(len)); - } else { - result += s[i]; - } - break; + for (size_t i = 0; s[i]; i++) { + switch (s[i]) { + case ' ': + result += "%20"; + break; + case '+': + result += "%2B"; + break; + case '\r': + result += "%0D"; + break; + case '\n': + result += "%0A"; + break; + case '\'': + result += "%27"; + break; + case ',': + result += "%2C"; + break; + // case ':': result += "%3A"; break; // ok? probably... + case ';': + result += "%3B"; + break; + default: + auto c = static_cast(s[i]); + if (c >= 0x80) { + result += '%'; + char hex[4]; + auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c); + assert(len == 2); + result.append(hex, static_cast(len)); + } else { + result += s[i]; + } + break; + } } - } - return result; + return result; } -inline std::string decode_url(const std::string &s, - bool convert_plus_to_space) { - std::string result; +inline std::string decode_url(const std::string &s, bool convert_plus_to_space) { + std::string result; - for (size_t i = 0; i < s.size(); i++) { - if (s[i] == '%' && i + 1 < s.size()) { - if (s[i + 1] == 'u') { - auto val = 0; - if (from_hex_to_i(s, i + 2, 4, val)) { - // 4 digits Unicode codes - char buff[4]; - size_t len = to_utf8(val, buff); - if (len > 0) { result.append(buff, len); } - i += 5; // 'u0000' + for (size_t i = 0; i < s.size(); i++) { + if (s[i] == '%' && i + 1 < s.size()) { + if (s[i + 1] == 'u') { + auto val = 0; + if (from_hex_to_i(s, i + 2, 4, val)) { + // 4 digits Unicode codes + char buff[4]; + size_t len = to_utf8(val, buff); + if (len > 0) { + result.append(buff, len); + } + i += 5; // 'u0000' + } else { + result += s[i]; + } + } else { + auto val = 0; + if (from_hex_to_i(s, i + 1, 2, val)) { + // 2 digits hex codes + result += static_cast(val); + i += 2; // '00' + } else { + result += s[i]; + } + } + } else if (convert_plus_to_space && s[i] == '+') { + result += ' '; } else { - result += s[i]; + result += s[i]; } - } else { - auto val = 0; - if (from_hex_to_i(s, i + 1, 2, val)) { - // 2 digits hex codes - result += static_cast(val); - i += 2; // '00' - } else { - result += s[i]; - } - } - } else if (convert_plus_to_space && s[i] == '+') { - result += ' '; - } else { - result += s[i]; } - } - return result; + return result; } inline void read_file(const std::string &path, std::string &out) { - std::ifstream fs(path, std::ios_base::binary); - fs.seekg(0, std::ios_base::end); - auto size = fs.tellg(); - fs.seekg(0); - out.resize(static_cast(size)); - fs.read(&out[0], static_cast(size)); + std::ifstream fs(path, std::ios_base::binary); + fs.seekg(0, std::ios_base::end); + auto size = fs.tellg(); + fs.seekg(0); + out.resize(static_cast(size)); + fs.read(&out[0], static_cast(size)); } inline std::string file_extension(const std::string &path) { - std::smatch m; - static auto re = std::regex("\\.([a-zA-Z0-9]+)$"); - if (std::regex_search(path, m, re)) { return m[1].str(); } - return std::string(); + std::smatch m; + static auto re = std::regex("\\.([a-zA-Z0-9]+)$"); + if (std::regex_search(path, m, re)) { + return m[1].str(); + } + return std::string(); } -inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; } +inline bool is_space_or_tab(char c) { + return c == ' ' || c == '\t'; +} -inline std::pair trim(const char *b, const char *e, size_t left, - size_t right) { - while (b + left < e && is_space_or_tab(b[left])) { - left++; - } - while (right > 0 && is_space_or_tab(b[right - 1])) { - right--; - } - return std::make_pair(left, right); +inline std::pair trim(const char *b, const char *e, size_t left, size_t right) { + while (b + left < e && is_space_or_tab(b[left])) { + left++; + } + while (right > 0 && is_space_or_tab(b[right - 1])) { + right--; + } + return std::make_pair(left, right); } inline std::string trim_copy(const std::string &s) { - auto r = trim(s.data(), s.data() + s.size(), 0, s.size()); - return s.substr(r.first, r.second - r.first); + auto r = trim(s.data(), s.data() + s.size(), 0, s.size()); + return s.substr(r.first, r.second - r.first); } -inline void split(const char *b, const char *e, char d, - std::function fn) { - size_t i = 0; - size_t beg = 0; +inline void split(const char *b, const char *e, char d, std::function fn) { + size_t i = 0; + size_t beg = 0; - while (e ? (b + i < e) : (b[i] != '\0')) { - if (b[i] == d) { - auto r = trim(b, e, beg, i); - if (r.first < r.second) { fn(&b[r.first], &b[r.second]); } - beg = i + 1; + while (e ? (b + i < e) : (b[i] != '\0')) { + if (b[i] == d) { + auto r = trim(b, e, beg, i); + if (r.first < r.second) { + fn(&b[r.first], &b[r.second]); + } + beg = i + 1; + } + i++; } - i++; - } - if (i) { - auto r = trim(b, e, beg, i); - if (r.first < r.second) { fn(&b[r.first], &b[r.second]); } - } + if (i) { + auto r = trim(b, e, beg, i); + if (r.first < r.second) { + fn(&b[r.first], &b[r.second]); + } + } } -inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer, - size_t fixed_buffer_size) - : strm_(strm), fixed_buffer_(fixed_buffer), - fixed_buffer_size_(fixed_buffer_size) {} +inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer, size_t fixed_buffer_size) + : strm_(strm), + fixed_buffer_(fixed_buffer), + fixed_buffer_size_(fixed_buffer_size) { +} inline const char *stream_line_reader::ptr() const { - if (glowable_buffer_.empty()) { - return fixed_buffer_; - } else { - return glowable_buffer_.data(); - } + if (glowable_buffer_.empty()) { + return fixed_buffer_; + } else { + return glowable_buffer_.data(); + } } inline size_t stream_line_reader::size() const { - if (glowable_buffer_.empty()) { - return fixed_buffer_used_size_; - } else { - return glowable_buffer_.size(); - } + if (glowable_buffer_.empty()) { + return fixed_buffer_used_size_; + } else { + return glowable_buffer_.size(); + } } inline bool stream_line_reader::end_with_crlf() const { - auto end = ptr() + size(); - return size() >= 2 && end[-2] == '\r' && end[-1] == '\n'; + auto end = ptr() + size(); + return size() >= 2 && end[-2] == '\r' && end[-1] == '\n'; } inline bool stream_line_reader::getline() { - fixed_buffer_used_size_ = 0; - glowable_buffer_.clear(); + fixed_buffer_used_size_ = 0; + glowable_buffer_.clear(); - for (size_t i = 0;; i++) { - char byte; - auto n = strm_.read(&byte, 1); + for (size_t i = 0;; i++) { + char byte; + auto n = strm_.read(&byte, 1); - if (n < 0) { - return false; - } else if (n == 0) { - if (i == 0) { - return false; - } else { - break; - } + if (n < 0) { + return false; + } else if (n == 0) { + if (i == 0) { + return false; + } else { + break; + } + } + + append(byte); + + if (byte == '\n') { + break; + } } - append(byte); - - if (byte == '\n') { break; } - } - - return true; + return true; } inline void stream_line_reader::append(char c) { - if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) { - fixed_buffer_[fixed_buffer_used_size_++] = c; - fixed_buffer_[fixed_buffer_used_size_] = '\0'; - } else { - if (glowable_buffer_.empty()) { - assert(fixed_buffer_[fixed_buffer_used_size_] == '\0'); - glowable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_); + if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) { + fixed_buffer_[fixed_buffer_used_size_++] = c; + fixed_buffer_[fixed_buffer_used_size_] = '\0'; + } else { + if (glowable_buffer_.empty()) { + assert(fixed_buffer_[fixed_buffer_used_size_] == '\0'); + glowable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_); + } + glowable_buffer_ += c; } - glowable_buffer_ += c; - } } inline int close_socket(socket_t sock) { #ifdef _WIN32 - return closesocket(sock); + return closesocket(sock); #else - return close(sock); + return close(sock); #endif } -template inline ssize_t handle_EINTR(T fn) { - ssize_t res = 0; - while (true) { - res = fn(); - if (res < 0 && errno == EINTR) { continue; } - break; - } - return res; +template inline ssize_t handle_EINTR(T fn) { + ssize_t res = 0; + while (true) { + res = fn(); + if (res < 0 && errno == EINTR) { + continue; + } + break; + } + return res; } inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) { - return handle_EINTR([&]() { - return recv(sock, + return handle_EINTR([&]() { + return recv(sock, #ifdef _WIN32 - static_cast(ptr), static_cast(size), + static_cast(ptr), + static_cast(size), #else - ptr, size, + ptr, + size, #endif - flags); - }); + flags); + }); } -inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size, - int flags) { - return handle_EINTR([&]() { - return send(sock, +inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags) { + return handle_EINTR([&]() { + return send(sock, #ifdef _WIN32 - static_cast(ptr), static_cast(size), + static_cast(ptr), + static_cast(size), #else - ptr, size, + ptr, + size, #endif - flags); - }); + flags); + }); } inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) { #ifdef CPPHTTPLIB_USE_POLL - struct pollfd pfd_read; - pfd_read.fd = sock; - pfd_read.events = POLLIN; + struct pollfd pfd_read; + pfd_read.fd = sock; + pfd_read.events = POLLIN; - auto timeout = static_cast(sec * 1000 + usec / 1000); + auto timeout = static_cast(sec * 1000 + usec / 1000); - return handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); }); + return handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); }); #else #ifndef _WIN32 - if (sock >= FD_SETSIZE) { return 1; } + if (sock >= FD_SETSIZE) { + return 1; + } #endif - fd_set fds; - FD_ZERO(&fds); - FD_SET(sock, &fds); + fd_set fds; + FD_ZERO(&fds); + FD_SET(sock, &fds); - timeval tv; - tv.tv_sec = static_cast(sec); - tv.tv_usec = static_cast(usec); + timeval tv; + tv.tv_sec = static_cast(sec); + tv.tv_usec = static_cast(usec); - return handle_EINTR([&]() { - return select(static_cast(sock + 1), &fds, nullptr, nullptr, &tv); - }); + return handle_EINTR([&]() { return select(static_cast(sock + 1), &fds, nullptr, nullptr, &tv); }); #endif } inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) { #ifdef CPPHTTPLIB_USE_POLL - struct pollfd pfd_read; - pfd_read.fd = sock; - pfd_read.events = POLLOUT; + struct pollfd pfd_read; + pfd_read.fd = sock; + pfd_read.events = POLLOUT; - auto timeout = static_cast(sec * 1000 + usec / 1000); + auto timeout = static_cast(sec * 1000 + usec / 1000); - return handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); }); + return handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); }); #else #ifndef _WIN32 - if (sock >= FD_SETSIZE) { return 1; } + if (sock >= FD_SETSIZE) { + return 1; + } #endif - fd_set fds; - FD_ZERO(&fds); - FD_SET(sock, &fds); + fd_set fds; + FD_ZERO(&fds); + FD_SET(sock, &fds); - timeval tv; - tv.tv_sec = static_cast(sec); - tv.tv_usec = static_cast(usec); + timeval tv; + tv.tv_sec = static_cast(sec); + tv.tv_usec = static_cast(usec); - return handle_EINTR([&]() { - return select(static_cast(sock + 1), nullptr, &fds, nullptr, &tv); - }); + return handle_EINTR([&]() { return select(static_cast(sock + 1), nullptr, &fds, nullptr, &tv); }); #endif } -inline Error wait_until_socket_is_ready(socket_t sock, time_t sec, - time_t usec) { +inline Error wait_until_socket_is_ready(socket_t sock, time_t sec, time_t usec) { #ifdef CPPHTTPLIB_USE_POLL - struct pollfd pfd_read; - pfd_read.fd = sock; - pfd_read.events = POLLIN | POLLOUT; + struct pollfd pfd_read; + pfd_read.fd = sock; + pfd_read.events = POLLIN | POLLOUT; - auto timeout = static_cast(sec * 1000 + usec / 1000); + auto timeout = static_cast(sec * 1000 + usec / 1000); - auto poll_res = handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); }); + auto poll_res = handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); }); - if (poll_res == 0) { return Error::ConnectionTimeout; } + if (poll_res == 0) { + return Error::ConnectionTimeout; + } - if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) { - auto error = 0; - socklen_t len = sizeof(error); - auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR, - reinterpret_cast(&error), &len); - auto successful = res >= 0 && !error; - return successful ? Error::Success : Error::Connection; - } + if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) { + auto error = 0; + socklen_t len = sizeof(error); + auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR, reinterpret_cast(&error), &len); + auto successful = res >= 0 && !error; + return successful ? Error::Success : Error::Connection; + } - return Error::Connection; + return Error::Connection; #else #ifndef _WIN32 - if (sock >= FD_SETSIZE) { return Error::Connection; } + if (sock >= FD_SETSIZE) { + return Error::Connection; + } #endif - fd_set fdsr; - FD_ZERO(&fdsr); - FD_SET(sock, &fdsr); + fd_set fdsr; + FD_ZERO(&fdsr); + FD_SET(sock, &fdsr); - auto fdsw = fdsr; - auto fdse = fdsr; + auto fdsw = fdsr; + auto fdse = fdsr; - timeval tv; - tv.tv_sec = static_cast(sec); - tv.tv_usec = static_cast(usec); + timeval tv; + tv.tv_sec = static_cast(sec); + tv.tv_usec = static_cast(usec); - auto ret = handle_EINTR([&]() { - return select(static_cast(sock + 1), &fdsr, &fdsw, &fdse, &tv); - }); + auto ret = handle_EINTR([&]() { return select(static_cast(sock + 1), &fdsr, &fdsw, &fdse, &tv); }); - if (ret == 0) { return Error::ConnectionTimeout; } + if (ret == 0) { + return Error::ConnectionTimeout; + } - if (ret > 0 && (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) { - auto error = 0; - socklen_t len = sizeof(error); - auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR, - reinterpret_cast(&error), &len); - auto successful = res >= 0 && !error; - return successful ? Error::Success : Error::Connection; - } - return Error::Connection; + if (ret > 0 && (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) { + auto error = 0; + socklen_t len = sizeof(error); + auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR, reinterpret_cast(&error), &len); + auto successful = res >= 0 && !error; + return successful ? Error::Success : Error::Connection; + } + return Error::Connection; #endif } inline bool is_socket_alive(socket_t sock) { - const auto val = detail::select_read(sock, 0, 0); - if (val == 0) { - return true; - } else if (val < 0 && errno == EBADF) { - return false; - } - char buf[1]; - return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0; + const auto val = detail::select_read(sock, 0, 0); + if (val == 0) { + return true; + } else if (val < 0 && errno == EBADF) { + return false; + } + char buf[1]; + return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0; } class SocketStream : public Stream { public: - SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec, - time_t write_timeout_sec, time_t write_timeout_usec); - ~SocketStream() override; + SocketStream(socket_t sock, + time_t read_timeout_sec, + time_t read_timeout_usec, + time_t write_timeout_sec, + time_t write_timeout_usec); + ~SocketStream() override; - bool is_readable() const override; - bool is_writable() const override; - ssize_t read(char *ptr, size_t size) override; - ssize_t write(const char *ptr, size_t size) override; - void get_remote_ip_and_port(std::string &ip, int &port) const override; - void get_local_ip_and_port(std::string &ip, int &port) const override; - socket_t socket() const override; + bool is_readable() const override; + bool is_writable() const override; + ssize_t read(char *ptr, size_t size) override; + ssize_t write(const char *ptr, size_t size) override; + void get_remote_ip_and_port(std::string &ip, int &port) const override; + void get_local_ip_and_port(std::string &ip, int &port) const override; + socket_t socket() const override; private: - socket_t sock_; - time_t read_timeout_sec_; - time_t read_timeout_usec_; - time_t write_timeout_sec_; - time_t write_timeout_usec_; + socket_t sock_; + time_t read_timeout_sec_; + time_t read_timeout_usec_; + time_t write_timeout_sec_; + time_t write_timeout_usec_; - std::vector read_buff_; - size_t read_buff_off_ = 0; - size_t read_buff_content_size_ = 0; + std::vector read_buff_; + size_t read_buff_off_ = 0; + size_t read_buff_content_size_ = 0; - static const size_t read_buff_size_ = 1024 * 4; + static const size_t read_buff_size_ = 1024 * 4; }; #ifdef CPPHTTPLIB_OPENSSL_SUPPORT class SSLSocketStream : public Stream { public: - SSLSocketStream(socket_t sock, SSL *ssl, time_t read_timeout_sec, - time_t read_timeout_usec, time_t write_timeout_sec, - time_t write_timeout_usec); - ~SSLSocketStream() override; + SSLSocketStream(socket_t sock, + SSL *ssl, + time_t read_timeout_sec, + time_t read_timeout_usec, + time_t write_timeout_sec, + time_t write_timeout_usec); + ~SSLSocketStream() override; - bool is_readable() const override; - bool is_writable() const override; - ssize_t read(char *ptr, size_t size) override; - ssize_t write(const char *ptr, size_t size) override; - void get_remote_ip_and_port(std::string &ip, int &port) const override; - void get_local_ip_and_port(std::string &ip, int &port) const override; - socket_t socket() const override; + bool is_readable() const override; + bool is_writable() const override; + ssize_t read(char *ptr, size_t size) override; + ssize_t write(const char *ptr, size_t size) override; + void get_remote_ip_and_port(std::string &ip, int &port) const override; + void get_local_ip_and_port(std::string &ip, int &port) const override; + socket_t socket() const override; private: - socket_t sock_; - SSL *ssl_; - time_t read_timeout_sec_; - time_t read_timeout_usec_; - time_t write_timeout_sec_; - time_t write_timeout_usec_; + socket_t sock_; + SSL *ssl_; + time_t read_timeout_sec_; + time_t read_timeout_usec_; + time_t write_timeout_sec_; + time_t write_timeout_usec_; }; #endif inline bool keep_alive(socket_t sock, time_t keep_alive_timeout_sec) { - using namespace std::chrono; - auto start = steady_clock::now(); - while (true) { - auto val = select_read(sock, 0, 10000); - if (val < 0) { - return false; - } else if (val == 0) { - auto current = steady_clock::now(); - auto duration = duration_cast(current - start); - auto timeout = keep_alive_timeout_sec * 1000; - if (duration.count() > timeout) { return false; } - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - } else { - return true; + using namespace std::chrono; + auto start = steady_clock::now(); + while (true) { + auto val = select_read(sock, 0, 10000); + if (val < 0) { + return false; + } else if (val == 0) { + auto current = steady_clock::now(); + auto duration = duration_cast(current - start); + auto timeout = keep_alive_timeout_sec * 1000; + if (duration.count() > timeout) { + return false; + } + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } else { + return true; + } } - } } -template -inline bool -process_server_socket_core(const std::atomic &svr_sock, socket_t sock, - size_t keep_alive_max_count, - time_t keep_alive_timeout_sec, T callback) { - assert(keep_alive_max_count > 0); - auto ret = false; - auto count = keep_alive_max_count; - while (svr_sock != INVALID_SOCKET && count > 0 && - keep_alive(sock, keep_alive_timeout_sec)) { - auto close_connection = count == 1; - auto connection_closed = false; - ret = callback(close_connection, connection_closed); - if (!ret || connection_closed) { break; } - count--; - } - return ret; +template +inline bool process_server_socket_core(const std::atomic &svr_sock, + socket_t sock, + size_t keep_alive_max_count, + time_t keep_alive_timeout_sec, + T callback) { + assert(keep_alive_max_count > 0); + auto ret = false; + auto count = keep_alive_max_count; + while (svr_sock != INVALID_SOCKET && count > 0 && keep_alive(sock, keep_alive_timeout_sec)) { + auto close_connection = count == 1; + auto connection_closed = false; + ret = callback(close_connection, connection_closed); + if (!ret || connection_closed) { + break; + } + count--; + } + return ret; } -template -inline bool -process_server_socket(const std::atomic &svr_sock, socket_t sock, - size_t keep_alive_max_count, - time_t keep_alive_timeout_sec, time_t read_timeout_sec, - time_t read_timeout_usec, time_t write_timeout_sec, - time_t write_timeout_usec, T callback) { - return process_server_socket_core( - svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec, - [&](bool close_connection, bool &connection_closed) { - SocketStream strm(sock, read_timeout_sec, read_timeout_usec, - write_timeout_sec, write_timeout_usec); - return callback(strm, close_connection, connection_closed); - }); +template +inline bool process_server_socket(const std::atomic &svr_sock, + socket_t sock, + size_t keep_alive_max_count, + time_t keep_alive_timeout_sec, + time_t read_timeout_sec, + time_t read_timeout_usec, + time_t write_timeout_sec, + time_t write_timeout_usec, + T callback) { + return process_server_socket_core( + svr_sock, + sock, + keep_alive_max_count, + keep_alive_timeout_sec, + [&](bool close_connection, bool &connection_closed) { + SocketStream strm(sock, read_timeout_sec, read_timeout_usec, write_timeout_sec, write_timeout_usec); + return callback(strm, close_connection, connection_closed); + }); } -inline bool process_client_socket(socket_t sock, time_t read_timeout_sec, - time_t read_timeout_usec, - time_t write_timeout_sec, - time_t write_timeout_usec, +inline bool process_client_socket(socket_t sock, + time_t read_timeout_sec, + time_t read_timeout_usec, + time_t write_timeout_sec, + time_t write_timeout_usec, std::function callback) { - SocketStream strm(sock, read_timeout_sec, read_timeout_usec, - write_timeout_sec, write_timeout_usec); - return callback(strm); + SocketStream strm(sock, read_timeout_sec, read_timeout_usec, write_timeout_sec, write_timeout_usec); + return callback(strm); } inline int shutdown_socket(socket_t sock) { #ifdef _WIN32 - return shutdown(sock, SD_BOTH); + return shutdown(sock, SD_BOTH); #else - return shutdown(sock, SHUT_RDWR); + return shutdown(sock, SHUT_RDWR); #endif } -template -socket_t create_socket(const std::string &host, const std::string &ip, int port, - int address_family, int socket_flags, bool tcp_nodelay, - SocketOptions socket_options, - BindOrConnect bind_or_connect) { - // Get address info - const char *node = nullptr; - struct addrinfo hints; - struct addrinfo *result; +template +socket_t create_socket(const std::string &host, + const std::string &ip, + int port, + int address_family, + int socket_flags, + bool tcp_nodelay, + SocketOptions socket_options, + BindOrConnect bind_or_connect) { + // Get address info + const char *node = nullptr; + struct addrinfo hints; + struct addrinfo *result; - memset(&hints, 0, sizeof(struct addrinfo)); - hints.ai_socktype = SOCK_STREAM; - hints.ai_protocol = 0; + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = 0; - if (!ip.empty()) { - node = ip.c_str(); - // Ask getaddrinfo to convert IP in c-string to address - hints.ai_family = AF_UNSPEC; - hints.ai_flags = AI_NUMERICHOST; - } else { - if (!host.empty()) { node = host.c_str(); } - hints.ai_family = address_family; - hints.ai_flags = socket_flags; - } + if (!ip.empty()) { + node = ip.c_str(); + // Ask getaddrinfo to convert IP in c-string to address + hints.ai_family = AF_UNSPEC; + hints.ai_flags = AI_NUMERICHOST; + } else { + if (!host.empty()) { + node = host.c_str(); + } + hints.ai_family = address_family; + hints.ai_flags = socket_flags; + } #ifndef _WIN32 - if (hints.ai_family == AF_UNIX) { - const auto addrlen = host.length(); - if (addrlen > sizeof(sockaddr_un::sun_path)) return INVALID_SOCKET; + if (hints.ai_family == AF_UNIX) { + const auto addrlen = host.length(); + if (addrlen > sizeof(sockaddr_un::sun_path)) { + return INVALID_SOCKET; + } - auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol); - if (sock != INVALID_SOCKET) { - sockaddr_un addr{}; - addr.sun_family = AF_UNIX; - std::copy(host.begin(), host.end(), addr.sun_path); + auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol); + if (sock != INVALID_SOCKET) { + sockaddr_un addr {}; + addr.sun_family = AF_UNIX; + std::copy(host.begin(), host.end(), addr.sun_path); - hints.ai_addr = reinterpret_cast(&addr); - hints.ai_addrlen = static_cast( - sizeof(addr) - sizeof(addr.sun_path) + addrlen); + hints.ai_addr = reinterpret_cast(&addr); + hints.ai_addrlen = static_cast(sizeof(addr) - sizeof(addr.sun_path) + addrlen); - fcntl(sock, F_SETFD, FD_CLOEXEC); - if (socket_options) { socket_options(sock); } + fcntl(sock, F_SETFD, FD_CLOEXEC); + if (socket_options) { + socket_options(sock); + } - if (!bind_or_connect(sock, hints)) { - close_socket(sock); - sock = INVALID_SOCKET; - } + if (!bind_or_connect(sock, hints)) { + close_socket(sock); + sock = INVALID_SOCKET; + } + } + return sock; } - return sock; - } #endif - auto service = std::to_string(port); + auto service = std::to_string(port); - if (getaddrinfo(node, service.c_str(), &hints, &result)) { + if (getaddrinfo(node, service.c_str(), &hints, &result)) { #if defined __linux__ && !defined __ANDROID__ - res_init(); + res_init(); #endif - return INVALID_SOCKET; - } + return INVALID_SOCKET; + } - for (auto rp = result; rp; rp = rp->ai_next) { - // Create a socket + for (auto rp = result; rp; rp = rp->ai_next) { + // Create a socket #ifdef _WIN32 - auto sock = - WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0, - WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED); - /** + auto sock = WSASocketW(rp->ai_family, + rp->ai_socktype, + rp->ai_protocol, + nullptr, + 0, + WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED); + /** * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1 * and above the socket creation fails on older Windows Systems. * @@ -2815,99 +2934,100 @@ socket_t create_socket(const std::string &host, const std::string &ip, int port, * SP1, and later * */ - if (sock == INVALID_SOCKET) { - sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); - } + if (sock == INVALID_SOCKET) { + sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); + } #else - auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); + auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); #endif - if (sock == INVALID_SOCKET) { continue; } + if (sock == INVALID_SOCKET) { + continue; + } #ifndef _WIN32 - if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) { - close_socket(sock); - continue; - } + if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) { + close_socket(sock); + continue; + } #endif - if (tcp_nodelay) { - auto yes = 1; + if (tcp_nodelay) { + auto yes = 1; #ifdef _WIN32 - setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, - reinterpret_cast(&yes), sizeof(yes)); + setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast(&yes), sizeof(yes)); #else - setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, - reinterpret_cast(&yes), sizeof(yes)); + setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast(&yes), sizeof(yes)); #endif - } + } - if (socket_options) { socket_options(sock); } + if (socket_options) { + socket_options(sock); + } - if (rp->ai_family == AF_INET6) { - auto no = 0; + if (rp->ai_family == AF_INET6) { + auto no = 0; #ifdef _WIN32 - setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, - reinterpret_cast(&no), sizeof(no)); + setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast(&no), sizeof(no)); #else - setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, - reinterpret_cast(&no), sizeof(no)); + setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast(&no), sizeof(no)); #endif + } + + // bind or connect + if (bind_or_connect(sock, *rp)) { + freeaddrinfo(result); + return sock; + } + + close_socket(sock); } - // bind or connect - if (bind_or_connect(sock, *rp)) { - freeaddrinfo(result); - return sock; - } - - close_socket(sock); - } - - freeaddrinfo(result); - return INVALID_SOCKET; + freeaddrinfo(result); + return INVALID_SOCKET; } inline void set_nonblocking(socket_t sock, bool nonblocking) { #ifdef _WIN32 - auto flags = nonblocking ? 1UL : 0UL; - ioctlsocket(sock, FIONBIO, &flags); + auto flags = nonblocking ? 1UL : 0UL; + ioctlsocket(sock, FIONBIO, &flags); #else - auto flags = fcntl(sock, F_GETFL, 0); - fcntl(sock, F_SETFL, - nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK))); + auto flags = fcntl(sock, F_GETFL, 0); + fcntl(sock, F_SETFL, nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK))); #endif } inline bool is_connection_error() { #ifdef _WIN32 - return WSAGetLastError() != WSAEWOULDBLOCK; + return WSAGetLastError() != WSAEWOULDBLOCK; #else - return errno != EINPROGRESS; + return errno != EINPROGRESS; #endif } inline bool bind_ip_address(socket_t sock, const std::string &host) { - struct addrinfo hints; - struct addrinfo *result; + struct addrinfo hints; + struct addrinfo *result; - memset(&hints, 0, sizeof(struct addrinfo)); - hints.ai_family = AF_UNSPEC; - hints.ai_socktype = SOCK_STREAM; - hints.ai_protocol = 0; + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = 0; - if (getaddrinfo(host.c_str(), "0", &hints, &result)) { return false; } - - auto ret = false; - for (auto rp = result; rp; rp = rp->ai_next) { - const auto &ai = *rp; - if (!::bind(sock, ai.ai_addr, static_cast(ai.ai_addrlen))) { - ret = true; - break; + if (getaddrinfo(host.c_str(), "0", &hints, &result)) { + return false; } - } - freeaddrinfo(result); - return ret; + auto ret = false; + for (auto rp = result; rp; rp = rp->ai_next) { + const auto &ai = *rp; + if (!::bind(sock, ai.ai_addr, static_cast(ai.ai_addrlen))) { + ret = true; + break; + } + } + + freeaddrinfo(result); + return ret; } #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__ @@ -2916,1162 +3036,1357 @@ inline bool bind_ip_address(socket_t sock, const std::string &host) { #ifdef USE_IF2IP inline std::string if2ip(int address_family, const std::string &ifn) { - struct ifaddrs *ifap; - getifaddrs(&ifap); - std::string addr_candidate; - for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) { - if (ifa->ifa_addr && ifn == ifa->ifa_name && - (AF_UNSPEC == address_family || - ifa->ifa_addr->sa_family == address_family)) { - if (ifa->ifa_addr->sa_family == AF_INET) { - auto sa = reinterpret_cast(ifa->ifa_addr); - char buf[INET_ADDRSTRLEN]; - if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) { - freeifaddrs(ifap); - return std::string(buf, INET_ADDRSTRLEN); - } - } else if (ifa->ifa_addr->sa_family == AF_INET6) { - auto sa = reinterpret_cast(ifa->ifa_addr); - if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) { - char buf[INET6_ADDRSTRLEN] = {}; - if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) { - // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL - auto s6_addr_head = sa->sin6_addr.s6_addr[0]; - if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) { - addr_candidate = std::string(buf, INET6_ADDRSTRLEN); - } else { - freeifaddrs(ifap); - return std::string(buf, INET6_ADDRSTRLEN); + struct ifaddrs *ifap; + getifaddrs(&ifap); + std::string addr_candidate; + for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) { + if (ifa->ifa_addr && ifn == ifa->ifa_name && + (AF_UNSPEC == address_family || ifa->ifa_addr->sa_family == address_family)) { + if (ifa->ifa_addr->sa_family == AF_INET) { + auto sa = reinterpret_cast(ifa->ifa_addr); + char buf[INET_ADDRSTRLEN]; + if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) { + freeifaddrs(ifap); + return std::string(buf, INET_ADDRSTRLEN); + } + } else if (ifa->ifa_addr->sa_family == AF_INET6) { + auto sa = reinterpret_cast(ifa->ifa_addr); + if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) { + char buf[INET6_ADDRSTRLEN] = {}; + if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) { + // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL + auto s6_addr_head = sa->sin6_addr.s6_addr[0]; + if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) { + addr_candidate = std::string(buf, INET6_ADDRSTRLEN); + } else { + freeifaddrs(ifap); + return std::string(buf, INET6_ADDRSTRLEN); + } + } + } } - } } - } } - } - freeifaddrs(ifap); - return addr_candidate; + freeifaddrs(ifap); + return addr_candidate; } #endif -inline socket_t create_client_socket( - const std::string &host, const std::string &ip, int port, - int address_family, bool tcp_nodelay, SocketOptions socket_options, - time_t connection_timeout_sec, time_t connection_timeout_usec, - time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec, - time_t write_timeout_usec, const std::string &intf, Error &error) { - auto sock = create_socket( - host, ip, port, address_family, 0, tcp_nodelay, std::move(socket_options), - [&](socket_t sock2, struct addrinfo &ai) -> bool { - if (!intf.empty()) { +inline socket_t create_client_socket(const std::string &host, + const std::string &ip, + int port, + int address_family, + bool tcp_nodelay, + SocketOptions socket_options, + time_t connection_timeout_sec, + time_t connection_timeout_usec, + time_t read_timeout_sec, + time_t read_timeout_usec, + time_t write_timeout_sec, + time_t write_timeout_usec, + const std::string &intf, + Error &error) { + auto sock = create_socket( + host, + ip, + port, + address_family, + 0, + tcp_nodelay, + std::move(socket_options), + [&](socket_t sock2, struct addrinfo &ai) -> bool { + if (!intf.empty()) { #ifdef USE_IF2IP - auto ip_from_if = if2ip(address_family, intf); - if (ip_from_if.empty()) { ip_from_if = intf; } - if (!bind_ip_address(sock2, ip_from_if.c_str())) { - error = Error::BindIPAddress; - return false; - } + auto ip_from_if = if2ip(address_family, intf); + if (ip_from_if.empty()) { + ip_from_if = intf; + } + if (!bind_ip_address(sock2, ip_from_if.c_str())) { + error = Error::BindIPAddress; + return false; + } #endif - } + } - set_nonblocking(sock2, true); + set_nonblocking(sock2, true); - auto ret = - ::connect(sock2, ai.ai_addr, static_cast(ai.ai_addrlen)); + auto ret = ::connect(sock2, ai.ai_addr, static_cast(ai.ai_addrlen)); - if (ret < 0) { - if (is_connection_error()) { - error = Error::Connection; - return false; - } - error = wait_until_socket_is_ready(sock2, connection_timeout_sec, - connection_timeout_usec); - if (error != Error::Success) { return false; } - } + if (ret < 0) { + if (is_connection_error()) { + error = Error::Connection; + return false; + } + error = wait_until_socket_is_ready(sock2, connection_timeout_sec, connection_timeout_usec); + if (error != Error::Success) { + return false; + } + } - set_nonblocking(sock2, false); + set_nonblocking(sock2, false); - { + { #ifdef _WIN32 - auto timeout = static_cast(read_timeout_sec * 1000 + - read_timeout_usec / 1000); - setsockopt(sock2, SOL_SOCKET, SO_RCVTIMEO, - reinterpret_cast(&timeout), sizeof(timeout)); + auto timeout = static_cast(read_timeout_sec * 1000 + read_timeout_usec / 1000); + setsockopt(sock2, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast(&timeout), sizeof(timeout)); #else - timeval tv; - tv.tv_sec = static_cast(read_timeout_sec); - tv.tv_usec = static_cast(read_timeout_usec); - setsockopt(sock2, SOL_SOCKET, SO_RCVTIMEO, - reinterpret_cast(&tv), sizeof(tv)); + timeval tv; + tv.tv_sec = static_cast(read_timeout_sec); + tv.tv_usec = static_cast(read_timeout_usec); + setsockopt(sock2, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast(&tv), sizeof(tv)); #endif - } - { + } + { #ifdef _WIN32 - auto timeout = static_cast(write_timeout_sec * 1000 + - write_timeout_usec / 1000); - setsockopt(sock2, SOL_SOCKET, SO_SNDTIMEO, - reinterpret_cast(&timeout), sizeof(timeout)); + auto timeout = static_cast(write_timeout_sec * 1000 + write_timeout_usec / 1000); + setsockopt(sock2, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast(&timeout), sizeof(timeout)); #else - timeval tv; - tv.tv_sec = static_cast(write_timeout_sec); - tv.tv_usec = static_cast(write_timeout_usec); - setsockopt(sock2, SOL_SOCKET, SO_SNDTIMEO, - reinterpret_cast(&tv), sizeof(tv)); + timeval tv; + tv.tv_sec = static_cast(write_timeout_sec); + tv.tv_usec = static_cast(write_timeout_usec); + setsockopt(sock2, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast(&tv), sizeof(tv)); #endif - } + } + error = Error::Success; + return true; + }); + + if (sock != INVALID_SOCKET) { error = Error::Success; - return true; - }); + } else { + if (error == Error::Success) { + error = Error::Connection; + } + } - if (sock != INVALID_SOCKET) { - error = Error::Success; - } else { - if (error == Error::Success) { error = Error::Connection; } - } - - return sock; + return sock; } -inline bool get_ip_and_port(const struct sockaddr_storage &addr, - socklen_t addr_len, std::string &ip, int &port) { - if (addr.ss_family == AF_INET) { - port = ntohs(reinterpret_cast(&addr)->sin_port); - } else if (addr.ss_family == AF_INET6) { - port = - ntohs(reinterpret_cast(&addr)->sin6_port); - } else { - return false; - } +inline bool get_ip_and_port(const struct sockaddr_storage &addr, socklen_t addr_len, std::string &ip, int &port) { + if (addr.ss_family == AF_INET) { + port = ntohs(reinterpret_cast(&addr)->sin_port); + } else if (addr.ss_family == AF_INET6) { + port = ntohs(reinterpret_cast(&addr)->sin6_port); + } else { + return false; + } - std::array ipstr{}; - if (getnameinfo(reinterpret_cast(&addr), addr_len, - ipstr.data(), static_cast(ipstr.size()), nullptr, - 0, NI_NUMERICHOST)) { - return false; - } + std::array ipstr {}; + if (getnameinfo(reinterpret_cast(&addr), + addr_len, + ipstr.data(), + static_cast(ipstr.size()), + nullptr, + 0, + NI_NUMERICHOST)) { + return false; + } - ip = ipstr.data(); - return true; + ip = ipstr.data(); + return true; } inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) { - struct sockaddr_storage addr; - socklen_t addr_len = sizeof(addr); - if (!getsockname(sock, reinterpret_cast(&addr), - &addr_len)) { - get_ip_and_port(addr, addr_len, ip, port); - } + struct sockaddr_storage addr; + socklen_t addr_len = sizeof(addr); + if (!getsockname(sock, reinterpret_cast(&addr), &addr_len)) { + get_ip_and_port(addr, addr_len, ip, port); + } } inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) { - struct sockaddr_storage addr; - socklen_t addr_len = sizeof(addr); + struct sockaddr_storage addr; + socklen_t addr_len = sizeof(addr); - if (!getpeername(sock, reinterpret_cast(&addr), - &addr_len)) { + if (!getpeername(sock, reinterpret_cast(&addr), &addr_len)) { #ifndef _WIN32 - if (addr.ss_family == AF_UNIX) { + if (addr.ss_family == AF_UNIX) { #if defined(__linux__) - struct ucred ucred; - socklen_t len = sizeof(ucred); - if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) { - port = ucred.pid; - } -#elif defined(SOL_LOCAL) && defined(SO_PEERPID) // __APPLE__ - pid_t pid; - socklen_t len = sizeof(pid); - if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) { - port = pid; - } + struct ucred ucred; + socklen_t len = sizeof(ucred); + if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) { + port = ucred.pid; + } +#elif defined(SOL_LOCAL) && defined(SO_PEERPID) // __APPLE__ + pid_t pid; + socklen_t len = sizeof(pid); + if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) { + port = pid; + } #endif - return; + return; + } +#endif + get_ip_and_port(addr, addr_len, ip, port); } -#endif - get_ip_and_port(addr, addr_len, ip, port); - } } -inline constexpr unsigned int str2tag_core(const char *s, size_t l, - unsigned int h) { - return (l == 0) - ? h - : str2tag_core( - s + 1, l - 1, - // Unsets the 6 high bits of h, therefore no overflow happens - (((std::numeric_limits::max)() >> 6) & - h * 33) ^ - static_cast(*s)); +inline constexpr unsigned int str2tag_core(const char *s, size_t l, unsigned int h) { + return (l == 0) + ? h + : str2tag_core(s + 1, + l - 1, + // Unsets the 6 high bits of h, therefore no overflow happens + (((std::numeric_limits::max)() >> 6) & h * 33) ^ static_cast(*s)); } inline unsigned int str2tag(const std::string &s) { - return str2tag_core(s.data(), s.size(), 0); + return str2tag_core(s.data(), s.size(), 0); } namespace udl { inline constexpr unsigned int operator"" _t(const char *s, size_t l) { - return str2tag_core(s, l, 0); + return str2tag_core(s, l, 0); } -} // namespace udl +} // namespace udl -inline const char * -find_content_type(const std::string &path, - const std::map &user_data) { - auto ext = file_extension(path); +inline const char *find_content_type(const std::string &path, const std::map &user_data) { + auto ext = file_extension(path); - auto it = user_data.find(ext); - if (it != user_data.end()) { return it->second.c_str(); } + auto it = user_data.find(ext); + if (it != user_data.end()) { + return it->second.c_str(); + } - using udl::operator""_t; + using udl::operator""_t; - switch (str2tag(ext)) { - default: return nullptr; - case "css"_t: return "text/css"; - case "csv"_t: return "text/csv"; - case "htm"_t: - case "html"_t: return "text/html"; - case "js"_t: - case "mjs"_t: return "text/javascript"; - case "txt"_t: return "text/plain"; - case "vtt"_t: return "text/vtt"; + switch (str2tag(ext)) { + default: + return nullptr; + case "css"_t: + return "text/css"; + case "csv"_t: + return "text/csv"; + case "htm"_t: + case "html"_t: + return "text/html"; + case "js"_t: + case "mjs"_t: + return "text/javascript"; + case "txt"_t: + return "text/plain"; + case "vtt"_t: + return "text/vtt"; - case "apng"_t: return "image/apng"; - case "avif"_t: return "image/avif"; - case "bmp"_t: return "image/bmp"; - case "gif"_t: return "image/gif"; - case "png"_t: return "image/png"; - case "svg"_t: return "image/svg+xml"; - case "webp"_t: return "image/webp"; - case "ico"_t: return "image/x-icon"; - case "tif"_t: return "image/tiff"; - case "tiff"_t: return "image/tiff"; - case "jpg"_t: - case "jpeg"_t: return "image/jpeg"; + case "apng"_t: + return "image/apng"; + case "avif"_t: + return "image/avif"; + case "bmp"_t: + return "image/bmp"; + case "gif"_t: + return "image/gif"; + case "png"_t: + return "image/png"; + case "svg"_t: + return "image/svg+xml"; + case "webp"_t: + return "image/webp"; + case "ico"_t: + return "image/x-icon"; + case "tif"_t: + return "image/tiff"; + case "tiff"_t: + return "image/tiff"; + case "jpg"_t: + case "jpeg"_t: + return "image/jpeg"; - case "mp4"_t: return "video/mp4"; - case "mpeg"_t: return "video/mpeg"; - case "webm"_t: return "video/webm"; + case "mp4"_t: + return "video/mp4"; + case "mpeg"_t: + return "video/mpeg"; + case "webm"_t: + return "video/webm"; - case "mp3"_t: return "audio/mp3"; - case "mpga"_t: return "audio/mpeg"; - case "weba"_t: return "audio/webm"; - case "wav"_t: return "audio/wave"; + case "mp3"_t: + return "audio/mp3"; + case "mpga"_t: + return "audio/mpeg"; + case "weba"_t: + return "audio/webm"; + case "wav"_t: + return "audio/wave"; - case "otf"_t: return "font/otf"; - case "ttf"_t: return "font/ttf"; - case "woff"_t: return "font/woff"; - case "woff2"_t: return "font/woff2"; + case "otf"_t: + return "font/otf"; + case "ttf"_t: + return "font/ttf"; + case "woff"_t: + return "font/woff"; + case "woff2"_t: + return "font/woff2"; - case "7z"_t: return "application/x-7z-compressed"; - case "atom"_t: return "application/atom+xml"; - case "pdf"_t: return "application/pdf"; - case "json"_t: return "application/json"; - case "rss"_t: return "application/rss+xml"; - case "tar"_t: return "application/x-tar"; - case "xht"_t: - case "xhtml"_t: return "application/xhtml+xml"; - case "xslt"_t: return "application/xslt+xml"; - case "xml"_t: return "application/xml"; - case "gz"_t: return "application/gzip"; - case "zip"_t: return "application/zip"; - case "wasm"_t: return "application/wasm"; - } + case "7z"_t: + return "application/x-7z-compressed"; + case "atom"_t: + return "application/atom+xml"; + case "pdf"_t: + return "application/pdf"; + case "json"_t: + return "application/json"; + case "rss"_t: + return "application/rss+xml"; + case "tar"_t: + return "application/x-tar"; + case "xht"_t: + case "xhtml"_t: + return "application/xhtml+xml"; + case "xslt"_t: + return "application/xslt+xml"; + case "xml"_t: + return "application/xml"; + case "gz"_t: + return "application/gzip"; + case "zip"_t: + return "application/zip"; + case "wasm"_t: + return "application/wasm"; + } } inline const char *status_message(int status) { - switch (status) { - case 100: return "Continue"; - case 101: return "Switching Protocol"; - case 102: return "Processing"; - case 103: return "Early Hints"; - case 200: return "OK"; - case 201: return "Created"; - case 202: return "Accepted"; - case 203: return "Non-Authoritative Information"; - case 204: return "No Content"; - case 205: return "Reset Content"; - case 206: return "Partial Content"; - case 207: return "Multi-Status"; - case 208: return "Already Reported"; - case 226: return "IM Used"; - case 300: return "Multiple Choice"; - case 301: return "Moved Permanently"; - case 302: return "Found"; - case 303: return "See Other"; - case 304: return "Not Modified"; - case 305: return "Use Proxy"; - case 306: return "unused"; - case 307: return "Temporary Redirect"; - case 308: return "Permanent Redirect"; - case 400: return "Bad Request"; - case 401: return "Unauthorized"; - case 402: return "Payment Required"; - case 403: return "Forbidden"; - case 404: return "Not Found"; - case 405: return "Method Not Allowed"; - case 406: return "Not Acceptable"; - case 407: return "Proxy Authentication Required"; - case 408: return "Request Timeout"; - case 409: return "Conflict"; - case 410: return "Gone"; - case 411: return "Length Required"; - case 412: return "Precondition Failed"; - case 413: return "Payload Too Large"; - case 414: return "URI Too Long"; - case 415: return "Unsupported Media Type"; - case 416: return "Range Not Satisfiable"; - case 417: return "Expectation Failed"; - case 418: return "I'm a teapot"; - case 421: return "Misdirected Request"; - case 422: return "Unprocessable Entity"; - case 423: return "Locked"; - case 424: return "Failed Dependency"; - case 425: return "Too Early"; - case 426: return "Upgrade Required"; - case 428: return "Precondition Required"; - case 429: return "Too Many Requests"; - case 431: return "Request Header Fields Too Large"; - case 451: return "Unavailable For Legal Reasons"; - case 501: return "Not Implemented"; - case 502: return "Bad Gateway"; - case 503: return "Service Unavailable"; - case 504: return "Gateway Timeout"; - case 505: return "HTTP Version Not Supported"; - case 506: return "Variant Also Negotiates"; - case 507: return "Insufficient Storage"; - case 508: return "Loop Detected"; - case 510: return "Not Extended"; - case 511: return "Network Authentication Required"; + switch (status) { + case 100: + return "Continue"; + case 101: + return "Switching Protocol"; + case 102: + return "Processing"; + case 103: + return "Early Hints"; + case 200: + return "OK"; + case 201: + return "Created"; + case 202: + return "Accepted"; + case 203: + return "Non-Authoritative Information"; + case 204: + return "No Content"; + case 205: + return "Reset Content"; + case 206: + return "Partial Content"; + case 207: + return "Multi-Status"; + case 208: + return "Already Reported"; + case 226: + return "IM Used"; + case 300: + return "Multiple Choice"; + case 301: + return "Moved Permanently"; + case 302: + return "Found"; + case 303: + return "See Other"; + case 304: + return "Not Modified"; + case 305: + return "Use Proxy"; + case 306: + return "unused"; + case 307: + return "Temporary Redirect"; + case 308: + return "Permanent Redirect"; + case 400: + return "Bad Request"; + case 401: + return "Unauthorized"; + case 402: + return "Payment Required"; + case 403: + return "Forbidden"; + case 404: + return "Not Found"; + case 405: + return "Method Not Allowed"; + case 406: + return "Not Acceptable"; + case 407: + return "Proxy Authentication Required"; + case 408: + return "Request Timeout"; + case 409: + return "Conflict"; + case 410: + return "Gone"; + case 411: + return "Length Required"; + case 412: + return "Precondition Failed"; + case 413: + return "Payload Too Large"; + case 414: + return "URI Too Long"; + case 415: + return "Unsupported Media Type"; + case 416: + return "Range Not Satisfiable"; + case 417: + return "Expectation Failed"; + case 418: + return "I'm a teapot"; + case 421: + return "Misdirected Request"; + case 422: + return "Unprocessable Entity"; + case 423: + return "Locked"; + case 424: + return "Failed Dependency"; + case 425: + return "Too Early"; + case 426: + return "Upgrade Required"; + case 428: + return "Precondition Required"; + case 429: + return "Too Many Requests"; + case 431: + return "Request Header Fields Too Large"; + case 451: + return "Unavailable For Legal Reasons"; + case 501: + return "Not Implemented"; + case 502: + return "Bad Gateway"; + case 503: + return "Service Unavailable"; + case 504: + return "Gateway Timeout"; + case 505: + return "HTTP Version Not Supported"; + case 506: + return "Variant Also Negotiates"; + case 507: + return "Insufficient Storage"; + case 508: + return "Loop Detected"; + case 510: + return "Not Extended"; + case 511: + return "Network Authentication Required"; - default: - case 500: return "Internal Server Error"; - } + default: + case 500: + return "Internal Server Error"; + } } inline bool can_compress_content_type(const std::string &content_type) { - using udl::operator""_t; + using udl::operator""_t; - auto tag = str2tag(content_type); + auto tag = str2tag(content_type); - switch (tag) { - case "image/svg+xml"_t: - case "application/javascript"_t: - case "application/json"_t: - case "application/xml"_t: - case "application/protobuf"_t: - case "application/xhtml+xml"_t: return true; + switch (tag) { + case "image/svg+xml"_t: + case "application/javascript"_t: + case "application/json"_t: + case "application/xml"_t: + case "application/protobuf"_t: + case "application/xhtml+xml"_t: + return true; - default: - return !content_type.rfind("text/", 0) && tag != "text/event-stream"_t; - } + default: + return !content_type.rfind("text/", 0) && tag != "text/event-stream"_t; + } } inline EncodingType encoding_type(const Request &req, const Response &res) { - auto ret = - detail::can_compress_content_type(res.get_header_value("Content-Type")); - if (!ret) { return EncodingType::None; } + auto ret = detail::can_compress_content_type(res.get_header_value("Content-Type")); + if (!ret) { + return EncodingType::None; + } - const auto &s = req.get_header_value("Accept-Encoding"); - (void)(s); + const auto &s = req.get_header_value("Accept-Encoding"); + (void)(s); #ifdef CPPHTTPLIB_BROTLI_SUPPORT - // TODO: 'Accept-Encoding' has br, not br;q=0 - ret = s.find("br") != std::string::npos; - if (ret) { return EncodingType::Brotli; } + // TODO: 'Accept-Encoding' has br, not br;q=0 + ret = s.find("br") != std::string::npos; + if (ret) { + return EncodingType::Brotli; + } #endif #ifdef CPPHTTPLIB_ZLIB_SUPPORT - // TODO: 'Accept-Encoding' has gzip, not gzip;q=0 - ret = s.find("gzip") != std::string::npos; - if (ret) { return EncodingType::Gzip; } + // TODO: 'Accept-Encoding' has gzip, not gzip;q=0 + ret = s.find("gzip") != std::string::npos; + if (ret) { + return EncodingType::Gzip; + } #endif - return EncodingType::None; + return EncodingType::None; } -inline bool nocompressor::compress(const char *data, size_t data_length, - bool /*last*/, Callback callback) { - if (!data_length) { return true; } - return callback(data, data_length); +inline bool nocompressor::compress(const char *data, size_t data_length, bool /*last*/, Callback callback) { + if (!data_length) { + return true; + } + return callback(data, data_length); } #ifdef CPPHTTPLIB_ZLIB_SUPPORT inline gzip_compressor::gzip_compressor() { - std::memset(&strm_, 0, sizeof(strm_)); - strm_.zalloc = Z_NULL; - strm_.zfree = Z_NULL; - strm_.opaque = Z_NULL; + std::memset(&strm_, 0, sizeof(strm_)); + strm_.zalloc = Z_NULL; + strm_.zfree = Z_NULL; + strm_.opaque = Z_NULL; - is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, - Z_DEFAULT_STRATEGY) == Z_OK; + is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY) == Z_OK; } -inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); } +inline gzip_compressor::~gzip_compressor() { + deflateEnd(&strm_); +} -inline bool gzip_compressor::compress(const char *data, size_t data_length, - bool last, Callback callback) { - assert(is_valid_); +inline bool gzip_compressor::compress(const char *data, size_t data_length, bool last, Callback callback) { + assert(is_valid_); - do { - constexpr size_t max_avail_in = - (std::numeric_limits::max)(); - - strm_.avail_in = static_cast( - (std::min)(data_length, max_avail_in)); - strm_.next_in = const_cast(reinterpret_cast(data)); - - data_length -= strm_.avail_in; - data += strm_.avail_in; - - auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH; - auto ret = Z_OK; - - std::array buff{}; do { - strm_.avail_out = static_cast(buff.size()); - strm_.next_out = reinterpret_cast(buff.data()); + constexpr size_t max_avail_in = (std::numeric_limits::max)(); - ret = deflate(&strm_, flush); - if (ret == Z_STREAM_ERROR) { return false; } + strm_.avail_in = static_cast((std::min)(data_length, max_avail_in)); + strm_.next_in = const_cast(reinterpret_cast(data)); - if (!callback(buff.data(), buff.size() - strm_.avail_out)) { - return false; - } - } while (strm_.avail_out == 0); + data_length -= strm_.avail_in; + data += strm_.avail_in; - assert((flush == Z_FINISH && ret == Z_STREAM_END) || - (flush == Z_NO_FLUSH && ret == Z_OK)); - assert(strm_.avail_in == 0); - } while (data_length > 0); + auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH; + auto ret = Z_OK; - return true; + std::array buff {}; + do { + strm_.avail_out = static_cast(buff.size()); + strm_.next_out = reinterpret_cast(buff.data()); + + ret = deflate(&strm_, flush); + if (ret == Z_STREAM_ERROR) { + return false; + } + + if (!callback(buff.data(), buff.size() - strm_.avail_out)) { + return false; + } + } while (strm_.avail_out == 0); + + assert((flush == Z_FINISH && ret == Z_STREAM_END) || (flush == Z_NO_FLUSH && ret == Z_OK)); + assert(strm_.avail_in == 0); + } while (data_length > 0); + + return true; } inline gzip_decompressor::gzip_decompressor() { - std::memset(&strm_, 0, sizeof(strm_)); - strm_.zalloc = Z_NULL; - strm_.zfree = Z_NULL; - strm_.opaque = Z_NULL; + std::memset(&strm_, 0, sizeof(strm_)); + strm_.zalloc = Z_NULL; + strm_.zfree = Z_NULL; + strm_.opaque = Z_NULL; - // 15 is the value of wbits, which should be at the maximum possible value - // to ensure that any gzip stream can be decoded. The offset of 32 specifies - // that the stream type should be automatically detected either gzip or - // deflate. - is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK; + // 15 is the value of wbits, which should be at the maximum possible value + // to ensure that any gzip stream can be decoded. The offset of 32 specifies + // that the stream type should be automatically detected either gzip or + // deflate. + is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK; } -inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); } +inline gzip_decompressor::~gzip_decompressor() { + inflateEnd(&strm_); +} -inline bool gzip_decompressor::is_valid() const { return is_valid_; } +inline bool gzip_decompressor::is_valid() const { + return is_valid_; +} -inline bool gzip_decompressor::decompress(const char *data, size_t data_length, - Callback callback) { - assert(is_valid_); +inline bool gzip_decompressor::decompress(const char *data, size_t data_length, Callback callback) { + assert(is_valid_); - auto ret = Z_OK; + auto ret = Z_OK; - do { - constexpr size_t max_avail_in = - (std::numeric_limits::max)(); + do { + constexpr size_t max_avail_in = (std::numeric_limits::max)(); - strm_.avail_in = static_cast( - (std::min)(data_length, max_avail_in)); - strm_.next_in = const_cast(reinterpret_cast(data)); + strm_.avail_in = static_cast((std::min)(data_length, max_avail_in)); + strm_.next_in = const_cast(reinterpret_cast(data)); - data_length -= strm_.avail_in; - data += strm_.avail_in; + data_length -= strm_.avail_in; + data += strm_.avail_in; - std::array buff{}; - while (strm_.avail_in > 0) { - strm_.avail_out = static_cast(buff.size()); - strm_.next_out = reinterpret_cast(buff.data()); + std::array buff {}; + while (strm_.avail_in > 0) { + strm_.avail_out = static_cast(buff.size()); + strm_.next_out = reinterpret_cast(buff.data()); - auto prev_avail_in = strm_.avail_in; + auto prev_avail_in = strm_.avail_in; - ret = inflate(&strm_, Z_NO_FLUSH); + ret = inflate(&strm_, Z_NO_FLUSH); - if (prev_avail_in - strm_.avail_in == 0) { return false; } + if (prev_avail_in - strm_.avail_in == 0) { + return false; + } - assert(ret != Z_STREAM_ERROR); - switch (ret) { - case Z_NEED_DICT: - case Z_DATA_ERROR: - case Z_MEM_ERROR: inflateEnd(&strm_); return false; - } + assert(ret != Z_STREAM_ERROR); + switch (ret) { + case Z_NEED_DICT: + case Z_DATA_ERROR: + case Z_MEM_ERROR: + inflateEnd(&strm_); + return false; + } - if (!callback(buff.data(), buff.size() - strm_.avail_out)) { - return false; - } - } + if (!callback(buff.data(), buff.size() - strm_.avail_out)) { + return false; + } + } - if (ret != Z_OK && ret != Z_STREAM_END) return false; + if (ret != Z_OK && ret != Z_STREAM_END) { + return false; + } - } while (data_length > 0); + } while (data_length > 0); - return true; + return true; } #endif #ifdef CPPHTTPLIB_BROTLI_SUPPORT inline brotli_compressor::brotli_compressor() { - state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr); + state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr); } inline brotli_compressor::~brotli_compressor() { - BrotliEncoderDestroyInstance(state_); + BrotliEncoderDestroyInstance(state_); } -inline bool brotli_compressor::compress(const char *data, size_t data_length, - bool last, Callback callback) { - std::array buff{}; +inline bool brotli_compressor::compress(const char *data, size_t data_length, bool last, Callback callback) { + std::array buff {}; - auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS; - auto available_in = data_length; - auto next_in = reinterpret_cast(data); + auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS; + auto available_in = data_length; + auto next_in = reinterpret_cast(data); - for (;;) { - if (last) { - if (BrotliEncoderIsFinished(state_)) { break; } - } else { - if (!available_in) { break; } + for (;;) { + if (last) { + if (BrotliEncoderIsFinished(state_)) { + break; + } + } else { + if (!available_in) { + break; + } + } + + auto available_out = buff.size(); + auto next_out = buff.data(); + + if (!BrotliEncoderCompressStream(state_, + operation, + &available_in, + &next_in, + &available_out, + &next_out, + nullptr)) { + return false; + } + + auto output_bytes = buff.size() - available_out; + if (output_bytes) { + callback(reinterpret_cast(buff.data()), output_bytes); + } } - auto available_out = buff.size(); - auto next_out = buff.data(); - - if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in, - &available_out, &next_out, nullptr)) { - return false; - } - - auto output_bytes = buff.size() - available_out; - if (output_bytes) { - callback(reinterpret_cast(buff.data()), output_bytes); - } - } - - return true; + return true; } inline brotli_decompressor::brotli_decompressor() { - decoder_s = BrotliDecoderCreateInstance(0, 0, 0); - decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT - : BROTLI_DECODER_RESULT_ERROR; + decoder_s = BrotliDecoderCreateInstance(0, 0, 0); + decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT : BROTLI_DECODER_RESULT_ERROR; } inline brotli_decompressor::~brotli_decompressor() { - if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); } + if (decoder_s) { + BrotliDecoderDestroyInstance(decoder_s); + } } -inline bool brotli_decompressor::is_valid() const { return decoder_s; } +inline bool brotli_decompressor::is_valid() const { + return decoder_s; +} -inline bool brotli_decompressor::decompress(const char *data, - size_t data_length, - Callback callback) { - if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS || - decoder_r == BROTLI_DECODER_RESULT_ERROR) { - return 0; - } +inline bool brotli_decompressor::decompress(const char *data, size_t data_length, Callback callback) { + if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS || decoder_r == BROTLI_DECODER_RESULT_ERROR) { + return 0; + } - auto next_in = reinterpret_cast(data); - size_t avail_in = data_length; - size_t total_out; + auto next_in = reinterpret_cast(data); + size_t avail_in = data_length; + size_t total_out; - decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT; + decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT; - std::array buff{}; - while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) { - char *next_out = buff.data(); - size_t avail_out = buff.size(); + std::array buff {}; + while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) { + char *next_out = buff.data(); + size_t avail_out = buff.size(); - decoder_r = BrotliDecoderDecompressStream( - decoder_s, &avail_in, &next_in, &avail_out, - reinterpret_cast(&next_out), &total_out); + decoder_r = BrotliDecoderDecompressStream(decoder_s, + &avail_in, + &next_in, + &avail_out, + reinterpret_cast(&next_out), + &total_out); - if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; } + if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { + return false; + } - if (!callback(buff.data(), buff.size() - avail_out)) { return false; } - } + if (!callback(buff.data(), buff.size() - avail_out)) { + return false; + } + } - return decoder_r == BROTLI_DECODER_RESULT_SUCCESS || - decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT; + return decoder_r == BROTLI_DECODER_RESULT_SUCCESS || decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT; } #endif inline bool has_header(const Headers &headers, const std::string &key) { - return headers.find(key) != headers.end(); + return headers.find(key) != headers.end(); } -inline const char *get_header_value(const Headers &headers, - const std::string &key, size_t id, - const char *def) { - auto rng = headers.equal_range(key); - auto it = rng.first; - std::advance(it, static_cast(id)); - if (it != rng.second) { return it->second.c_str(); } - return def; +inline const char *get_header_value(const Headers &headers, const std::string &key, size_t id, const char *def) { + auto rng = headers.equal_range(key); + auto it = rng.first; + std::advance(it, static_cast(id)); + if (it != rng.second) { + return it->second.c_str(); + } + return def; } inline bool compare_case_ignore(const std::string &a, const std::string &b) { - if (a.size() != b.size()) { return false; } - for (size_t i = 0; i < b.size(); i++) { - if (::tolower(a[i]) != ::tolower(b[i])) { return false; } - } - return true; + if (a.size() != b.size()) { + return false; + } + for (size_t i = 0; i < b.size(); i++) { + if (::tolower(a[i]) != ::tolower(b[i])) { + return false; + } + } + return true; } -template -inline bool parse_header(const char *beg, const char *end, T fn) { - // Skip trailing spaces and tabs. - while (beg < end && is_space_or_tab(end[-1])) { - end--; - } +template inline bool parse_header(const char *beg, const char *end, T fn) { + // Skip trailing spaces and tabs. + while (beg < end && is_space_or_tab(end[-1])) { + end--; + } - auto p = beg; - while (p < end && *p != ':') { - p++; - } + auto p = beg; + while (p < end && *p != ':') { + p++; + } - if (p == end) { return false; } + if (p == end) { + return false; + } - auto key_end = p; + auto key_end = p; - if (*p++ != ':') { return false; } + if (*p++ != ':') { + return false; + } - while (p < end && is_space_or_tab(*p)) { - p++; - } + while (p < end && is_space_or_tab(*p)) { + p++; + } - if (p < end) { - auto key = std::string(beg, key_end); - auto val = compare_case_ignore(key, "Location") - ? std::string(p, end) - : decode_url(std::string(p, end), false); - fn(std::move(key), std::move(val)); - return true; - } + if (p < end) { + auto key = std::string(beg, key_end); + auto val = compare_case_ignore(key, "Location") ? std::string(p, end) : decode_url(std::string(p, end), false); + fn(std::move(key), std::move(val)); + return true; + } - return false; + return false; } inline bool read_headers(Stream &strm, Headers &headers) { - const auto bufsiz = 2048; - char buf[bufsiz]; - stream_line_reader line_reader(strm, buf, bufsiz); + const auto bufsiz = 2048; + char buf[bufsiz]; + stream_line_reader line_reader(strm, buf, bufsiz); - for (;;) { - if (!line_reader.getline()) { return false; } + for (;;) { + if (!line_reader.getline()) { + return false; + } - // Check if the line ends with CRLF. - auto line_terminator_len = 2; - if (line_reader.end_with_crlf()) { - // Blank line indicates end of headers. - if (line_reader.size() == 2) { break; } + // Check if the line ends with CRLF. + auto line_terminator_len = 2; + if (line_reader.end_with_crlf()) { + // Blank line indicates end of headers. + if (line_reader.size() == 2) { + break; + } #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR - } else { - // Blank line indicates end of headers. - if (line_reader.size() == 1) { break; } - line_terminator_len = 1; - } + } else { + // Blank line indicates end of headers. + if (line_reader.size() == 1) { + break; + } + line_terminator_len = 1; + } #else - } else { - continue; // Skip invalid line. - } + } else { + continue; // Skip invalid line. + } #endif - if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; } + if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { + return false; + } - // Exclude line terminator - auto end = line_reader.ptr() + line_reader.size() - line_terminator_len; + // Exclude line terminator + auto end = line_reader.ptr() + line_reader.size() - line_terminator_len; - parse_header(line_reader.ptr(), end, - [&](std::string &&key, std::string &&val) { - headers.emplace(std::move(key), std::move(val)); - }); - } + parse_header(line_reader.ptr(), end, [&](std::string &&key, std::string &&val) { + headers.emplace(std::move(key), std::move(val)); + }); + } - return true; + return true; } -inline bool read_content_with_length(Stream &strm, uint64_t len, - Progress progress, - ContentReceiverWithProgress out) { - char buf[CPPHTTPLIB_RECV_BUFSIZ]; +inline bool read_content_with_length(Stream &strm, uint64_t len, Progress progress, ContentReceiverWithProgress out) { + char buf[CPPHTTPLIB_RECV_BUFSIZ]; - uint64_t r = 0; - while (r < len) { - auto read_len = static_cast(len - r); - auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ)); - if (n <= 0) { return false; } + uint64_t r = 0; + while (r < len) { + auto read_len = static_cast(len - r); + auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ)); + if (n <= 0) { + return false; + } - if (!out(buf, static_cast(n), r, len)) { return false; } - r += static_cast(n); + if (!out(buf, static_cast(n), r, len)) { + return false; + } + r += static_cast(n); - if (progress) { - if (!progress(r, len)) { return false; } + if (progress) { + if (!progress(r, len)) { + return false; + } + } } - } - return true; + return true; } inline void skip_content_with_length(Stream &strm, uint64_t len) { - char buf[CPPHTTPLIB_RECV_BUFSIZ]; - uint64_t r = 0; - while (r < len) { - auto read_len = static_cast(len - r); - auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ)); - if (n <= 0) { return; } - r += static_cast(n); - } + char buf[CPPHTTPLIB_RECV_BUFSIZ]; + uint64_t r = 0; + while (r < len) { + auto read_len = static_cast(len - r); + auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ)); + if (n <= 0) { + return; + } + r += static_cast(n); + } } -inline bool read_content_without_length(Stream &strm, - ContentReceiverWithProgress out) { - char buf[CPPHTTPLIB_RECV_BUFSIZ]; - uint64_t r = 0; - for (;;) { - auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ); - if (n < 0) { - return false; - } else if (n == 0) { - return true; +inline bool read_content_without_length(Stream &strm, ContentReceiverWithProgress out) { + char buf[CPPHTTPLIB_RECV_BUFSIZ]; + uint64_t r = 0; + for (;;) { + auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ); + if (n < 0) { + return false; + } else if (n == 0) { + return true; + } + + if (!out(buf, static_cast(n), r, 0)) { + return false; + } + r += static_cast(n); } - if (!out(buf, static_cast(n), r, 0)) { return false; } - r += static_cast(n); - } - - return true; + return true; } -template -inline bool read_content_chunked(Stream &strm, T &x, - ContentReceiverWithProgress out) { - const auto bufsiz = 16; - char buf[bufsiz]; +template inline bool read_content_chunked(Stream &strm, T &x, ContentReceiverWithProgress out) { + const auto bufsiz = 16; + char buf[bufsiz]; - stream_line_reader line_reader(strm, buf, bufsiz); + stream_line_reader line_reader(strm, buf, bufsiz); - if (!line_reader.getline()) { return false; } - - unsigned long chunk_len; - while (true) { - char *end_ptr; - - chunk_len = std::strtoul(line_reader.ptr(), &end_ptr, 16); - - if (end_ptr == line_reader.ptr()) { return false; } - if (chunk_len == ULONG_MAX) { return false; } - - if (chunk_len == 0) { break; } - - if (!read_content_with_length(strm, chunk_len, nullptr, out)) { - return false; + if (!line_reader.getline()) { + return false; } - if (!line_reader.getline()) { return false; } + unsigned long chunk_len; + while (true) { + char *end_ptr; - if (strcmp(line_reader.ptr(), "\r\n")) { return false; } + chunk_len = std::strtoul(line_reader.ptr(), &end_ptr, 16); - if (!line_reader.getline()) { return false; } - } + if (end_ptr == line_reader.ptr()) { + return false; + } + if (chunk_len == ULONG_MAX) { + return false; + } - assert(chunk_len == 0); + if (chunk_len == 0) { + break; + } - // Trailer - if (!line_reader.getline()) { return false; } + if (!read_content_with_length(strm, chunk_len, nullptr, out)) { + return false; + } - while (strcmp(line_reader.ptr(), "\r\n")) { - if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; } + if (!line_reader.getline()) { + return false; + } - // Exclude line terminator - constexpr auto line_terminator_len = 2; - auto end = line_reader.ptr() + line_reader.size() - line_terminator_len; + if (strcmp(line_reader.ptr(), "\r\n")) { + return false; + } - parse_header(line_reader.ptr(), end, - [&](std::string &&key, std::string &&val) { - x.headers.emplace(std::move(key), std::move(val)); - }); + if (!line_reader.getline()) { + return false; + } + } - if (!line_reader.getline()) { return false; } - } + assert(chunk_len == 0); - return true; + // Trailer + if (!line_reader.getline()) { + return false; + } + + while (strcmp(line_reader.ptr(), "\r\n")) { + if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { + return false; + } + + // Exclude line terminator + constexpr auto line_terminator_len = 2; + auto end = line_reader.ptr() + line_reader.size() - line_terminator_len; + + parse_header(line_reader.ptr(), end, [&](std::string &&key, std::string &&val) { + x.headers.emplace(std::move(key), std::move(val)); + }); + + if (!line_reader.getline()) { + return false; + } + } + + return true; } inline bool is_chunked_transfer_encoding(const Headers &headers) { - return !strcasecmp(get_header_value(headers, "Transfer-Encoding", 0, ""), - "chunked"); + return !strcasecmp(get_header_value(headers, "Transfer-Encoding", 0, ""), "chunked"); } -template -bool prepare_content_receiver(T &x, int &status, - ContentReceiverWithProgress receiver, - bool decompress, U callback) { - if (decompress) { - std::string encoding = x.get_header_value("Content-Encoding"); - std::unique_ptr decompressor; +template +bool prepare_content_receiver(T &x, int &status, ContentReceiverWithProgress receiver, bool decompress, U callback) { + if (decompress) { + std::string encoding = x.get_header_value("Content-Encoding"); + std::unique_ptr decompressor; - if (encoding == "gzip" || encoding == "deflate") { + if (encoding == "gzip" || encoding == "deflate") { #ifdef CPPHTTPLIB_ZLIB_SUPPORT - decompressor = detail::make_unique(); + decompressor = detail::make_unique(); #else - status = 415; - return false; + status = 415; + return false; #endif - } else if (encoding.find("br") != std::string::npos) { + } else if (encoding.find("br") != std::string::npos) { #ifdef CPPHTTPLIB_BROTLI_SUPPORT - decompressor = detail::make_unique(); + decompressor = detail::make_unique(); #else - status = 415; - return false; + status = 415; + return false; #endif - } - - if (decompressor) { - if (decompressor->is_valid()) { - ContentReceiverWithProgress out = [&](const char *buf, size_t n, - uint64_t off, uint64_t len) { - return decompressor->decompress(buf, n, - [&](const char *buf2, size_t n2) { - return receiver(buf2, n2, off, len); - }); - }; - return callback(std::move(out)); - } else { - status = 500; - return false; - } - } - } - - ContentReceiverWithProgress out = [&](const char *buf, size_t n, uint64_t off, - uint64_t len) { - return receiver(buf, n, off, len); - }; - return callback(std::move(out)); -} - -template -bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status, - Progress progress, ContentReceiverWithProgress receiver, - bool decompress) { - return prepare_content_receiver( - x, status, std::move(receiver), decompress, - [&](const ContentReceiverWithProgress &out) { - auto ret = true; - auto exceed_payload_max_length = false; - - if (is_chunked_transfer_encoding(x.headers)) { - ret = read_content_chunked(strm, x, out); - } else if (!has_header(x.headers, "Content-Length")) { - ret = read_content_without_length(strm, out); - } else { - auto len = get_header_value(x.headers, "Content-Length"); - if (len > payload_max_length) { - exceed_payload_max_length = true; - skip_content_with_length(strm, len); - ret = false; - } else if (len > 0) { - ret = read_content_with_length(strm, len, std::move(progress), out); - } } - if (!ret) { status = exceed_payload_max_length ? 413 : 400; } - return ret; - }); -} // namespace detail + if (decompressor) { + if (decompressor->is_valid()) { + ContentReceiverWithProgress out = [&](const char *buf, size_t n, uint64_t off, uint64_t len) { + return decompressor->decompress(buf, n, [&](const char *buf2, size_t n2) { + return receiver(buf2, n2, off, len); + }); + }; + return callback(std::move(out)); + } else { + status = 500; + return false; + } + } + } + + ContentReceiverWithProgress out = [&](const char *buf, size_t n, uint64_t off, uint64_t len) { + return receiver(buf, n, off, len); + }; + return callback(std::move(out)); +} + +template +bool read_content(Stream &strm, + T &x, + size_t payload_max_length, + int &status, + Progress progress, + ContentReceiverWithProgress receiver, + bool decompress) { + return prepare_content_receiver(x, + status, + std::move(receiver), + decompress, + [&](const ContentReceiverWithProgress &out) { + auto ret = true; + auto exceed_payload_max_length = false; + + if (is_chunked_transfer_encoding(x.headers)) { + ret = read_content_chunked(strm, x, out); + } else if (!has_header(x.headers, "Content-Length")) { + ret = read_content_without_length(strm, out); + } else { + auto len = get_header_value(x.headers, "Content-Length"); + if (len > payload_max_length) { + exceed_payload_max_length = true; + skip_content_with_length(strm, len); + ret = false; + } else if (len > 0) { + ret = read_content_with_length(strm, len, std::move(progress), out); + } + } + + if (!ret) { + status = exceed_payload_max_length ? 413 : 400; + } + return ret; + }); +} // namespace detail inline ssize_t write_headers(Stream &strm, const Headers &headers) { - ssize_t write_len = 0; - for (const auto &x : headers) { - auto len = - strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str()); - if (len < 0) { return len; } + ssize_t write_len = 0; + for (const auto &x : headers) { + auto len = strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str()); + if (len < 0) { + return len; + } + write_len += len; + } + auto len = strm.write("\r\n"); + if (len < 0) { + return len; + } write_len += len; - } - auto len = strm.write("\r\n"); - if (len < 0) { return len; } - write_len += len; - return write_len; + return write_len; } inline bool write_data(Stream &strm, const char *d, size_t l) { - size_t offset = 0; - while (offset < l) { - auto length = strm.write(d + offset, l - offset); - if (length < 0) { return false; } - offset += static_cast(length); - } - return true; -} - -template -inline bool write_content(Stream &strm, const ContentProvider &content_provider, - size_t offset, size_t length, T is_shutting_down, - Error &error) { - size_t end_offset = offset + length; - auto ok = true; - DataSink data_sink; - - data_sink.write = [&](const char *d, size_t l) -> bool { - if (ok) { - if (strm.is_writable() && write_data(strm, d, l)) { - offset += l; - } else { - ok = false; - } - } - return ok; - }; - - while (offset < end_offset && !is_shutting_down()) { - if (!strm.is_writable()) { - error = Error::Write; - return false; - } else if (!content_provider(offset, end_offset - offset, data_sink)) { - error = Error::Canceled; - return false; - } else if (!ok) { - error = Error::Write; - return false; - } - } - - error = Error::Success; - return true; -} - -template -inline bool write_content(Stream &strm, const ContentProvider &content_provider, - size_t offset, size_t length, - const T &is_shutting_down) { - auto error = Error::Success; - return write_content(strm, content_provider, offset, length, is_shutting_down, - error); -} - -template -inline bool -write_content_without_length(Stream &strm, - const ContentProvider &content_provider, - const T &is_shutting_down) { - size_t offset = 0; - auto data_available = true; - auto ok = true; - DataSink data_sink; - - data_sink.write = [&](const char *d, size_t l) -> bool { - if (ok) { - offset += l; - if (!strm.is_writable() || !write_data(strm, d, l)) { ok = false; } - } - return ok; - }; - - data_sink.done = [&](void) { data_available = false; }; - - while (data_available && !is_shutting_down()) { - if (!strm.is_writable()) { - return false; - } else if (!content_provider(offset, 0, data_sink)) { - return false; - } else if (!ok) { - return false; - } - } - return true; -} - -template -inline bool -write_content_chunked(Stream &strm, const ContentProvider &content_provider, - const T &is_shutting_down, U &compressor, Error &error) { - size_t offset = 0; - auto data_available = true; - auto ok = true; - DataSink data_sink; - - data_sink.write = [&](const char *d, size_t l) -> bool { - if (ok) { - data_available = l > 0; - offset += l; - - std::string payload; - if (compressor.compress(d, l, false, - [&](const char *data, size_t data_len) { - payload.append(data, data_len); - return true; - })) { - if (!payload.empty()) { - // Emit chunked response header and footer for each chunk - auto chunk = - from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n"; - if (!strm.is_writable() || - !write_data(strm, chunk.data(), chunk.size())) { - ok = false; - } + size_t offset = 0; + while (offset < l) { + auto length = strm.write(d + offset, l - offset); + if (length < 0) { + return false; } - } else { - ok = false; - } + offset += static_cast(length); } - return ok; - }; - - auto done_with_trailer = [&](const Headers *trailer) { - if (!ok) { return; } - - data_available = false; - - std::string payload; - if (!compressor.compress(nullptr, 0, true, - [&](const char *data, size_t data_len) { - payload.append(data, data_len); - return true; - })) { - ok = false; - return; - } - - if (!payload.empty()) { - // Emit chunked response header and footer for each chunk - auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n"; - if (!strm.is_writable() || - !write_data(strm, chunk.data(), chunk.size())) { - ok = false; - return; - } - } - - static const std::string done_marker("0\r\n"); - if (!write_data(strm, done_marker.data(), done_marker.size())) { - ok = false; - } - - // Trailer - if (trailer) { - for (const auto &kv : *trailer) { - std::string field_line = kv.first + ": " + kv.second + "\r\n"; - if (!write_data(strm, field_line.data(), field_line.size())) { - ok = false; - } - } - } - - static const std::string crlf("\r\n"); - if (!write_data(strm, crlf.data(), crlf.size())) { ok = false; } - }; - - data_sink.done = [&](void) { done_with_trailer(nullptr); }; - - data_sink.done_with_trailer = [&](const Headers &trailer) { - done_with_trailer(&trailer); - }; - - while (data_available && !is_shutting_down()) { - if (!strm.is_writable()) { - error = Error::Write; - return false; - } else if (!content_provider(offset, 0, data_sink)) { - error = Error::Canceled; - return false; - } else if (!ok) { - error = Error::Write; - return false; - } - } - - error = Error::Success; - return true; + return true; } -template -inline bool write_content_chunked(Stream &strm, +template +inline bool write_content(Stream &strm, + const ContentProvider &content_provider, + size_t offset, + size_t length, + T is_shutting_down, + Error &error) { + size_t end_offset = offset + length; + auto ok = true; + DataSink data_sink; + + data_sink.write = [&](const char *d, size_t l) -> bool { + if (ok) { + if (strm.is_writable() && write_data(strm, d, l)) { + offset += l; + } else { + ok = false; + } + } + return ok; + }; + + while (offset < end_offset && !is_shutting_down()) { + if (!strm.is_writable()) { + error = Error::Write; + return false; + } else if (!content_provider(offset, end_offset - offset, data_sink)) { + error = Error::Canceled; + return false; + } else if (!ok) { + error = Error::Write; + return false; + } + } + + error = Error::Success; + return true; +} + +template +inline bool write_content(Stream &strm, + const ContentProvider &content_provider, + size_t offset, + size_t length, + const T &is_shutting_down) { + auto error = Error::Success; + return write_content(strm, content_provider, offset, length, is_shutting_down, error); +} + +template +inline bool write_content_without_length(Stream &strm, + const ContentProvider &content_provider, + const T &is_shutting_down) { + size_t offset = 0; + auto data_available = true; + auto ok = true; + DataSink data_sink; + + data_sink.write = [&](const char *d, size_t l) -> bool { + if (ok) { + offset += l; + if (!strm.is_writable() || !write_data(strm, d, l)) { + ok = false; + } + } + return ok; + }; + + data_sink.done = [&](void) { data_available = false; }; + + while (data_available && !is_shutting_down()) { + if (!strm.is_writable()) { + return false; + } else if (!content_provider(offset, 0, data_sink)) { + return false; + } else if (!ok) { + return false; + } + } + return true; +} + +template +inline bool write_content_chunked(Stream &strm, const ContentProvider &content_provider, - const T &is_shutting_down, U &compressor) { - auto error = Error::Success; - return write_content_chunked(strm, content_provider, is_shutting_down, - compressor, error); + const T &is_shutting_down, + U &compressor, + Error &error) { + size_t offset = 0; + auto data_available = true; + auto ok = true; + DataSink data_sink; + + data_sink.write = [&](const char *d, size_t l) -> bool { + if (ok) { + data_available = l > 0; + offset += l; + + std::string payload; + if (compressor.compress(d, l, false, [&](const char *data, size_t data_len) { + payload.append(data, data_len); + return true; + })) { + if (!payload.empty()) { + // Emit chunked response header and footer for each chunk + auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n"; + if (!strm.is_writable() || !write_data(strm, chunk.data(), chunk.size())) { + ok = false; + } + } + } else { + ok = false; + } + } + return ok; + }; + + auto done_with_trailer = [&](const Headers *trailer) { + if (!ok) { + return; + } + + data_available = false; + + std::string payload; + if (!compressor.compress(nullptr, 0, true, [&](const char *data, size_t data_len) { + payload.append(data, data_len); + return true; + })) { + ok = false; + return; + } + + if (!payload.empty()) { + // Emit chunked response header and footer for each chunk + auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n"; + if (!strm.is_writable() || !write_data(strm, chunk.data(), chunk.size())) { + ok = false; + return; + } + } + + static const std::string done_marker("0\r\n"); + if (!write_data(strm, done_marker.data(), done_marker.size())) { + ok = false; + } + + // Trailer + if (trailer) { + for (const auto &kv : *trailer) { + std::string field_line = kv.first + ": " + kv.second + "\r\n"; + if (!write_data(strm, field_line.data(), field_line.size())) { + ok = false; + } + } + } + + static const std::string crlf("\r\n"); + if (!write_data(strm, crlf.data(), crlf.size())) { + ok = false; + } + }; + + data_sink.done = [&](void) { done_with_trailer(nullptr); }; + + data_sink.done_with_trailer = [&](const Headers &trailer) { done_with_trailer(&trailer); }; + + while (data_available && !is_shutting_down()) { + if (!strm.is_writable()) { + error = Error::Write; + return false; + } else if (!content_provider(offset, 0, data_sink)) { + error = Error::Canceled; + return false; + } else if (!ok) { + error = Error::Write; + return false; + } + } + + error = Error::Success; + return true; } -template -inline bool redirect(T &cli, Request &req, Response &res, - const std::string &path, const std::string &location, - Error &error) { - Request new_req = req; - new_req.path = path; - new_req.redirect_count_ -= 1; +template +inline bool write_content_chunked(Stream &strm, + const ContentProvider &content_provider, + const T &is_shutting_down, + U &compressor) { + auto error = Error::Success; + return write_content_chunked(strm, content_provider, is_shutting_down, compressor, error); +} - if (res.status == 303 && (req.method != "GET" && req.method != "HEAD")) { - new_req.method = "GET"; - new_req.body.clear(); - new_req.headers.clear(); - } +template +inline bool redirect(T &cli, + Request &req, + Response &res, + const std::string &path, + const std::string &location, + Error &error) { + Request new_req = req; + new_req.path = path; + new_req.redirect_count_ -= 1; - Response new_res; + if (res.status == 303 && (req.method != "GET" && req.method != "HEAD")) { + new_req.method = "GET"; + new_req.body.clear(); + new_req.headers.clear(); + } - auto ret = cli.send(new_req, new_res, error); - if (ret) { - req = new_req; - res = new_res; + Response new_res; - if (res.location.empty()) res.location = location; - } - return ret; + auto ret = cli.send(new_req, new_res, error); + if (ret) { + req = new_req; + res = new_res; + + if (res.location.empty()) { + res.location = location; + } + } + return ret; } inline std::string params_to_query_str(const Params ¶ms) { - std::string query; + std::string query; - for (auto it = params.begin(); it != params.end(); ++it) { - if (it != params.begin()) { query += "&"; } - query += it->first; - query += "="; - query += encode_query_param(it->second); - } - return query; + for (auto it = params.begin(); it != params.end(); ++it) { + if (it != params.begin()) { + query += "&"; + } + query += it->first; + query += "="; + query += encode_query_param(it->second); + } + return query; } inline void parse_query_text(const std::string &s, Params ¶ms) { - std::set cache; - split(s.data(), s.data() + s.size(), '&', [&](const char *b, const char *e) { - std::string kv(b, e); - if (cache.find(kv) != cache.end()) { return; } - cache.insert(kv); + std::set cache; + split(s.data(), s.data() + s.size(), '&', [&](const char *b, const char *e) { + std::string kv(b, e); + if (cache.find(kv) != cache.end()) { + return; + } + cache.insert(kv); - std::string key; - std::string val; - split(b, e, '=', [&](const char *b2, const char *e2) { - if (key.empty()) { - key.assign(b2, e2); - } else { - val.assign(b2, e2); - } + std::string key; + std::string val; + split(b, e, '=', [&](const char *b2, const char *e2) { + if (key.empty()) { + key.assign(b2, e2); + } else { + val.assign(b2, e2); + } + }); + + if (!key.empty()) { + params.emplace(decode_url(key, true), decode_url(val, true)); + } }); - - if (!key.empty()) { - params.emplace(decode_url(key, true), decode_url(val, true)); - } - }); } -inline bool parse_multipart_boundary(const std::string &content_type, - std::string &boundary) { - auto boundary_keyword = "boundary="; - auto pos = content_type.find(boundary_keyword); - if (pos == std::string::npos) { return false; } - auto end = content_type.find(';', pos); - auto beg = pos + strlen(boundary_keyword); - boundary = content_type.substr(beg, end - beg); - if (boundary.length() >= 2 && boundary.front() == '"' && - boundary.back() == '"') { - boundary = boundary.substr(1, boundary.size() - 2); - } - return !boundary.empty(); +inline bool parse_multipart_boundary(const std::string &content_type, std::string &boundary) { + auto boundary_keyword = "boundary="; + auto pos = content_type.find(boundary_keyword); + if (pos == std::string::npos) { + return false; + } + auto end = content_type.find(';', pos); + auto beg = pos + strlen(boundary_keyword); + boundary = content_type.substr(beg, end - beg); + if (boundary.length() >= 2 && boundary.front() == '"' && boundary.back() == '"') { + boundary = boundary.substr(1, boundary.size() - 2); + } + return !boundary.empty(); } #ifdef CPPHTTPLIB_NO_EXCEPTIONS @@ -4079,523 +4394,580 @@ inline bool parse_range_header(const std::string &s, Ranges &ranges) { #else inline bool parse_range_header(const std::string &s, Ranges &ranges) try { #endif - static auto re_first_range = std::regex(R"(bytes=(\d*-\d*(?:,\s*\d*-\d*)*))"); - std::smatch m; - if (std::regex_match(s, m, re_first_range)) { - auto pos = static_cast(m.position(1)); - auto len = static_cast(m.length(1)); - bool all_valid_ranges = true; - split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) { - if (!all_valid_ranges) return; - static auto re_another_range = std::regex(R"(\s*(\d*)-(\d*))"); - std::cmatch cm; - if (std::regex_match(b, e, cm, re_another_range)) { - ssize_t first = -1; - if (!cm.str(1).empty()) { - first = static_cast(std::stoll(cm.str(1))); - } + static auto re_first_range = std::regex(R"(bytes=(\d*-\d*(?:,\s*\d*-\d*)*))"); + std::smatch m; + if (std::regex_match(s, m, re_first_range)) { + auto pos = static_cast(m.position(1)); + auto len = static_cast(m.length(1)); + bool all_valid_ranges = true; + split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) { + if (!all_valid_ranges) { + return; + } + static auto re_another_range = std::regex(R"(\s*(\d*)-(\d*))"); + std::cmatch cm; + if (std::regex_match(b, e, cm, re_another_range)) { + ssize_t first = -1; + if (!cm.str(1).empty()) { + first = static_cast(std::stoll(cm.str(1))); + } - ssize_t last = -1; - if (!cm.str(2).empty()) { - last = static_cast(std::stoll(cm.str(2))); - } + ssize_t last = -1; + if (!cm.str(2).empty()) { + last = static_cast(std::stoll(cm.str(2))); + } - if (first != -1 && last != -1 && first > last) { - all_valid_ranges = false; - return; - } - ranges.emplace_back(std::make_pair(first, last)); - } - }); - return all_valid_ranges; - } - return false; + if (first != -1 && last != -1 && first > last) { + all_valid_ranges = false; + return; + } + ranges.emplace_back(std::make_pair(first, last)); + } + }); + return all_valid_ranges; + } + return false; #ifdef CPPHTTPLIB_NO_EXCEPTIONS } #else -} catch (...) { return false; } +} +catch (...) { + return false; +} #endif class MultipartFormDataParser { public: - MultipartFormDataParser() = default; + MultipartFormDataParser() = default; - void set_boundary(std::string &&boundary) { - boundary_ = boundary; - dash_boundary_crlf_ = dash_ + boundary_ + crlf_; - crlf_dash_boundary_ = crlf_ + dash_ + boundary_; - } - - bool is_valid() const { return is_valid_; } - - bool parse(const char *buf, size_t n, const ContentReceiver &content_callback, - const MultipartContentHeader &header_callback) { - - // TODO: support 'filename*' - static const std::regex re_content_disposition( - R"~(^Content-Disposition:\s*form-data;\s*name="(.*?)"(?:;\s*filename="(.*?)")?(?:;\s*filename\*=\S+)?\s*$)~", - std::regex_constants::icase); - - buf_append(buf, n); - - while (buf_size() > 0) { - switch (state_) { - case 0: { // Initial boundary - buf_erase(buf_find(dash_boundary_crlf_)); - if (dash_boundary_crlf_.size() > buf_size()) { return true; } - if (!buf_start_with(dash_boundary_crlf_)) { return false; } - buf_erase(dash_boundary_crlf_.size()); - state_ = 1; - break; - } - case 1: { // New entry - clear_file_info(); - state_ = 2; - break; - } - case 2: { // Headers - auto pos = buf_find(crlf_); - if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; } - while (pos < buf_size()) { - // Empty line - if (pos == 0) { - if (!header_callback(file_)) { - is_valid_ = false; - return false; - } - buf_erase(crlf_.size()); - state_ = 3; - break; - } - - static const std::string header_name = "content-type:"; - const auto header = buf_head(pos); - if (start_with_case_ignore(header, header_name)) { - file_.content_type = trim_copy(header.substr(header_name.size())); - } else { - std::smatch m; - if (std::regex_match(header, m, re_content_disposition)) { - file_.name = m[1]; - file_.filename = m[2]; - } else { - is_valid_ = false; - return false; - } - } - buf_erase(pos + crlf_.size()); - pos = buf_find(crlf_); - } - if (state_ != 3) { return true; } - break; - } - case 3: { // Body - if (crlf_dash_boundary_.size() > buf_size()) { return true; } - auto pos = buf_find(crlf_dash_boundary_); - if (pos < buf_size()) { - if (!content_callback(buf_data(), pos)) { - is_valid_ = false; - return false; - } - buf_erase(pos + crlf_dash_boundary_.size()); - state_ = 4; - } else { - auto len = buf_size() - crlf_dash_boundary_.size(); - if (len > 0) { - if (!content_callback(buf_data(), len)) { - is_valid_ = false; - return false; - } - buf_erase(len); - } - return true; - } - break; - } - case 4: { // Boundary - if (crlf_.size() > buf_size()) { return true; } - if (buf_start_with(crlf_)) { - buf_erase(crlf_.size()); - state_ = 1; - } else { - if (dash_crlf_.size() > buf_size()) { return true; } - if (buf_start_with(dash_crlf_)) { - buf_erase(dash_crlf_.size()); - is_valid_ = true; - buf_erase(buf_size()); // Remove epilogue - } else { - return true; - } - } - break; - } - } + void set_boundary(std::string &&boundary) { + boundary_ = boundary; + dash_boundary_crlf_ = dash_ + boundary_ + crlf_; + crlf_dash_boundary_ = crlf_ + dash_ + boundary_; } - return true; - } + bool is_valid() const { + return is_valid_; + } + + bool parse(const char *buf, + size_t n, + const ContentReceiver &content_callback, + const MultipartContentHeader &header_callback) { + + // TODO: support 'filename*' + static const std::regex re_content_disposition( + R"~(^Content-Disposition:\s*form-data;\s*name="(.*?)"(?:;\s*filename="(.*?)")?(?:;\s*filename\*=\S+)?\s*$)~", + std::regex_constants::icase); + + buf_append(buf, n); + + while (buf_size() > 0) { + switch (state_) { + case 0: { // Initial boundary + buf_erase(buf_find(dash_boundary_crlf_)); + if (dash_boundary_crlf_.size() > buf_size()) { + return true; + } + if (!buf_start_with(dash_boundary_crlf_)) { + return false; + } + buf_erase(dash_boundary_crlf_.size()); + state_ = 1; + break; + } + case 1: { // New entry + clear_file_info(); + state_ = 2; + break; + } + case 2: { // Headers + auto pos = buf_find(crlf_); + if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { + return false; + } + while (pos < buf_size()) { + // Empty line + if (pos == 0) { + if (!header_callback(file_)) { + is_valid_ = false; + return false; + } + buf_erase(crlf_.size()); + state_ = 3; + break; + } + + static const std::string header_name = "content-type:"; + const auto header = buf_head(pos); + if (start_with_case_ignore(header, header_name)) { + file_.content_type = trim_copy(header.substr(header_name.size())); + } else { + std::smatch m; + if (std::regex_match(header, m, re_content_disposition)) { + file_.name = m[1]; + file_.filename = m[2]; + } else { + is_valid_ = false; + return false; + } + } + buf_erase(pos + crlf_.size()); + pos = buf_find(crlf_); + } + if (state_ != 3) { + return true; + } + break; + } + case 3: { // Body + if (crlf_dash_boundary_.size() > buf_size()) { + return true; + } + auto pos = buf_find(crlf_dash_boundary_); + if (pos < buf_size()) { + if (!content_callback(buf_data(), pos)) { + is_valid_ = false; + return false; + } + buf_erase(pos + crlf_dash_boundary_.size()); + state_ = 4; + } else { + auto len = buf_size() - crlf_dash_boundary_.size(); + if (len > 0) { + if (!content_callback(buf_data(), len)) { + is_valid_ = false; + return false; + } + buf_erase(len); + } + return true; + } + break; + } + case 4: { // Boundary + if (crlf_.size() > buf_size()) { + return true; + } + if (buf_start_with(crlf_)) { + buf_erase(crlf_.size()); + state_ = 1; + } else { + if (dash_crlf_.size() > buf_size()) { + return true; + } + if (buf_start_with(dash_crlf_)) { + buf_erase(dash_crlf_.size()); + is_valid_ = true; + buf_erase(buf_size()); // Remove epilogue + } else { + return true; + } + } + break; + } + } + } + + return true; + } private: - void clear_file_info() { - file_.name.clear(); - file_.filename.clear(); - file_.content_type.clear(); - } - - bool start_with_case_ignore(const std::string &a, - const std::string &b) const { - if (a.size() < b.size()) { return false; } - for (size_t i = 0; i < b.size(); i++) { - if (::tolower(a[i]) != ::tolower(b[i])) { return false; } - } - return true; - } - - const std::string dash_ = "--"; - const std::string crlf_ = "\r\n"; - const std::string dash_crlf_ = "--\r\n"; - std::string boundary_; - std::string dash_boundary_crlf_; - std::string crlf_dash_boundary_; - - size_t state_ = 0; - bool is_valid_ = false; - MultipartFormData file_; - - // Buffer - bool start_with(const std::string &a, size_t spos, size_t epos, - const std::string &b) const { - if (epos - spos < b.size()) { return false; } - for (size_t i = 0; i < b.size(); i++) { - if (a[i + spos] != b[i]) { return false; } - } - return true; - } - - size_t buf_size() const { return buf_epos_ - buf_spos_; } - - const char *buf_data() const { return &buf_[buf_spos_]; } - - std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); } - - bool buf_start_with(const std::string &s) const { - return start_with(buf_, buf_spos_, buf_epos_, s); - } - - size_t buf_find(const std::string &s) const { - auto c = s.front(); - - size_t off = buf_spos_; - while (off < buf_epos_) { - auto pos = off; - while (true) { - if (pos == buf_epos_) { return buf_size(); } - if (buf_[pos] == c) { break; } - pos++; - } - - auto remaining_size = buf_epos_ - pos; - if (s.size() > remaining_size) { return buf_size(); } - - if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; } - - off = pos + 1; + void clear_file_info() { + file_.name.clear(); + file_.filename.clear(); + file_.content_type.clear(); } - return buf_size(); - } - - void buf_append(const char *data, size_t n) { - auto remaining_size = buf_size(); - if (remaining_size > 0 && buf_spos_ > 0) { - for (size_t i = 0; i < remaining_size; i++) { - buf_[i] = buf_[buf_spos_ + i]; - } + bool start_with_case_ignore(const std::string &a, const std::string &b) const { + if (a.size() < b.size()) { + return false; + } + for (size_t i = 0; i < b.size(); i++) { + if (::tolower(a[i]) != ::tolower(b[i])) { + return false; + } + } + return true; } - buf_spos_ = 0; - buf_epos_ = remaining_size; - if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); } + const std::string dash_ = "--"; + const std::string crlf_ = "\r\n"; + const std::string dash_crlf_ = "--\r\n"; + std::string boundary_; + std::string dash_boundary_crlf_; + std::string crlf_dash_boundary_; - for (size_t i = 0; i < n; i++) { - buf_[buf_epos_ + i] = data[i]; + size_t state_ = 0; + bool is_valid_ = false; + MultipartFormData file_; + + // Buffer + bool start_with(const std::string &a, size_t spos, size_t epos, const std::string &b) const { + if (epos - spos < b.size()) { + return false; + } + for (size_t i = 0; i < b.size(); i++) { + if (a[i + spos] != b[i]) { + return false; + } + } + return true; } - buf_epos_ += n; - } - void buf_erase(size_t size) { buf_spos_ += size; } + size_t buf_size() const { + return buf_epos_ - buf_spos_; + } - std::string buf_; - size_t buf_spos_ = 0; - size_t buf_epos_ = 0; + const char *buf_data() const { + return &buf_[buf_spos_]; + } + + std::string buf_head(size_t l) const { + return buf_.substr(buf_spos_, l); + } + + bool buf_start_with(const std::string &s) const { + return start_with(buf_, buf_spos_, buf_epos_, s); + } + + size_t buf_find(const std::string &s) const { + auto c = s.front(); + + size_t off = buf_spos_; + while (off < buf_epos_) { + auto pos = off; + while (true) { + if (pos == buf_epos_) { + return buf_size(); + } + if (buf_[pos] == c) { + break; + } + pos++; + } + + auto remaining_size = buf_epos_ - pos; + if (s.size() > remaining_size) { + return buf_size(); + } + + if (start_with(buf_, pos, buf_epos_, s)) { + return pos - buf_spos_; + } + + off = pos + 1; + } + + return buf_size(); + } + + void buf_append(const char *data, size_t n) { + auto remaining_size = buf_size(); + if (remaining_size > 0 && buf_spos_ > 0) { + for (size_t i = 0; i < remaining_size; i++) { + buf_[i] = buf_[buf_spos_ + i]; + } + } + buf_spos_ = 0; + buf_epos_ = remaining_size; + + if (remaining_size + n > buf_.size()) { + buf_.resize(remaining_size + n); + } + + for (size_t i = 0; i < n; i++) { + buf_[buf_epos_ + i] = data[i]; + } + buf_epos_ += n; + } + + void buf_erase(size_t size) { + buf_spos_ += size; + } + + std::string buf_; + size_t buf_spos_ = 0; + size_t buf_epos_ = 0; }; inline std::string to_lower(const char *beg, const char *end) { - std::string out; - auto it = beg; - while (it != end) { - out += static_cast(::tolower(*it)); - it++; - } - return out; + std::string out; + auto it = beg; + while (it != end) { + out += static_cast(::tolower(*it)); + it++; + } + return out; } inline std::string make_multipart_data_boundary() { - static const char data[] = - "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + static const char data[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; - // std::random_device might actually be deterministic on some - // platforms, but due to lack of support in the c++ standard library, - // doing better requires either some ugly hacks or breaking portability. - std::random_device seed_gen; + // std::random_device might actually be deterministic on some + // platforms, but due to lack of support in the c++ standard library, + // doing better requires either some ugly hacks or breaking portability. + std::random_device seed_gen; - // Request 128 bits of entropy for initialization - std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()}; - std::mt19937 engine(seed_sequence); + // Request 128 bits of entropy for initialization + std::seed_seq seed_sequence {seed_gen(), seed_gen(), seed_gen(), seed_gen()}; + std::mt19937 engine(seed_sequence); - std::string result = "--cpp-httplib-multipart-data-"; + std::string result = "--cpp-httplib-multipart-data-"; - for (auto i = 0; i < 16; i++) { - result += data[engine() % (sizeof(data) - 1)]; - } + for (auto i = 0; i < 16; i++) { + result += data[engine() % (sizeof(data) - 1)]; + } - return result; + return result; } inline bool is_multipart_boundary_chars_valid(const std::string &boundary) { - auto valid = true; - for (size_t i = 0; i < boundary.size(); i++) { - auto c = boundary[i]; - if (!std::isalnum(c) && c != '-' && c != '_') { - valid = false; - break; + auto valid = true; + for (size_t i = 0; i < boundary.size(); i++) { + auto c = boundary[i]; + if (!std::isalnum(c) && c != '-' && c != '_') { + valid = false; + break; + } } - } - return valid; + return valid; } -template -inline std::string -serialize_multipart_formdata_item_begin(const T &item, - const std::string &boundary) { - std::string body = "--" + boundary + "\r\n"; - body += "Content-Disposition: form-data; name=\"" + item.name + "\""; - if (!item.filename.empty()) { - body += "; filename=\"" + item.filename + "\""; - } - body += "\r\n"; - if (!item.content_type.empty()) { - body += "Content-Type: " + item.content_type + "\r\n"; - } - body += "\r\n"; +template +inline std::string serialize_multipart_formdata_item_begin(const T &item, const std::string &boundary) { + std::string body = "--" + boundary + "\r\n"; + body += "Content-Disposition: form-data; name=\"" + item.name + "\""; + if (!item.filename.empty()) { + body += "; filename=\"" + item.filename + "\""; + } + body += "\r\n"; + if (!item.content_type.empty()) { + body += "Content-Type: " + item.content_type + "\r\n"; + } + body += "\r\n"; - return body; + return body; } -inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; } - -inline std::string -serialize_multipart_formdata_finish(const std::string &boundary) { - return "--" + boundary + "--\r\n"; +inline std::string serialize_multipart_formdata_item_end() { + return "\r\n"; } -inline std::string -serialize_multipart_formdata_get_content_type(const std::string &boundary) { - return "multipart/form-data; boundary=" + boundary; +inline std::string serialize_multipart_formdata_finish(const std::string &boundary) { + return "--" + boundary + "--\r\n"; } -inline std::string -serialize_multipart_formdata(const MultipartFormDataItems &items, - const std::string &boundary, bool finish = true) { - std::string body; - - for (const auto &item : items) { - body += serialize_multipart_formdata_item_begin(item, boundary); - body += item.content + serialize_multipart_formdata_item_end(); - } - - if (finish) body += serialize_multipart_formdata_finish(boundary); - - return body; +inline std::string serialize_multipart_formdata_get_content_type(const std::string &boundary) { + return "multipart/form-data; boundary=" + boundary; } -inline std::pair -get_range_offset_and_length(const Request &req, size_t content_length, - size_t index) { - auto r = req.ranges[index]; +inline std::string serialize_multipart_formdata(const MultipartFormDataItems &items, + const std::string &boundary, + bool finish = true) { + std::string body; - if (r.first == -1 && r.second == -1) { - return std::make_pair(0, content_length); - } + for (const auto &item : items) { + body += serialize_multipart_formdata_item_begin(item, boundary); + body += item.content + serialize_multipart_formdata_item_end(); + } - auto slen = static_cast(content_length); + if (finish) { + body += serialize_multipart_formdata_finish(boundary); + } - if (r.first == -1) { - r.first = (std::max)(static_cast(0), slen - r.second); - r.second = slen - 1; - } - - if (r.second == -1) { r.second = slen - 1; } - return std::make_pair(r.first, static_cast(r.second - r.first) + 1); + return body; } -inline std::string make_content_range_header_field(size_t offset, size_t length, - size_t content_length) { - std::string field = "bytes "; - field += std::to_string(offset); - field += "-"; - field += std::to_string(offset + length - 1); - field += "/"; - field += std::to_string(content_length); - return field; +inline std::pair get_range_offset_and_length(const Request &req, size_t content_length, size_t index) { + auto r = req.ranges[index]; + + if (r.first == -1 && r.second == -1) { + return std::make_pair(0, content_length); + } + + auto slen = static_cast(content_length); + + if (r.first == -1) { + r.first = (std::max)(static_cast(0), slen - r.second); + r.second = slen - 1; + } + + if (r.second == -1) { + r.second = slen - 1; + } + return std::make_pair(r.first, static_cast(r.second - r.first) + 1); } -template -bool process_multipart_ranges_data(const Request &req, Response &res, +inline std::string make_content_range_header_field(size_t offset, size_t length, size_t content_length) { + std::string field = "bytes "; + field += std::to_string(offset); + field += "-"; + field += std::to_string(offset + length - 1); + field += "/"; + field += std::to_string(content_length); + return field; +} + +template +bool process_multipart_ranges_data(const Request &req, + Response &res, const std::string &boundary, const std::string &content_type, - SToken stoken, CToken ctoken, - Content content) { - for (size_t i = 0; i < req.ranges.size(); i++) { - ctoken("--"); - stoken(boundary); - ctoken("\r\n"); - if (!content_type.empty()) { - ctoken("Content-Type: "); - stoken(content_type); - ctoken("\r\n"); + SToken stoken, + CToken ctoken, + Content content) { + for (size_t i = 0; i < req.ranges.size(); i++) { + ctoken("--"); + stoken(boundary); + ctoken("\r\n"); + if (!content_type.empty()) { + ctoken("Content-Type: "); + stoken(content_type); + ctoken("\r\n"); + } + + auto offsets = get_range_offset_and_length(req, res.body.size(), i); + auto offset = offsets.first; + auto length = offsets.second; + + ctoken("Content-Range: "); + stoken(make_content_range_header_field(offset, length, res.body.size())); + ctoken("\r\n"); + ctoken("\r\n"); + if (!content(offset, length)) { + return false; + } + ctoken("\r\n"); } - auto offsets = get_range_offset_and_length(req, res.body.size(), i); - auto offset = offsets.first; - auto length = offsets.second; + ctoken("--"); + stoken(boundary); + ctoken("--\r\n"); - ctoken("Content-Range: "); - stoken(make_content_range_header_field(offset, length, res.body.size())); - ctoken("\r\n"); - ctoken("\r\n"); - if (!content(offset, length)) { return false; } - ctoken("\r\n"); - } - - ctoken("--"); - stoken(boundary); - ctoken("--\r\n"); - - return true; + return true; } -inline bool make_multipart_ranges_data(const Request &req, Response &res, +inline bool make_multipart_ranges_data(const Request &req, + Response &res, const std::string &boundary, const std::string &content_type, - std::string &data) { - return process_multipart_ranges_data( - req, res, boundary, content_type, - [&](const std::string &token) { data += token; }, - [&](const std::string &token) { data += token; }, - [&](size_t offset, size_t length) { - if (offset < res.body.size()) { - data += res.body.substr(offset, length); - return true; - } - return false; - }); + std::string &data) { + return process_multipart_ranges_data( + req, + res, + boundary, + content_type, + [&](const std::string &token) { data += token; }, + [&](const std::string &token) { data += token; }, + [&](size_t offset, size_t length) { + if (offset < res.body.size()) { + data += res.body.substr(offset, length); + return true; + } + return false; + }); } -inline size_t -get_multipart_ranges_data_length(const Request &req, Response &res, - const std::string &boundary, - const std::string &content_type) { - size_t data_length = 0; +inline size_t get_multipart_ranges_data_length(const Request &req, + Response &res, + const std::string &boundary, + const std::string &content_type) { + size_t data_length = 0; - process_multipart_ranges_data( - req, res, boundary, content_type, - [&](const std::string &token) { data_length += token.size(); }, - [&](const std::string &token) { data_length += token.size(); }, - [&](size_t /*offset*/, size_t length) { - data_length += length; - return true; - }); + process_multipart_ranges_data( + req, + res, + boundary, + content_type, + [&](const std::string &token) { data_length += token.size(); }, + [&](const std::string &token) { data_length += token.size(); }, + [&](size_t /*offset*/, size_t length) { + data_length += length; + return true; + }); - return data_length; + return data_length; } -template -inline bool write_multipart_ranges_data(Stream &strm, const Request &req, - Response &res, +template +inline bool write_multipart_ranges_data(Stream &strm, + const Request &req, + Response &res, const std::string &boundary, const std::string &content_type, - const T &is_shutting_down) { - return process_multipart_ranges_data( - req, res, boundary, content_type, - [&](const std::string &token) { strm.write(token); }, - [&](const std::string &token) { strm.write(token); }, - [&](size_t offset, size_t length) { - return write_content(strm, res.content_provider_, offset, length, - is_shutting_down); - }); + const T &is_shutting_down) { + return process_multipart_ranges_data( + req, + res, + boundary, + content_type, + [&](const std::string &token) { strm.write(token); }, + [&](const std::string &token) { strm.write(token); }, + [&](size_t offset, size_t length) { + return write_content(strm, res.content_provider_, offset, length, is_shutting_down); + }); } -inline std::pair -get_range_offset_and_length(const Request &req, const Response &res, - size_t index) { - auto r = req.ranges[index]; +inline std::pair get_range_offset_and_length(const Request &req, const Response &res, size_t index) { + auto r = req.ranges[index]; - if (r.second == -1) { - r.second = static_cast(res.content_length_) - 1; - } + if (r.second == -1) { + r.second = static_cast(res.content_length_) - 1; + } - return std::make_pair(r.first, r.second - r.first + 1); + return std::make_pair(r.first, r.second - r.first + 1); } inline bool expect_content(const Request &req) { - if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" || - req.method == "PRI" || req.method == "DELETE") { - return true; - } - // TODO: check if Content-Length is set - return false; + if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" || req.method == "PRI" || + req.method == "DELETE") { + return true; + } + // TODO: check if Content-Length is set + return false; } inline bool has_crlf(const std::string &s) { - auto p = s.c_str(); - while (*p) { - if (*p == '\r' || *p == '\n') { return true; } - p++; - } - return false; + auto p = s.c_str(); + while (*p) { + if (*p == '\r' || *p == '\n') { + return true; + } + p++; + } + return false; } #ifdef CPPHTTPLIB_OPENSSL_SUPPORT inline std::string message_digest(const std::string &s, const EVP_MD *algo) { - auto context = std::unique_ptr( - EVP_MD_CTX_new(), EVP_MD_CTX_free); + auto context = std::unique_ptr(EVP_MD_CTX_new(), EVP_MD_CTX_free); - unsigned int hash_length = 0; - unsigned char hash[EVP_MAX_MD_SIZE]; + unsigned int hash_length = 0; + unsigned char hash[EVP_MAX_MD_SIZE]; - EVP_DigestInit_ex(context.get(), algo, nullptr); - EVP_DigestUpdate(context.get(), s.c_str(), s.size()); - EVP_DigestFinal_ex(context.get(), hash, &hash_length); + EVP_DigestInit_ex(context.get(), algo, nullptr); + EVP_DigestUpdate(context.get(), s.c_str(), s.size()); + EVP_DigestFinal_ex(context.get(), hash, &hash_length); - std::stringstream ss; - for (auto i = 0u; i < hash_length; ++i) { - ss << std::hex << std::setw(2) << std::setfill('0') - << static_cast(hash[i]); - } + std::stringstream ss; + for (auto i = 0u; i < hash_length; ++i) { + ss << std::hex << std::setw(2) << std::setfill('0') << static_cast(hash[i]); + } - return ss.str(); + return ss.str(); } inline std::string MD5(const std::string &s) { - return message_digest(s, EVP_md5()); + return message_digest(s, EVP_md5()); } inline std::string SHA_256(const std::string &s) { - return message_digest(s, EVP_sha256()); + return message_digest(s, EVP_sha256()); } inline std::string SHA_512(const std::string &s) { - return message_digest(s, EVP_sha512()); + return message_digest(s, EVP_sha512()); } #endif @@ -4604,135 +4976,139 @@ inline std::string SHA_512(const std::string &s) { // NOTE: This code came up with the following stackoverflow post: // https://stackoverflow.com/questions/9507184/can-openssl-on-windows-use-the-system-certificate-store inline bool load_system_certs_on_windows(X509_STORE *store) { - auto hStore = CertOpenSystemStoreW((HCRYPTPROV_LEGACY)NULL, L"ROOT"); - if (!hStore) { return false; } - - auto result = false; - PCCERT_CONTEXT pContext = NULL; - while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) != - nullptr) { - auto encoded_cert = - static_cast(pContext->pbCertEncoded); - - auto x509 = d2i_X509(NULL, &encoded_cert, pContext->cbCertEncoded); - if (x509) { - X509_STORE_add_cert(store, x509); - X509_free(x509); - result = true; + auto hStore = CertOpenSystemStoreW((HCRYPTPROV_LEGACY)NULL, L"ROOT"); + if (!hStore) { + return false; } - } - CertFreeCertificateContext(pContext); - CertCloseStore(hStore, 0); + auto result = false; + PCCERT_CONTEXT pContext = NULL; + while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) != nullptr) { + auto encoded_cert = static_cast(pContext->pbCertEncoded); - return result; + auto x509 = d2i_X509(NULL, &encoded_cert, pContext->cbCertEncoded); + if (x509) { + X509_STORE_add_cert(store, x509); + X509_free(x509); + result = true; + } + } + + CertFreeCertificateContext(pContext); + CertCloseStore(hStore, 0); + + return result; } #elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && defined(__APPLE__) #if TARGET_OS_OSX -template -using CFObjectPtr = - std::unique_ptr::type, void (*)(CFTypeRef)>; +template using CFObjectPtr = std::unique_ptr::type, void (*)(CFTypeRef)>; inline void cf_object_ptr_deleter(CFTypeRef obj) { - if (obj) { CFRelease(obj); } + if (obj) { + CFRelease(obj); + } } inline bool retrieve_certs_from_keychain(CFObjectPtr &certs) { - CFStringRef keys[] = {kSecClass, kSecMatchLimit, kSecReturnRef}; - CFTypeRef values[] = {kSecClassCertificate, kSecMatchLimitAll, - kCFBooleanTrue}; + CFStringRef keys[] = {kSecClass, kSecMatchLimit, kSecReturnRef}; + CFTypeRef values[] = {kSecClassCertificate, kSecMatchLimitAll, kCFBooleanTrue}; - CFObjectPtr query( - CFDictionaryCreate(nullptr, reinterpret_cast(keys), values, - sizeof(keys) / sizeof(keys[0]), - &kCFTypeDictionaryKeyCallBacks, - &kCFTypeDictionaryValueCallBacks), - cf_object_ptr_deleter); + CFObjectPtr query(CFDictionaryCreate(nullptr, + reinterpret_cast(keys), + values, + sizeof(keys) / sizeof(keys[0]), + &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks), + cf_object_ptr_deleter); - if (!query) { return false; } + if (!query) { + return false; + } - CFTypeRef security_items = nullptr; - if (SecItemCopyMatching(query.get(), &security_items) != errSecSuccess || - CFArrayGetTypeID() != CFGetTypeID(security_items)) { - return false; - } + CFTypeRef security_items = nullptr; + if (SecItemCopyMatching(query.get(), &security_items) != errSecSuccess || + CFArrayGetTypeID() != CFGetTypeID(security_items)) { + return false; + } - certs.reset(reinterpret_cast(security_items)); - return true; + certs.reset(reinterpret_cast(security_items)); + return true; } inline bool retrieve_root_certs_from_keychain(CFObjectPtr &certs) { - CFArrayRef root_security_items = nullptr; - if (SecTrustCopyAnchorCertificates(&root_security_items) != errSecSuccess) { - return false; - } + CFArrayRef root_security_items = nullptr; + if (SecTrustCopyAnchorCertificates(&root_security_items) != errSecSuccess) { + return false; + } - certs.reset(root_security_items); - return true; + certs.reset(root_security_items); + return true; } inline bool add_certs_to_x509_store(CFArrayRef certs, X509_STORE *store) { - auto result = false; - for (auto i = 0; i < CFArrayGetCount(certs); ++i) { - const auto cert = reinterpret_cast( - CFArrayGetValueAtIndex(certs, i)); + auto result = false; + for (auto i = 0; i < CFArrayGetCount(certs); ++i) { + const auto cert = reinterpret_cast(CFArrayGetValueAtIndex(certs, i)); - if (SecCertificateGetTypeID() != CFGetTypeID(cert)) { continue; } + if (SecCertificateGetTypeID() != CFGetTypeID(cert)) { + continue; + } - CFDataRef cert_data = nullptr; - if (SecItemExport(cert, kSecFormatX509Cert, 0, nullptr, &cert_data) != - errSecSuccess) { - continue; + CFDataRef cert_data = nullptr; + if (SecItemExport(cert, kSecFormatX509Cert, 0, nullptr, &cert_data) != errSecSuccess) { + continue; + } + + CFObjectPtr cert_data_ptr(cert_data, cf_object_ptr_deleter); + + auto encoded_cert = static_cast(CFDataGetBytePtr(cert_data_ptr.get())); + + auto x509 = d2i_X509(NULL, &encoded_cert, CFDataGetLength(cert_data_ptr.get())); + + if (x509) { + X509_STORE_add_cert(store, x509); + X509_free(x509); + result = true; + } } - CFObjectPtr cert_data_ptr(cert_data, cf_object_ptr_deleter); - - auto encoded_cert = static_cast( - CFDataGetBytePtr(cert_data_ptr.get())); - - auto x509 = - d2i_X509(NULL, &encoded_cert, CFDataGetLength(cert_data_ptr.get())); - - if (x509) { - X509_STORE_add_cert(store, x509); - X509_free(x509); - result = true; - } - } - - return result; + return result; } inline bool load_system_certs_on_macos(X509_STORE *store) { - auto result = false; - CFObjectPtr certs(nullptr, cf_object_ptr_deleter); - if (retrieve_certs_from_keychain(certs) && certs) { - result = add_certs_to_x509_store(certs.get(), store); - } + auto result = false; + CFObjectPtr certs(nullptr, cf_object_ptr_deleter); + if (retrieve_certs_from_keychain(certs) && certs) { + result = add_certs_to_x509_store(certs.get(), store); + } - if (retrieve_root_certs_from_keychain(certs) && certs) { - result = add_certs_to_x509_store(certs.get(), store) || result; - } + if (retrieve_root_certs_from_keychain(certs) && certs) { + result = add_certs_to_x509_store(certs.get(), store) || result; + } - return result; + return result; } -#endif // TARGET_OS_OSX -#endif // _WIN32 -#endif // CPPHTTPLIB_OPENSSL_SUPPORT +#endif // TARGET_OS_OSX +#endif // _WIN32 +#endif // CPPHTTPLIB_OPENSSL_SUPPORT #ifdef _WIN32 class WSInit { public: - WSInit() { - WSADATA wsaData; - if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true; - } + WSInit() { + WSADATA wsaData; + if (WSAStartup(0x0002, &wsaData) == 0) { + is_valid_ = true; + } + } - ~WSInit() { - if (is_valid_) WSACleanup(); - } + ~WSInit() { + if (is_valid_) { + WSACleanup(); + } + } - bool is_valid_ = false; + bool is_valid_ = false; }; static WSInit wsinit_; @@ -4740,1111 +5116,1132 @@ static WSInit wsinit_; #ifdef CPPHTTPLIB_OPENSSL_SUPPORT inline std::pair make_digest_authentication_header( - const Request &req, const std::map &auth, - size_t cnonce_count, const std::string &cnonce, const std::string &username, - const std::string &password, bool is_proxy = false) { - std::string nc; - { - std::stringstream ss; - ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count; - nc = ss.str(); - } - - std::string qop; - if (auth.find("qop") != auth.end()) { - qop = auth.at("qop"); - if (qop.find("auth-int") != std::string::npos) { - qop = "auth-int"; - } else if (qop.find("auth") != std::string::npos) { - qop = "auth"; - } else { - qop.clear(); + const Request &req, + const std::map &auth, + size_t cnonce_count, + const std::string &cnonce, + const std::string &username, + const std::string &password, + bool is_proxy = false) { + std::string nc; + { + std::stringstream ss; + ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count; + nc = ss.str(); } - } - std::string algo = "MD5"; - if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); } - - std::string response; - { - auto H = algo == "SHA-256" ? detail::SHA_256 - : algo == "SHA-512" ? detail::SHA_512 - : detail::MD5; - - auto A1 = username + ":" + auth.at("realm") + ":" + password; - - auto A2 = req.method + ":" + req.path; - if (qop == "auth-int") { A2 += ":" + H(req.body); } - - if (qop.empty()) { - response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2)); - } else { - response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce + - ":" + qop + ":" + H(A2)); + std::string qop; + if (auth.find("qop") != auth.end()) { + qop = auth.at("qop"); + if (qop.find("auth-int") != std::string::npos) { + qop = "auth-int"; + } else if (qop.find("auth") != std::string::npos) { + qop = "auth"; + } else { + qop.clear(); + } } - } - auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : ""; + std::string algo = "MD5"; + if (auth.find("algorithm") != auth.end()) { + algo = auth.at("algorithm"); + } - auto field = "Digest username=\"" + username + "\", realm=\"" + - auth.at("realm") + "\", nonce=\"" + auth.at("nonce") + - "\", uri=\"" + req.path + "\", algorithm=" + algo + - (qop.empty() ? ", response=\"" - : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" + - cnonce + "\", response=\"") + - response + "\"" + - (opaque.empty() ? "" : ", opaque=\"" + opaque + "\""); + std::string response; + { + auto H = algo == "SHA-256" ? detail::SHA_256 : algo == "SHA-512" ? detail::SHA_512 : detail::MD5; - auto key = is_proxy ? "Proxy-Authorization" : "Authorization"; - return std::make_pair(key, field); + auto A1 = username + ":" + auth.at("realm") + ":" + password; + + auto A2 = req.method + ":" + req.path; + if (qop == "auth-int") { + A2 += ":" + H(req.body); + } + + if (qop.empty()) { + response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2)); + } else { + response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce + ":" + qop + ":" + H(A2)); + } + } + + auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : ""; + + auto field = "Digest username=\"" + username + "\", realm=\"" + auth.at("realm") + "\", nonce=\"" + + auth.at("nonce") + "\", uri=\"" + req.path + "\", algorithm=" + algo + + (qop.empty() ? ", response=\"" : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" + cnonce + "\", response=\"") + + response + "\"" + (opaque.empty() ? "" : ", opaque=\"" + opaque + "\""); + + auto key = is_proxy ? "Proxy-Authorization" : "Authorization"; + return std::make_pair(key, field); } #endif -inline bool parse_www_authenticate(const Response &res, - std::map &auth, - bool is_proxy) { - auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate"; - if (res.has_header(auth_key)) { - static auto re = std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~"); - auto s = res.get_header_value(auth_key); - auto pos = s.find(' '); - if (pos != std::string::npos) { - auto type = s.substr(0, pos); - if (type == "Basic") { - return false; - } else if (type == "Digest") { - s = s.substr(pos + 1); - auto beg = std::sregex_iterator(s.begin(), s.end(), re); - for (auto i = beg; i != std::sregex_iterator(); ++i) { - auto m = *i; - auto key = s.substr(static_cast(m.position(1)), - static_cast(m.length(1))); - auto val = m.length(2) > 0 - ? s.substr(static_cast(m.position(2)), - static_cast(m.length(2))) - : s.substr(static_cast(m.position(3)), - static_cast(m.length(3))); - auth[key] = val; +inline bool parse_www_authenticate(const Response &res, std::map &auth, bool is_proxy) { + auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate"; + if (res.has_header(auth_key)) { + static auto re = std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~"); + auto s = res.get_header_value(auth_key); + auto pos = s.find(' '); + if (pos != std::string::npos) { + auto type = s.substr(0, pos); + if (type == "Basic") { + return false; + } else if (type == "Digest") { + s = s.substr(pos + 1); + auto beg = std::sregex_iterator(s.begin(), s.end(), re); + for (auto i = beg; i != std::sregex_iterator(); ++i) { + auto m = *i; + auto key = s.substr(static_cast(m.position(1)), static_cast(m.length(1))); + auto val = m.length(2) > 0 + ? s.substr(static_cast(m.position(2)), static_cast(m.length(2))) + : s.substr(static_cast(m.position(3)), static_cast(m.length(3))); + auth[key] = val; + } + return true; + } } - return true; - } } - } - return false; + return false; } // https://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c/440240#answer-440240 inline std::string random_string(size_t length) { - auto randchar = []() -> char { - const char charset[] = "0123456789" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz"; - const size_t max_index = (sizeof(charset) - 1); - return charset[static_cast(std::rand()) % max_index]; - }; - std::string str(length, 0); - std::generate_n(str.begin(), length, randchar); - return str; + auto randchar = []() -> char { + const char charset + [] = "0123456789" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz"; + const size_t max_index = (sizeof(charset) - 1); + return charset[static_cast(std::rand()) % max_index]; + }; + std::string str(length, 0); + std::generate_n(str.begin(), length, randchar); + return str; } class ContentProviderAdapter { public: - explicit ContentProviderAdapter( - ContentProviderWithoutLength &&content_provider) - : content_provider_(content_provider) {} + explicit ContentProviderAdapter(ContentProviderWithoutLength &&content_provider) + : content_provider_(content_provider) { + } - bool operator()(size_t offset, size_t, DataSink &sink) { - return content_provider_(offset, sink); - } + bool operator()(size_t offset, size_t, DataSink &sink) { + return content_provider_(offset, sink); + } private: - ContentProviderWithoutLength content_provider_; + ContentProviderWithoutLength content_provider_; }; -} // namespace detail +} // namespace detail inline std::string hosted_at(const std::string &hostname) { - std::vector addrs; - hosted_at(hostname, addrs); - if (addrs.empty()) { return std::string(); } - return addrs[0]; -} - -inline void hosted_at(const std::string &hostname, - std::vector &addrs) { - struct addrinfo hints; - struct addrinfo *result; - - memset(&hints, 0, sizeof(struct addrinfo)); - hints.ai_family = AF_UNSPEC; - hints.ai_socktype = SOCK_STREAM; - hints.ai_protocol = 0; - - if (getaddrinfo(hostname.c_str(), nullptr, &hints, &result)) { -#if defined __linux__ && !defined __ANDROID__ - res_init(); -#endif - return; - } - - for (auto rp = result; rp; rp = rp->ai_next) { - const auto &addr = - *reinterpret_cast(rp->ai_addr); - std::string ip; - auto dummy = -1; - if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip, - dummy)) { - addrs.push_back(ip); + std::vector addrs; + hosted_at(hostname, addrs); + if (addrs.empty()) { + return std::string(); } - } - - freeaddrinfo(result); + return addrs[0]; } -inline std::string append_query_params(const std::string &path, - const Params ¶ms) { - std::string path_with_query = path; - const static std::regex re("[^?]+\\?.*"); - auto delm = std::regex_match(path, re) ? '&' : '?'; - path_with_query += delm + detail::params_to_query_str(params); - return path_with_query; +inline void hosted_at(const std::string &hostname, std::vector &addrs) { + struct addrinfo hints; + struct addrinfo *result; + + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = 0; + + if (getaddrinfo(hostname.c_str(), nullptr, &hints, &result)) { +#if defined __linux__ && !defined __ANDROID__ + res_init(); +#endif + return; + } + + for (auto rp = result; rp; rp = rp->ai_next) { + const auto &addr = *reinterpret_cast(rp->ai_addr); + std::string ip; + auto dummy = -1; + if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip, dummy)) { + addrs.push_back(ip); + } + } + + freeaddrinfo(result); +} + +inline std::string append_query_params(const std::string &path, const Params ¶ms) { + std::string path_with_query = path; + const static std::regex re("[^?]+\\?.*"); + auto delm = std::regex_match(path, re) ? '&' : '?'; + path_with_query += delm + detail::params_to_query_str(params); + return path_with_query; } // Header utilities inline std::pair make_range_header(Ranges ranges) { - std::string field = "bytes="; - auto i = 0; - for (auto r : ranges) { - if (i != 0) { field += ", "; } - if (r.first != -1) { field += std::to_string(r.first); } - field += '-'; - if (r.second != -1) { field += std::to_string(r.second); } - i++; - } - return std::make_pair("Range", std::move(field)); + std::string field = "bytes="; + auto i = 0; + for (auto r : ranges) { + if (i != 0) { + field += ", "; + } + if (r.first != -1) { + field += std::to_string(r.first); + } + field += '-'; + if (r.second != -1) { + field += std::to_string(r.second); + } + i++; + } + return std::make_pair("Range", std::move(field)); } -inline std::pair -make_basic_authentication_header(const std::string &username, - const std::string &password, bool is_proxy) { - auto field = "Basic " + detail::base64_encode(username + ":" + password); - auto key = is_proxy ? "Proxy-Authorization" : "Authorization"; - return std::make_pair(key, std::move(field)); +inline std::pair make_basic_authentication_header(const std::string &username, + const std::string &password, + bool is_proxy) { + auto field = "Basic " + detail::base64_encode(username + ":" + password); + auto key = is_proxy ? "Proxy-Authorization" : "Authorization"; + return std::make_pair(key, std::move(field)); } -inline std::pair -make_bearer_token_authentication_header(const std::string &token, - bool is_proxy = false) { - auto field = "Bearer " + token; - auto key = is_proxy ? "Proxy-Authorization" : "Authorization"; - return std::make_pair(key, std::move(field)); +inline std::pair make_bearer_token_authentication_header(const std::string &token, + bool is_proxy = false) { + auto field = "Bearer " + token; + auto key = is_proxy ? "Proxy-Authorization" : "Authorization"; + return std::make_pair(key, std::move(field)); } // Request implementation inline bool Request::has_header(const std::string &key) const { - return detail::has_header(headers, key); + return detail::has_header(headers, key); } -inline std::string Request::get_header_value(const std::string &key, - size_t id) const { - return detail::get_header_value(headers, key, id, ""); +inline std::string Request::get_header_value(const std::string &key, size_t id) const { + return detail::get_header_value(headers, key, id, ""); } inline size_t Request::get_header_value_count(const std::string &key) const { - auto r = headers.equal_range(key); - return static_cast(std::distance(r.first, r.second)); + auto r = headers.equal_range(key); + return static_cast(std::distance(r.first, r.second)); } -inline void Request::set_header(const std::string &key, - const std::string &val) { - if (!detail::has_crlf(key) && !detail::has_crlf(val)) { - headers.emplace(key, val); - } +inline void Request::set_header(const std::string &key, const std::string &val) { + if (!detail::has_crlf(key) && !detail::has_crlf(val)) { + headers.emplace(key, val); + } } inline bool Request::has_param(const std::string &key) const { - return params.find(key) != params.end(); + return params.find(key) != params.end(); } -inline std::string Request::get_param_value(const std::string &key, - size_t id) const { - auto rng = params.equal_range(key); - auto it = rng.first; - std::advance(it, static_cast(id)); - if (it != rng.second) { return it->second; } - return std::string(); +inline std::string Request::get_param_value(const std::string &key, size_t id) const { + auto rng = params.equal_range(key); + auto it = rng.first; + std::advance(it, static_cast(id)); + if (it != rng.second) { + return it->second; + } + return std::string(); } inline size_t Request::get_param_value_count(const std::string &key) const { - auto r = params.equal_range(key); - return static_cast(std::distance(r.first, r.second)); + auto r = params.equal_range(key); + return static_cast(std::distance(r.first, r.second)); } inline bool Request::is_multipart_form_data() const { - const auto &content_type = get_header_value("Content-Type"); - return !content_type.rfind("multipart/form-data", 0); + const auto &content_type = get_header_value("Content-Type"); + return !content_type.rfind("multipart/form-data", 0); } inline bool Request::has_file(const std::string &key) const { - return files.find(key) != files.end(); + return files.find(key) != files.end(); } inline MultipartFormData Request::get_file_value(const std::string &key) const { - auto it = files.find(key); - if (it != files.end()) { return it->second; } - return MultipartFormData(); + auto it = files.find(key); + if (it != files.end()) { + return it->second; + } + return MultipartFormData(); } -inline std::vector -Request::get_file_values(const std::string &key) const { - std::vector values; - auto rng = files.equal_range(key); - for (auto it = rng.first; it != rng.second; it++) { - values.push_back(it->second); - } - return values; +inline std::vector Request::get_file_values(const std::string &key) const { + std::vector values; + auto rng = files.equal_range(key); + for (auto it = rng.first; it != rng.second; it++) { + values.push_back(it->second); + } + return values; } // Response implementation inline bool Response::has_header(const std::string &key) const { - return headers.find(key) != headers.end(); + return headers.find(key) != headers.end(); } -inline std::string Response::get_header_value(const std::string &key, - size_t id) const { - return detail::get_header_value(headers, key, id, ""); +inline std::string Response::get_header_value(const std::string &key, size_t id) const { + return detail::get_header_value(headers, key, id, ""); } inline size_t Response::get_header_value_count(const std::string &key) const { - auto r = headers.equal_range(key); - return static_cast(std::distance(r.first, r.second)); + auto r = headers.equal_range(key); + return static_cast(std::distance(r.first, r.second)); } -inline void Response::set_header(const std::string &key, - const std::string &val) { - if (!detail::has_crlf(key) && !detail::has_crlf(val)) { - headers.emplace(key, val); - } +inline void Response::set_header(const std::string &key, const std::string &val) { + if (!detail::has_crlf(key) && !detail::has_crlf(val)) { + headers.emplace(key, val); + } } inline void Response::set_redirect(const std::string &url, int stat) { - if (!detail::has_crlf(url)) { - set_header("Location", url); - if (300 <= stat && stat < 400) { - this->status = stat; - } else { - this->status = 302; + if (!detail::has_crlf(url)) { + set_header("Location", url); + if (300 <= stat && stat < 400) { + this->status = stat; + } else { + this->status = 302; + } } - } } -inline void Response::set_content(const char *s, size_t n, - const std::string &content_type) { - body.assign(s, n); +inline void Response::set_content(const char *s, size_t n, const std::string &content_type) { + body.assign(s, n); - auto rng = headers.equal_range("Content-Type"); - headers.erase(rng.first, rng.second); - set_header("Content-Type", content_type); + auto rng = headers.equal_range("Content-Type"); + headers.erase(rng.first, rng.second); + set_header("Content-Type", content_type); } -inline void Response::set_content(const std::string &s, - const std::string &content_type) { - set_content(s.data(), s.size(), content_type); +inline void Response::set_content(const std::string &s, const std::string &content_type) { + set_content(s.data(), s.size(), content_type); } -inline void Response::set_content_provider( - size_t in_length, const std::string &content_type, ContentProvider provider, - ContentProviderResourceReleaser resource_releaser) { - set_header("Content-Type", content_type); - content_length_ = in_length; - if (in_length > 0) { content_provider_ = std::move(provider); } - content_provider_resource_releaser_ = resource_releaser; - is_chunked_content_provider_ = false; +inline void Response::set_content_provider(size_t in_length, + const std::string &content_type, + ContentProvider provider, + ContentProviderResourceReleaser resource_releaser) { + set_header("Content-Type", content_type); + content_length_ = in_length; + if (in_length > 0) { + content_provider_ = std::move(provider); + } + content_provider_resource_releaser_ = resource_releaser; + is_chunked_content_provider_ = false; } -inline void Response::set_content_provider( - const std::string &content_type, ContentProviderWithoutLength provider, - ContentProviderResourceReleaser resource_releaser) { - set_header("Content-Type", content_type); - content_length_ = 0; - content_provider_ = detail::ContentProviderAdapter(std::move(provider)); - content_provider_resource_releaser_ = resource_releaser; - is_chunked_content_provider_ = false; +inline void Response::set_content_provider(const std::string &content_type, + ContentProviderWithoutLength provider, + ContentProviderResourceReleaser resource_releaser) { + set_header("Content-Type", content_type); + content_length_ = 0; + content_provider_ = detail::ContentProviderAdapter(std::move(provider)); + content_provider_resource_releaser_ = resource_releaser; + is_chunked_content_provider_ = false; } -inline void Response::set_chunked_content_provider( - const std::string &content_type, ContentProviderWithoutLength provider, - ContentProviderResourceReleaser resource_releaser) { - set_header("Content-Type", content_type); - content_length_ = 0; - content_provider_ = detail::ContentProviderAdapter(std::move(provider)); - content_provider_resource_releaser_ = resource_releaser; - is_chunked_content_provider_ = true; +inline void Response::set_chunked_content_provider(const std::string &content_type, + ContentProviderWithoutLength provider, + ContentProviderResourceReleaser resource_releaser) { + set_header("Content-Type", content_type); + content_length_ = 0; + content_provider_ = detail::ContentProviderAdapter(std::move(provider)); + content_provider_resource_releaser_ = resource_releaser; + is_chunked_content_provider_ = true; } // Result implementation inline bool Result::has_request_header(const std::string &key) const { - return request_headers_.find(key) != request_headers_.end(); + return request_headers_.find(key) != request_headers_.end(); } -inline std::string Result::get_request_header_value(const std::string &key, - size_t id) const { - return detail::get_header_value(request_headers_, key, id, ""); +inline std::string Result::get_request_header_value(const std::string &key, size_t id) const { + return detail::get_header_value(request_headers_, key, id, ""); } -inline size_t -Result::get_request_header_value_count(const std::string &key) const { - auto r = request_headers_.equal_range(key); - return static_cast(std::distance(r.first, r.second)); +inline size_t Result::get_request_header_value_count(const std::string &key) const { + auto r = request_headers_.equal_range(key); + return static_cast(std::distance(r.first, r.second)); } // Stream implementation inline ssize_t Stream::write(const char *ptr) { - return write(ptr, strlen(ptr)); + return write(ptr, strlen(ptr)); } inline ssize_t Stream::write(const std::string &s) { - return write(s.data(), s.size()); + return write(s.data(), s.size()); } namespace detail { // Socket stream implementation -inline SocketStream::SocketStream(socket_t sock, time_t read_timeout_sec, - time_t read_timeout_usec, - time_t write_timeout_sec, - time_t write_timeout_usec) - : sock_(sock), read_timeout_sec_(read_timeout_sec), +inline SocketStream::SocketStream(socket_t sock, + time_t read_timeout_sec, + time_t read_timeout_usec, + time_t write_timeout_sec, + time_t write_timeout_usec) + : sock_(sock), + read_timeout_sec_(read_timeout_sec), read_timeout_usec_(read_timeout_usec), write_timeout_sec_(write_timeout_sec), - write_timeout_usec_(write_timeout_usec), read_buff_(read_buff_size_, 0) {} + write_timeout_usec_(write_timeout_usec), + read_buff_(read_buff_size_, 0) { +} -inline SocketStream::~SocketStream() {} +inline SocketStream::~SocketStream() { +} inline bool SocketStream::is_readable() const { - return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0; + return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0; } inline bool SocketStream::is_writable() const { - return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 && - is_socket_alive(sock_); + return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 && is_socket_alive(sock_); } inline ssize_t SocketStream::read(char *ptr, size_t size) { #ifdef _WIN32 - size = - (std::min)(size, static_cast((std::numeric_limits::max)())); + size = (std::min)(size, static_cast((std::numeric_limits::max)())); #else - size = (std::min)(size, - static_cast((std::numeric_limits::max)())); + size = (std::min)(size, static_cast((std::numeric_limits::max)())); #endif - if (read_buff_off_ < read_buff_content_size_) { - auto remaining_size = read_buff_content_size_ - read_buff_off_; - if (size <= remaining_size) { - memcpy(ptr, read_buff_.data() + read_buff_off_, size); - read_buff_off_ += size; - return static_cast(size); - } else { - memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size); - read_buff_off_ += remaining_size; - return static_cast(remaining_size); + if (read_buff_off_ < read_buff_content_size_) { + auto remaining_size = read_buff_content_size_ - read_buff_off_; + if (size <= remaining_size) { + memcpy(ptr, read_buff_.data() + read_buff_off_, size); + read_buff_off_ += size; + return static_cast(size); + } else { + memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size); + read_buff_off_ += remaining_size; + return static_cast(remaining_size); + } } - } - if (!is_readable()) { return -1; } - - read_buff_off_ = 0; - read_buff_content_size_ = 0; - - if (size < read_buff_size_) { - auto n = read_socket(sock_, read_buff_.data(), read_buff_size_, - CPPHTTPLIB_RECV_FLAGS); - if (n <= 0) { - return n; - } else if (n <= static_cast(size)) { - memcpy(ptr, read_buff_.data(), static_cast(n)); - return n; - } else { - memcpy(ptr, read_buff_.data(), size); - read_buff_off_ = size; - read_buff_content_size_ = static_cast(n); - return static_cast(size); + if (!is_readable()) { + return -1; + } + + read_buff_off_ = 0; + read_buff_content_size_ = 0; + + if (size < read_buff_size_) { + auto n = read_socket(sock_, read_buff_.data(), read_buff_size_, CPPHTTPLIB_RECV_FLAGS); + if (n <= 0) { + return n; + } else if (n <= static_cast(size)) { + memcpy(ptr, read_buff_.data(), static_cast(n)); + return n; + } else { + memcpy(ptr, read_buff_.data(), size); + read_buff_off_ = size; + read_buff_content_size_ = static_cast(n); + return static_cast(size); + } + } else { + return read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS); } - } else { - return read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS); - } } inline ssize_t SocketStream::write(const char *ptr, size_t size) { - if (!is_writable()) { return -1; } + if (!is_writable()) { + return -1; + } #if defined(_WIN32) && !defined(_WIN64) - size = - (std::min)(size, static_cast((std::numeric_limits::max)())); + size = (std::min)(size, static_cast((std::numeric_limits::max)())); #endif - return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS); + return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS); } -inline void SocketStream::get_remote_ip_and_port(std::string &ip, - int &port) const { - return detail::get_remote_ip_and_port(sock_, ip, port); +inline void SocketStream::get_remote_ip_and_port(std::string &ip, int &port) const { + return detail::get_remote_ip_and_port(sock_, ip, port); } -inline void SocketStream::get_local_ip_and_port(std::string &ip, - int &port) const { - return detail::get_local_ip_and_port(sock_, ip, port); +inline void SocketStream::get_local_ip_and_port(std::string &ip, int &port) const { + return detail::get_local_ip_and_port(sock_, ip, port); } -inline socket_t SocketStream::socket() const { return sock_; } +inline socket_t SocketStream::socket() const { + return sock_; +} // Buffer stream implementation -inline bool BufferStream::is_readable() const { return true; } +inline bool BufferStream::is_readable() const { + return true; +} -inline bool BufferStream::is_writable() const { return true; } +inline bool BufferStream::is_writable() const { + return true; +} inline ssize_t BufferStream::read(char *ptr, size_t size) { #if defined(_MSC_VER) && _MSC_VER < 1910 - auto len_read = buffer._Copy_s(ptr, size, size, position); + auto len_read = buffer._Copy_s(ptr, size, size, position); #else - auto len_read = buffer.copy(ptr, size, position); + auto len_read = buffer.copy(ptr, size, position); #endif - position += static_cast(len_read); - return static_cast(len_read); + position += static_cast(len_read); + return static_cast(len_read); } inline ssize_t BufferStream::write(const char *ptr, size_t size) { - buffer.append(ptr, size); - return static_cast(size); + buffer.append(ptr, size); + return static_cast(size); } -inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/, - int & /*port*/) const {} +inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/, int & /*port*/) const { +} -inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/, - int & /*port*/) const {} +inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/, int & /*port*/) const { +} -inline socket_t BufferStream::socket() const { return 0; } +inline socket_t BufferStream::socket() const { + return 0; +} -inline const std::string &BufferStream::get_buffer() const { return buffer; } +inline const std::string &BufferStream::get_buffer() const { + return buffer; +} inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern) { - // One past the last ending position of a path param substring - std::size_t last_param_end = 0; + // One past the last ending position of a path param substring + std::size_t last_param_end = 0; #ifndef CPPHTTPLIB_NO_EXCEPTIONS - // Needed to ensure that parameter names are unique during matcher - // construction - // If exceptions are disabled, only last duplicate path - // parameter will be set - std::unordered_set param_name_set; + // Needed to ensure that parameter names are unique during matcher + // construction + // If exceptions are disabled, only last duplicate path + // parameter will be set + std::unordered_set param_name_set; #endif - while (true) { - const auto marker_pos = pattern.find(marker, last_param_end); - if (marker_pos == std::string::npos) { break; } + while (true) { + const auto marker_pos = pattern.find(marker, last_param_end); + if (marker_pos == std::string::npos) { + break; + } - static_fragments_.push_back( - pattern.substr(last_param_end, marker_pos - last_param_end)); + static_fragments_.push_back(pattern.substr(last_param_end, marker_pos - last_param_end)); - const auto param_name_start = marker_pos + 1; + const auto param_name_start = marker_pos + 1; - auto sep_pos = pattern.find(separator, param_name_start); - if (sep_pos == std::string::npos) { sep_pos = pattern.length(); } + auto sep_pos = pattern.find(separator, param_name_start); + if (sep_pos == std::string::npos) { + sep_pos = pattern.length(); + } - auto param_name = - pattern.substr(param_name_start, sep_pos - param_name_start); + auto param_name = pattern.substr(param_name_start, sep_pos - param_name_start); #ifndef CPPHTTPLIB_NO_EXCEPTIONS - if (param_name_set.find(param_name) != param_name_set.cend()) { - std::string msg = "Encountered path parameter '" + param_name + - "' multiple times in route pattern '" + pattern + "'."; - throw std::invalid_argument(msg); + if (param_name_set.find(param_name) != param_name_set.cend()) { + std::string msg = "Encountered path parameter '" + param_name + "' multiple times in route pattern '" + + pattern + "'."; + throw std::invalid_argument(msg); + } +#endif + + param_names_.push_back(std::move(param_name)); + + last_param_end = sep_pos + 1; } -#endif - param_names_.push_back(std::move(param_name)); - - last_param_end = sep_pos + 1; - } - - if (last_param_end < pattern.length()) { - static_fragments_.push_back(pattern.substr(last_param_end)); - } + if (last_param_end < pattern.length()) { + static_fragments_.push_back(pattern.substr(last_param_end)); + } } inline bool PathParamsMatcher::match(Request &request) const { - request.matches = {}; - request.path_params.clear(); - request.path_params.reserve(param_names_.size()); + request.matches = {}; + request.path_params.clear(); + request.path_params.reserve(param_names_.size()); - // One past the position at which the path matched the pattern last time - std::size_t starting_pos = 0; - for (size_t i = 0; i < static_fragments_.size(); ++i) { - const auto &fragment = static_fragments_[i]; + // One past the position at which the path matched the pattern last time + std::size_t starting_pos = 0; + for (size_t i = 0; i < static_fragments_.size(); ++i) { + const auto &fragment = static_fragments_[i]; - if (starting_pos + fragment.length() > request.path.length()) { - return false; + if (starting_pos + fragment.length() > request.path.length()) { + return false; + } + + // Avoid unnecessary allocation by using strncmp instead of substr + + // comparison + if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(), fragment.length()) != 0) { + return false; + } + + starting_pos += fragment.length(); + + // Should only happen when we have a static fragment after a param + // Example: '/users/:id/subscriptions' + // The 'subscriptions' fragment here does not have a corresponding param + if (i >= param_names_.size()) { + continue; + } + + auto sep_pos = request.path.find(separator, starting_pos); + if (sep_pos == std::string::npos) { + sep_pos = request.path.length(); + } + + const auto ¶m_name = param_names_[i]; + + request.path_params.emplace(param_name, request.path.substr(starting_pos, sep_pos - starting_pos)); + + // Mark everythin up to '/' as matched + starting_pos = sep_pos + 1; } - - // Avoid unnecessary allocation by using strncmp instead of substr + - // comparison - if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(), - fragment.length()) != 0) { - return false; - } - - starting_pos += fragment.length(); - - // Should only happen when we have a static fragment after a param - // Example: '/users/:id/subscriptions' - // The 'subscriptions' fragment here does not have a corresponding param - if (i >= param_names_.size()) { continue; } - - auto sep_pos = request.path.find(separator, starting_pos); - if (sep_pos == std::string::npos) { sep_pos = request.path.length(); } - - const auto ¶m_name = param_names_[i]; - - request.path_params.emplace( - param_name, request.path.substr(starting_pos, sep_pos - starting_pos)); - - // Mark everythin up to '/' as matched - starting_pos = sep_pos + 1; - } - // Returns false if the path is longer than the pattern - return starting_pos >= request.path.length(); + // Returns false if the path is longer than the pattern + return starting_pos >= request.path.length(); } inline bool RegexMatcher::match(Request &request) const { - request.path_params.clear(); - return std::regex_match(request.path, request.matches, regex_); + request.path_params.clear(); + return std::regex_match(request.path, request.matches, regex_); } -} // namespace detail +} // namespace detail // HTTP server implementation -inline Server::Server() - : new_task_queue( - [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); }) { +inline Server::Server() : new_task_queue([] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); }) { #ifndef _WIN32 - signal(SIGPIPE, SIG_IGN); + signal(SIGPIPE, SIG_IGN); #endif } -inline Server::~Server() {} +inline Server::~Server() { +} -inline std::unique_ptr -Server::make_matcher(const std::string &pattern) { - if (pattern.find("/:") != std::string::npos) { - return detail::make_unique(pattern); - } else { - return detail::make_unique(pattern); - } +inline std::unique_ptr Server::make_matcher(const std::string &pattern) { + if (pattern.find("/:") != std::string::npos) { + return detail::make_unique(pattern); + } else { + return detail::make_unique(pattern); + } } inline Server &Server::Get(const std::string &pattern, Handler handler) { - get_handlers_.push_back( - std::make_pair(make_matcher(pattern), std::move(handler))); - return *this; + get_handlers_.push_back(std::make_pair(make_matcher(pattern), std::move(handler))); + return *this; } inline Server &Server::Post(const std::string &pattern, Handler handler) { - post_handlers_.push_back( - std::make_pair(make_matcher(pattern), std::move(handler))); - return *this; + post_handlers_.push_back(std::make_pair(make_matcher(pattern), std::move(handler))); + return *this; } -inline Server &Server::Post(const std::string &pattern, - HandlerWithContentReader handler) { - post_handlers_for_content_reader_.push_back( - std::make_pair(make_matcher(pattern), std::move(handler))); - return *this; +inline Server &Server::Post(const std::string &pattern, HandlerWithContentReader handler) { + post_handlers_for_content_reader_.push_back(std::make_pair(make_matcher(pattern), std::move(handler))); + return *this; } inline Server &Server::Put(const std::string &pattern, Handler handler) { - put_handlers_.push_back( - std::make_pair(make_matcher(pattern), std::move(handler))); - return *this; + put_handlers_.push_back(std::make_pair(make_matcher(pattern), std::move(handler))); + return *this; } -inline Server &Server::Put(const std::string &pattern, - HandlerWithContentReader handler) { - put_handlers_for_content_reader_.push_back( - std::make_pair(make_matcher(pattern), std::move(handler))); - return *this; +inline Server &Server::Put(const std::string &pattern, HandlerWithContentReader handler) { + put_handlers_for_content_reader_.push_back(std::make_pair(make_matcher(pattern), std::move(handler))); + return *this; } inline Server &Server::Patch(const std::string &pattern, Handler handler) { - patch_handlers_.push_back( - std::make_pair(make_matcher(pattern), std::move(handler))); - return *this; + patch_handlers_.push_back(std::make_pair(make_matcher(pattern), std::move(handler))); + return *this; } -inline Server &Server::Patch(const std::string &pattern, - HandlerWithContentReader handler) { - patch_handlers_for_content_reader_.push_back( - std::make_pair(make_matcher(pattern), std::move(handler))); - return *this; +inline Server &Server::Patch(const std::string &pattern, HandlerWithContentReader handler) { + patch_handlers_for_content_reader_.push_back(std::make_pair(make_matcher(pattern), std::move(handler))); + return *this; } inline Server &Server::Delete(const std::string &pattern, Handler handler) { - delete_handlers_.push_back( - std::make_pair(make_matcher(pattern), std::move(handler))); - return *this; + delete_handlers_.push_back(std::make_pair(make_matcher(pattern), std::move(handler))); + return *this; } -inline Server &Server::Delete(const std::string &pattern, - HandlerWithContentReader handler) { - delete_handlers_for_content_reader_.push_back( - std::make_pair(make_matcher(pattern), std::move(handler))); - return *this; +inline Server &Server::Delete(const std::string &pattern, HandlerWithContentReader handler) { + delete_handlers_for_content_reader_.push_back(std::make_pair(make_matcher(pattern), std::move(handler))); + return *this; } inline Server &Server::Options(const std::string &pattern, Handler handler) { - options_handlers_.push_back( - std::make_pair(make_matcher(pattern), std::move(handler))); - return *this; + options_handlers_.push_back(std::make_pair(make_matcher(pattern), std::move(handler))); + return *this; } -inline bool Server::set_base_dir(const std::string &dir, - const std::string &mount_point) { - return set_mount_point(mount_point, dir); +inline bool Server::set_base_dir(const std::string &dir, const std::string &mount_point) { + return set_mount_point(mount_point, dir); } -inline bool Server::set_mount_point(const std::string &mount_point, - const std::string &dir, Headers headers) { - if (detail::is_dir(dir)) { - std::string mnt = !mount_point.empty() ? mount_point : "/"; - if (!mnt.empty() && mnt[0] == '/') { - base_dirs_.push_back({mnt, dir, std::move(headers)}); - return true; +inline bool Server::set_mount_point(const std::string &mount_point, const std::string &dir, Headers headers) { + if (detail::is_dir(dir)) { + std::string mnt = !mount_point.empty() ? mount_point : "/"; + if (!mnt.empty() && mnt[0] == '/') { + base_dirs_.push_back({mnt, dir, std::move(headers)}); + return true; + } } - } - return false; + return false; } inline bool Server::remove_mount_point(const std::string &mount_point) { - for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) { - if (it->mount_point == mount_point) { - base_dirs_.erase(it); - return true; + for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) { + if (it->mount_point == mount_point) { + base_dirs_.erase(it); + return true; + } } - } - return false; + return false; } -inline Server & -Server::set_file_extension_and_mimetype_mapping(const std::string &ext, - const std::string &mime) { - file_extension_and_mimetype_map_[ext] = mime; - return *this; +inline Server &Server::set_file_extension_and_mimetype_mapping(const std::string &ext, const std::string &mime) { + file_extension_and_mimetype_map_[ext] = mime; + return *this; } inline Server &Server::set_file_request_handler(Handler handler) { - file_request_handler_ = std::move(handler); - return *this; + file_request_handler_ = std::move(handler); + return *this; } inline Server &Server::set_error_handler(HandlerWithResponse handler) { - error_handler_ = std::move(handler); - return *this; + error_handler_ = std::move(handler); + return *this; } inline Server &Server::set_error_handler(Handler handler) { - error_handler_ = [handler](const Request &req, Response &res) { - handler(req, res); - return HandlerResponse::Handled; - }; - return *this; + error_handler_ = [handler](const Request &req, Response &res) { + handler(req, res); + return HandlerResponse::Handled; + }; + return *this; } inline Server &Server::set_exception_handler(ExceptionHandler handler) { - exception_handler_ = std::move(handler); - return *this; + exception_handler_ = std::move(handler); + return *this; } inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) { - pre_routing_handler_ = std::move(handler); - return *this; + pre_routing_handler_ = std::move(handler); + return *this; } inline Server &Server::set_post_routing_handler(Handler handler) { - post_routing_handler_ = std::move(handler); - return *this; + post_routing_handler_ = std::move(handler); + return *this; } inline Server &Server::set_logger(Logger logger) { - logger_ = std::move(logger); - return *this; + logger_ = std::move(logger); + return *this; } -inline Server & -Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) { - expect_100_continue_handler_ = std::move(handler); - return *this; +inline Server &Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) { + expect_100_continue_handler_ = std::move(handler); + return *this; } inline Server &Server::set_address_family(int family) { - address_family_ = family; - return *this; + address_family_ = family; + return *this; } inline Server &Server::set_tcp_nodelay(bool on) { - tcp_nodelay_ = on; - return *this; + tcp_nodelay_ = on; + return *this; } inline Server &Server::set_socket_options(SocketOptions socket_options) { - socket_options_ = std::move(socket_options); - return *this; + socket_options_ = std::move(socket_options); + return *this; } inline Server &Server::set_default_headers(Headers headers) { - default_headers_ = std::move(headers); - return *this; + default_headers_ = std::move(headers); + return *this; } inline Server &Server::set_keep_alive_max_count(size_t count) { - keep_alive_max_count_ = count; - return *this; + keep_alive_max_count_ = count; + return *this; } inline Server &Server::set_keep_alive_timeout(time_t sec) { - keep_alive_timeout_sec_ = sec; - return *this; + keep_alive_timeout_sec_ = sec; + return *this; } inline Server &Server::set_read_timeout(time_t sec, time_t usec) { - read_timeout_sec_ = sec; - read_timeout_usec_ = usec; - return *this; + read_timeout_sec_ = sec; + read_timeout_usec_ = usec; + return *this; } inline Server &Server::set_write_timeout(time_t sec, time_t usec) { - write_timeout_sec_ = sec; - write_timeout_usec_ = usec; - return *this; + write_timeout_sec_ = sec; + write_timeout_usec_ = usec; + return *this; } inline Server &Server::set_idle_interval(time_t sec, time_t usec) { - idle_interval_sec_ = sec; - idle_interval_usec_ = usec; - return *this; + idle_interval_sec_ = sec; + idle_interval_usec_ = usec; + return *this; } inline Server &Server::set_payload_max_length(size_t length) { - payload_max_length_ = length; - return *this; + payload_max_length_ = length; + return *this; } -inline bool Server::bind_to_port(const std::string &host, int port, - int socket_flags) { - if (bind_internal(host, port, socket_flags) < 0) return false; - return true; +inline bool Server::bind_to_port(const std::string &host, int port, int socket_flags) { + if (bind_internal(host, port, socket_flags) < 0) { + return false; + } + return true; } + inline int Server::bind_to_any_port(const std::string &host, int socket_flags) { - return bind_internal(host, 0, socket_flags); + return bind_internal(host, 0, socket_flags); } inline bool Server::listen_after_bind() { - auto se = detail::scope_exit([&]() { done_ = true; }); - return listen_internal(); + auto se = detail::scope_exit([&]() { done_ = true; }); + return listen_internal(); } -inline bool Server::listen(const std::string &host, int port, - int socket_flags) { - auto se = detail::scope_exit([&]() { done_ = true; }); - return bind_to_port(host, port, socket_flags) && listen_internal(); +inline bool Server::listen(const std::string &host, int port, int socket_flags) { + auto se = detail::scope_exit([&]() { done_ = true; }); + return bind_to_port(host, port, socket_flags) && listen_internal(); } -inline bool Server::is_running() const { return is_running_; } +inline bool Server::is_running() const { + return is_running_; +} inline void Server::wait_until_ready() const { - while (!is_running() && !done_) { - std::this_thread::sleep_for(std::chrono::milliseconds{1}); - } + while (!is_running() && !done_) { + std::this_thread::sleep_for(std::chrono::milliseconds {1}); + } } inline void Server::stop() { - if (is_running_) { - assert(svr_sock_ != INVALID_SOCKET); - std::atomic sock(svr_sock_.exchange(INVALID_SOCKET)); - detail::shutdown_socket(sock); - detail::close_socket(sock); - } + if (is_running_) { + assert(svr_sock_ != INVALID_SOCKET); + std::atomic sock(svr_sock_.exchange(INVALID_SOCKET)); + detail::shutdown_socket(sock); + detail::close_socket(sock); + } } inline bool Server::parse_request_line(const char *s, Request &req) { - auto len = strlen(s); - if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; } - len -= 2; + auto len = strlen(s); + if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { + return false; + } + len -= 2; - { - size_t count = 0; + { + size_t count = 0; - detail::split(s, s + len, ' ', [&](const char *b, const char *e) { - switch (count) { - case 0: req.method = std::string(b, e); break; - case 1: req.target = std::string(b, e); break; - case 2: req.version = std::string(b, e); break; - default: break; - } - count++; - }); + detail::split(s, s + len, ' ', [&](const char *b, const char *e) { + switch (count) { + case 0: + req.method = std::string(b, e); + break; + case 1: + req.target = std::string(b, e); + break; + case 2: + req.version = std::string(b, e); + break; + default: + break; + } + count++; + }); - if (count != 3) { return false; } - } - - static const std::set methods{ - "GET", "HEAD", "POST", "PUT", "DELETE", - "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"}; - - if (methods.find(req.method) == methods.end()) { return false; } - - if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") { return false; } - - { - // Skip URL fragment - for (size_t i = 0; i < req.target.size(); i++) { - if (req.target[i] == '#') { - req.target.erase(i); - break; - } + if (count != 3) { + return false; + } } - size_t count = 0; + static const std::set + methods {"GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"}; - detail::split(req.target.data(), req.target.data() + req.target.size(), '?', - [&](const char *b, const char *e) { - switch (count) { - case 0: - req.path = detail::decode_url(std::string(b, e), false); - break; - case 1: { - if (e - b > 0) { + if (methods.find(req.method) == methods.end()) { + return false; + } + + if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") { + return false; + } + + { + // Skip URL fragment + for (size_t i = 0; i < req.target.size(); i++) { + if (req.target[i] == '#') { + req.target.erase(i); + break; + } + } + + size_t count = 0; + + detail::split(req.target.data(), req.target.data() + req.target.size(), '?', [&](const char *b, const char *e) { + switch (count) { + case 0: + req.path = detail::decode_url(std::string(b, e), false); + break; + case 1: { + if (e - b > 0) { detail::parse_query_text(std::string(b, e), req.params); - } - break; } - default: break; - } - count++; - }); + break; + } + default: + break; + } + count++; + }); - if (count > 2) { return false; } - } + if (count > 2) { + return false; + } + } - return true; + return true; } -inline bool Server::write_response(Stream &strm, bool close_connection, - const Request &req, Response &res) { - return write_response_core(strm, close_connection, req, res, false); +inline bool Server::write_response(Stream &strm, bool close_connection, const Request &req, Response &res) { + return write_response_core(strm, close_connection, req, res, false); } -inline bool Server::write_response_with_content(Stream &strm, - bool close_connection, +inline bool Server::write_response_with_content(Stream &strm, + bool close_connection, const Request &req, - Response &res) { - return write_response_core(strm, close_connection, req, res, true); + Response &res) { + return write_response_core(strm, close_connection, req, res, true); } -inline bool Server::write_response_core(Stream &strm, bool close_connection, - const Request &req, Response &res, - bool need_apply_ranges) { - assert(res.status != -1); +inline bool Server::write_response_core(Stream &strm, + bool close_connection, + const Request &req, + Response &res, + bool need_apply_ranges) { + assert(res.status != -1); - if (400 <= res.status && error_handler_ && - error_handler_(req, res) == HandlerResponse::Handled) { - need_apply_ranges = true; - } - - std::string content_type; - std::string boundary; - if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); } - - // Prepare additional headers - if (close_connection || req.get_header_value("Connection") == "close") { - res.set_header("Connection", "close"); - } else { - std::stringstream ss; - ss << "timeout=" << keep_alive_timeout_sec_ - << ", max=" << keep_alive_max_count_; - res.set_header("Keep-Alive", ss.str()); - } - - if (!res.has_header("Content-Type") && - (!res.body.empty() || res.content_length_ > 0 || res.content_provider_)) { - res.set_header("Content-Type", "text/plain"); - } - - if (!res.has_header("Content-Length") && res.body.empty() && - !res.content_length_ && !res.content_provider_) { - res.set_header("Content-Length", "0"); - } - - if (!res.has_header("Accept-Ranges") && req.method == "HEAD") { - res.set_header("Accept-Ranges", "bytes"); - } - - if (post_routing_handler_) { post_routing_handler_(req, res); } - - // Response line and headers - { - detail::BufferStream bstrm; - - if (!bstrm.write_format("HTTP/1.1 %d %s\r\n", res.status, - detail::status_message(res.status))) { - return false; + if (400 <= res.status && error_handler_ && error_handler_(req, res) == HandlerResponse::Handled) { + need_apply_ranges = true; } - if (!detail::write_headers(bstrm, res.headers)) { return false; } - - // Flush buffer - auto &data = bstrm.get_buffer(); - detail::write_data(strm, data.data(), data.size()); - } - - // Body - auto ret = true; - if (req.method != "HEAD") { - if (!res.body.empty()) { - if (!detail::write_data(strm, res.body.data(), res.body.size())) { - ret = false; - } - } else if (res.content_provider_) { - if (write_content_with_provider(strm, req, res, boundary, content_type)) { - res.content_provider_success_ = true; - } else { - res.content_provider_success_ = false; - ret = false; - } + std::string content_type; + std::string boundary; + if (need_apply_ranges) { + apply_ranges(req, res, content_type, boundary); } - } - // Log - if (logger_) { logger_(req, res); } - - return ret; -} - -inline bool -Server::write_content_with_provider(Stream &strm, const Request &req, - Response &res, const std::string &boundary, - const std::string &content_type) { - auto is_shutting_down = [this]() { - return this->svr_sock_ == INVALID_SOCKET; - }; - - if (res.content_length_ > 0) { - if (req.ranges.empty()) { - return detail::write_content(strm, res.content_provider_, 0, - res.content_length_, is_shutting_down); - } else if (req.ranges.size() == 1) { - auto offsets = - detail::get_range_offset_and_length(req, res.content_length_, 0); - auto offset = offsets.first; - auto length = offsets.second; - return detail::write_content(strm, res.content_provider_, offset, length, - is_shutting_down); + // Prepare additional headers + if (close_connection || req.get_header_value("Connection") == "close") { + res.set_header("Connection", "close"); } else { - return detail::write_multipart_ranges_data( - strm, req, res, boundary, content_type, is_shutting_down); + std::stringstream ss; + ss << "timeout=" << keep_alive_timeout_sec_ << ", max=" << keep_alive_max_count_; + res.set_header("Keep-Alive", ss.str()); } - } else { - if (res.is_chunked_content_provider_) { - auto type = detail::encoding_type(req, res); - std::unique_ptr compressor; - if (type == detail::EncodingType::Gzip) { + if (!res.has_header("Content-Type") && (!res.body.empty() || res.content_length_ > 0 || res.content_provider_)) { + res.set_header("Content-Type", "text/plain"); + } + + if (!res.has_header("Content-Length") && res.body.empty() && !res.content_length_ && !res.content_provider_) { + res.set_header("Content-Length", "0"); + } + + if (!res.has_header("Accept-Ranges") && req.method == "HEAD") { + res.set_header("Accept-Ranges", "bytes"); + } + + if (post_routing_handler_) { + post_routing_handler_(req, res); + } + + // Response line and headers + { + detail::BufferStream bstrm; + + if (!bstrm.write_format("HTTP/1.1 %d %s\r\n", res.status, detail::status_message(res.status))) { + return false; + } + + if (!detail::write_headers(bstrm, res.headers)) { + return false; + } + + // Flush buffer + auto &data = bstrm.get_buffer(); + detail::write_data(strm, data.data(), data.size()); + } + + // Body + auto ret = true; + if (req.method != "HEAD") { + if (!res.body.empty()) { + if (!detail::write_data(strm, res.body.data(), res.body.size())) { + ret = false; + } + } else if (res.content_provider_) { + if (write_content_with_provider(strm, req, res, boundary, content_type)) { + res.content_provider_success_ = true; + } else { + res.content_provider_success_ = false; + ret = false; + } + } + } + + // Log + if (logger_) { + logger_(req, res); + } + + return ret; +} + +inline bool Server::write_content_with_provider(Stream &strm, + const Request &req, + Response &res, + const std::string &boundary, + const std::string &content_type) { + auto is_shutting_down = [this]() { return this->svr_sock_ == INVALID_SOCKET; }; + + if (res.content_length_ > 0) { + if (req.ranges.empty()) { + return detail::write_content(strm, res.content_provider_, 0, res.content_length_, is_shutting_down); + } else if (req.ranges.size() == 1) { + auto offsets = detail::get_range_offset_and_length(req, res.content_length_, 0); + auto offset = offsets.first; + auto length = offsets.second; + return detail::write_content(strm, res.content_provider_, offset, length, is_shutting_down); + } else { + return detail::write_multipart_ranges_data(strm, req, res, boundary, content_type, is_shutting_down); + } + } else { + if (res.is_chunked_content_provider_) { + auto type = detail::encoding_type(req, res); + + std::unique_ptr compressor; + if (type == detail::EncodingType::Gzip) { #ifdef CPPHTTPLIB_ZLIB_SUPPORT - compressor = detail::make_unique(); + compressor = detail::make_unique(); #endif - } else if (type == detail::EncodingType::Brotli) { + } else if (type == detail::EncodingType::Brotli) { #ifdef CPPHTTPLIB_BROTLI_SUPPORT - compressor = detail::make_unique(); + compressor = detail::make_unique(); #endif - } else { - compressor = detail::make_unique(); - } - assert(compressor != nullptr); + } else { + compressor = detail::make_unique(); + } + assert(compressor != nullptr); - return detail::write_content_chunked(strm, res.content_provider_, - is_shutting_down, *compressor); - } else { - return detail::write_content_without_length(strm, res.content_provider_, - is_shutting_down); + return detail::write_content_chunked(strm, res.content_provider_, is_shutting_down, *compressor); + } else { + return detail::write_content_without_length(strm, res.content_provider_, is_shutting_down); + } } - } } inline bool Server::read_content(Stream &strm, Request &req, Response &res) { - MultipartFormDataMap::iterator cur; - auto file_count = 0; - if (read_content_core( - strm, req, res, - // Regular - [&](const char *buf, size_t n) { - if (req.body.size() + n > req.body.max_size()) { return false; } - req.body.append(buf, n); - return true; - }, - // Multipart - [&](const MultipartFormData &file) { - if (file_count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) { - return false; + MultipartFormDataMap::iterator cur; + auto file_count = 0; + if (read_content_core( + strm, + req, + res, + // Regular + [&](const char *buf, size_t n) { + if (req.body.size() + n > req.body.max_size()) { + return false; + } + req.body.append(buf, n); + return true; + }, + // Multipart + [&](const MultipartFormData &file) { + if (file_count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) { + return false; + } + cur = req.files.emplace(file.name, file); + return true; + }, + [&](const char *buf, size_t n) { + auto &content = cur->second.content; + if (content.size() + n > content.max_size()) { + return false; + } + content.append(buf, n); + return true; + })) { + const auto &content_type = req.get_header_value("Content-Type"); + if (!content_type.find("application/x-www-form-urlencoded")) { + if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) { + res.status = 413; // NOTE: should be 414? + return false; } - cur = req.files.emplace(file.name, file); - return true; - }, - [&](const char *buf, size_t n) { - auto &content = cur->second.content; - if (content.size() + n > content.max_size()) { return false; } - content.append(buf, n); - return true; - })) { - const auto &content_type = req.get_header_value("Content-Type"); - if (!content_type.find("application/x-www-form-urlencoded")) { - if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) { - res.status = 413; // NOTE: should be 414? - return false; - } - detail::parse_query_text(req.body, req.params); + detail::parse_query_text(req.body, req.params); + } + return true; } - return true; - } - return false; + return false; } -inline bool Server::read_content_with_content_receiver( - Stream &strm, Request &req, Response &res, ContentReceiver receiver, - MultipartContentHeader multipart_header, - ContentReceiver multipart_receiver) { - return read_content_core(strm, req, res, std::move(receiver), - std::move(multipart_header), - std::move(multipart_receiver)); +inline bool Server::read_content_with_content_receiver(Stream &strm, + Request &req, + Response &res, + ContentReceiver receiver, + MultipartContentHeader multipart_header, + ContentReceiver multipart_receiver) { + return read_content_core(strm, + req, + res, + std::move(receiver), + std::move(multipart_header), + std::move(multipart_receiver)); } -inline bool Server::read_content_core(Stream &strm, Request &req, Response &res, - ContentReceiver receiver, +inline bool Server::read_content_core(Stream &strm, + Request &req, + Response &res, + ContentReceiver receiver, MultipartContentHeader multipart_header, - ContentReceiver multipart_receiver) { - detail::MultipartFormDataParser multipart_form_data_parser; - ContentReceiverWithProgress out; + ContentReceiver multipart_receiver) { + detail::MultipartFormDataParser multipart_form_data_parser; + ContentReceiverWithProgress out; - if (req.is_multipart_form_data()) { - const auto &content_type = req.get_header_value("Content-Type"); - std::string boundary; - if (!detail::parse_multipart_boundary(content_type, boundary)) { - res.status = 400; - return false; - } + if (req.is_multipart_form_data()) { + const auto &content_type = req.get_header_value("Content-Type"); + std::string boundary; + if (!detail::parse_multipart_boundary(content_type, boundary)) { + res.status = 400; + return false; + } - multipart_form_data_parser.set_boundary(std::move(boundary)); - out = [&](const char *buf, size_t n, uint64_t /*off*/, uint64_t /*len*/) { - /* For debug + multipart_form_data_parser.set_boundary(std::move(boundary)); + out = [&](const char *buf, size_t n, uint64_t /*off*/, uint64_t /*len*/) { + /* For debug size_t pos = 0; while (pos < n) { auto read_size = (std::min)(1, n - pos); @@ -5855,1984 +6252,2141 @@ inline bool Server::read_content_core(Stream &strm, Request &req, Response &res, } return true; */ - return multipart_form_data_parser.parse(buf, n, multipart_receiver, - multipart_header); - }; - } else { - out = [receiver](const char *buf, size_t n, uint64_t /*off*/, - uint64_t /*len*/) { return receiver(buf, n); }; - } - - if (req.method == "DELETE" && !req.has_header("Content-Length")) { - return true; - } - - if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr, - out, true)) { - return false; - } - - if (req.is_multipart_form_data()) { - if (!multipart_form_data_parser.is_valid()) { - res.status = 400; - return false; - } - } - - return true; -} - -inline bool Server::handle_file_request(const Request &req, Response &res, - bool head) { - for (const auto &entry : base_dirs_) { - // Prefix match - if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) { - std::string sub_path = "/" + req.path.substr(entry.mount_point.size()); - if (detail::is_valid_path(sub_path)) { - auto path = entry.base_dir + sub_path; - if (path.back() == '/') { path += "index.html"; } - - if (detail::is_file(path)) { - detail::read_file(path, res.body); - auto type = - detail::find_content_type(path, file_extension_and_mimetype_map_); - if (type) { res.set_header("Content-Type", type); } - for (const auto &kv : entry.headers) { - res.set_header(kv.first.c_str(), kv.second); - } - res.status = req.has_header("Range") ? 206 : 200; - if (!head && file_request_handler_) { - file_request_handler_(req, res); - } - return true; - } - } - } - } - return false; -} - -inline socket_t -Server::create_server_socket(const std::string &host, int port, - int socket_flags, - SocketOptions socket_options) const { - return detail::create_socket( - host, std::string(), port, address_family_, socket_flags, tcp_nodelay_, - std::move(socket_options), - [](socket_t sock, struct addrinfo &ai) -> bool { - if (::bind(sock, ai.ai_addr, static_cast(ai.ai_addrlen))) { - return false; - } - if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) { return false; } - return true; - }); -} - -inline int Server::bind_internal(const std::string &host, int port, - int socket_flags) { - if (!is_valid()) { return -1; } - - svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_); - if (svr_sock_ == INVALID_SOCKET) { return -1; } - - if (port == 0) { - struct sockaddr_storage addr; - socklen_t addr_len = sizeof(addr); - if (getsockname(svr_sock_, reinterpret_cast(&addr), - &addr_len) == -1) { - return -1; - } - if (addr.ss_family == AF_INET) { - return ntohs(reinterpret_cast(&addr)->sin_port); - } else if (addr.ss_family == AF_INET6) { - return ntohs(reinterpret_cast(&addr)->sin6_port); + return multipart_form_data_parser.parse(buf, n, multipart_receiver, multipart_header); + }; } else { - return -1; + out = [receiver](const char *buf, size_t n, uint64_t /*off*/, uint64_t /*len*/) { return receiver(buf, n); }; + } + + if (req.method == "DELETE" && !req.has_header("Content-Length")) { + return true; + } + + if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr, out, true)) { + return false; + } + + if (req.is_multipart_form_data()) { + if (!multipart_form_data_parser.is_valid()) { + res.status = 400; + return false; + } + } + + return true; +} + +inline bool Server::handle_file_request(const Request &req, Response &res, bool head) { + for (const auto &entry : base_dirs_) { + // Prefix match + if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) { + std::string sub_path = "/" + req.path.substr(entry.mount_point.size()); + if (detail::is_valid_path(sub_path)) { + auto path = entry.base_dir + sub_path; + if (path.back() == '/') { + path += "index.html"; + } + + if (detail::is_file(path)) { + detail::read_file(path, res.body); + auto type = detail::find_content_type(path, file_extension_and_mimetype_map_); + if (type) { + res.set_header("Content-Type", type); + } + for (const auto &kv : entry.headers) { + res.set_header(kv.first.c_str(), kv.second); + } + res.status = req.has_header("Range") ? 206 : 200; + if (!head && file_request_handler_) { + file_request_handler_(req, res); + } + return true; + } + } + } + } + return false; +} + +inline socket_t Server::create_server_socket(const std::string &host, + int port, + int socket_flags, + SocketOptions socket_options) const { + return detail::create_socket(host, + std::string(), + port, + address_family_, + socket_flags, + tcp_nodelay_, + std::move(socket_options), + [](socket_t sock, struct addrinfo &ai) -> bool { + if (::bind(sock, ai.ai_addr, static_cast(ai.ai_addrlen))) { + return false; + } + if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) { + return false; + } + return true; + }); +} + +inline int Server::bind_internal(const std::string &host, int port, int socket_flags) { + if (!is_valid()) { + return -1; + } + + svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_); + if (svr_sock_ == INVALID_SOCKET) { + return -1; + } + + if (port == 0) { + struct sockaddr_storage addr; + socklen_t addr_len = sizeof(addr); + if (getsockname(svr_sock_, reinterpret_cast(&addr), &addr_len) == -1) { + return -1; + } + if (addr.ss_family == AF_INET) { + return ntohs(reinterpret_cast(&addr)->sin_port); + } else if (addr.ss_family == AF_INET6) { + return ntohs(reinterpret_cast(&addr)->sin6_port); + } else { + return -1; + } + } else { + return port; } - } else { - return port; - } } inline bool Server::listen_internal() { - auto ret = true; - is_running_ = true; - auto se = detail::scope_exit([&]() { is_running_ = false; }); + auto ret = true; + is_running_ = true; + auto se = detail::scope_exit([&]() { is_running_ = false; }); - { - std::unique_ptr task_queue(new_task_queue()); + { + std::unique_ptr task_queue(new_task_queue()); - while (svr_sock_ != INVALID_SOCKET) { + while (svr_sock_ != INVALID_SOCKET) { #ifndef _WIN32 - if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) { + if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) { #endif - auto val = detail::select_read(svr_sock_, idle_interval_sec_, - idle_interval_usec_); - if (val == 0) { // Timeout - task_queue->on_idle(); - continue; - } + auto val = detail::select_read(svr_sock_, idle_interval_sec_, idle_interval_usec_); + if (val == 0) { // Timeout + task_queue->on_idle(); + continue; + } #ifndef _WIN32 - } + } #endif - socket_t sock = accept(svr_sock_, nullptr, nullptr); + socket_t sock = accept(svr_sock_, nullptr, nullptr); - if (sock == INVALID_SOCKET) { - if (errno == EMFILE) { - // The per-process limit of open file descriptors has been reached. - // Try to accept new connections after a short sleep. - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - continue; - } else if (errno == EINTR || errno == EAGAIN) { - continue; - } - if (svr_sock_ != INVALID_SOCKET) { - detail::close_socket(svr_sock_); - ret = false; - } else { - ; // The server socket was closed by user. - } - break; - } + if (sock == INVALID_SOCKET) { + if (errno == EMFILE) { + // The per-process limit of open file descriptors has been reached. + // Try to accept new connections after a short sleep. + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + continue; + } else if (errno == EINTR || errno == EAGAIN) { + continue; + } + if (svr_sock_ != INVALID_SOCKET) { + detail::close_socket(svr_sock_); + ret = false; + } else { + ; // The server socket was closed by user. + } + break; + } - { + { #ifdef _WIN32 - auto timeout = static_cast(read_timeout_sec_ * 1000 + - read_timeout_usec_ / 1000); - setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, - reinterpret_cast(&timeout), sizeof(timeout)); + auto timeout = static_cast(read_timeout_sec_ * 1000 + read_timeout_usec_ / 1000); + setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast(&timeout), sizeof(timeout)); #else - timeval tv; - tv.tv_sec = static_cast(read_timeout_sec_); - tv.tv_usec = static_cast(read_timeout_usec_); - setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, - reinterpret_cast(&tv), sizeof(tv)); + timeval tv; + tv.tv_sec = static_cast(read_timeout_sec_); + tv.tv_usec = static_cast(read_timeout_usec_); + setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast(&tv), sizeof(tv)); #endif - } - { + } + { #ifdef _WIN32 - auto timeout = static_cast(write_timeout_sec_ * 1000 + - write_timeout_usec_ / 1000); - setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, - reinterpret_cast(&timeout), sizeof(timeout)); + auto timeout = static_cast(write_timeout_sec_ * 1000 + write_timeout_usec_ / 1000); + setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast(&timeout), sizeof(timeout)); #else - timeval tv; - tv.tv_sec = static_cast(write_timeout_sec_); - tv.tv_usec = static_cast(write_timeout_usec_); - setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, - reinterpret_cast(&tv), sizeof(tv)); + timeval tv; + tv.tv_sec = static_cast(write_timeout_sec_); + tv.tv_usec = static_cast(write_timeout_usec_); + setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast(&tv), sizeof(tv)); #endif - } + } - task_queue->enqueue([this, sock]() { process_and_close_socket(sock); }); + task_queue->enqueue([this, sock]() { process_and_close_socket(sock); }); + } + + task_queue->shutdown(); } - task_queue->shutdown(); - } - - return ret; + return ret; } inline bool Server::routing(Request &req, Response &res, Stream &strm) { - if (pre_routing_handler_ && - pre_routing_handler_(req, res) == HandlerResponse::Handled) { - return true; - } - - // File handler - auto is_head_request = req.method == "HEAD"; - if ((req.method == "GET" || is_head_request) && - handle_file_request(req, res, is_head_request)) { - return true; - } - - if (detail::expect_content(req)) { - // Content reader handler - { - ContentReader reader( - [&](ContentReceiver receiver) { - return read_content_with_content_receiver( - strm, req, res, std::move(receiver), nullptr, nullptr); - }, - [&](MultipartContentHeader header, ContentReceiver receiver) { - return read_content_with_content_receiver(strm, req, res, nullptr, - std::move(header), - std::move(receiver)); - }); - - if (req.method == "POST") { - if (dispatch_request_for_content_reader( - req, res, std::move(reader), - post_handlers_for_content_reader_)) { - return true; - } - } else if (req.method == "PUT") { - if (dispatch_request_for_content_reader( - req, res, std::move(reader), - put_handlers_for_content_reader_)) { - return true; - } - } else if (req.method == "PATCH") { - if (dispatch_request_for_content_reader( - req, res, std::move(reader), - patch_handlers_for_content_reader_)) { - return true; - } - } else if (req.method == "DELETE") { - if (dispatch_request_for_content_reader( - req, res, std::move(reader), - delete_handlers_for_content_reader_)) { - return true; - } - } + if (pre_routing_handler_ && pre_routing_handler_(req, res) == HandlerResponse::Handled) { + return true; } - // Read content into `req.body` - if (!read_content(strm, req, res)) { return false; } - } + // File handler + auto is_head_request = req.method == "HEAD"; + if ((req.method == "GET" || is_head_request) && handle_file_request(req, res, is_head_request)) { + return true; + } - // Regular handler - if (req.method == "GET" || req.method == "HEAD") { - return dispatch_request(req, res, get_handlers_); - } else if (req.method == "POST") { - return dispatch_request(req, res, post_handlers_); - } else if (req.method == "PUT") { - return dispatch_request(req, res, put_handlers_); - } else if (req.method == "DELETE") { - return dispatch_request(req, res, delete_handlers_); - } else if (req.method == "OPTIONS") { - return dispatch_request(req, res, options_handlers_); - } else if (req.method == "PATCH") { - return dispatch_request(req, res, patch_handlers_); - } + if (detail::expect_content(req)) { + // Content reader handler + { + ContentReader reader( + [&](ContentReceiver receiver) { + return read_content_with_content_receiver(strm, req, res, std::move(receiver), nullptr, nullptr); + }, + [&](MultipartContentHeader header, ContentReceiver receiver) { + return read_content_with_content_receiver(strm, + req, + res, + nullptr, + std::move(header), + std::move(receiver)); + }); - res.status = 400; - return false; + if (req.method == "POST") { + if (dispatch_request_for_content_reader(req, + res, + std::move(reader), + post_handlers_for_content_reader_)) { + return true; + } + } else if (req.method == "PUT") { + if (dispatch_request_for_content_reader(req, + res, + std::move(reader), + put_handlers_for_content_reader_)) { + return true; + } + } else if (req.method == "PATCH") { + if (dispatch_request_for_content_reader(req, + res, + std::move(reader), + patch_handlers_for_content_reader_)) { + return true; + } + } else if (req.method == "DELETE") { + if (dispatch_request_for_content_reader(req, + res, + std::move(reader), + delete_handlers_for_content_reader_)) { + return true; + } + } + } + + // Read content into `req.body` + if (!read_content(strm, req, res)) { + return false; + } + } + + // Regular handler + if (req.method == "GET" || req.method == "HEAD") { + return dispatch_request(req, res, get_handlers_); + } else if (req.method == "POST") { + return dispatch_request(req, res, post_handlers_); + } else if (req.method == "PUT") { + return dispatch_request(req, res, put_handlers_); + } else if (req.method == "DELETE") { + return dispatch_request(req, res, delete_handlers_); + } else if (req.method == "OPTIONS") { + return dispatch_request(req, res, options_handlers_); + } else if (req.method == "PATCH") { + return dispatch_request(req, res, patch_handlers_); + } + + res.status = 400; + return false; } -inline bool Server::dispatch_request(Request &req, Response &res, - const Handlers &handlers) { - for (const auto &x : handlers) { - const auto &matcher = x.first; - const auto &handler = x.second; +inline bool Server::dispatch_request(Request &req, Response &res, const Handlers &handlers) { + for (const auto &x : handlers) { + const auto &matcher = x.first; + const auto &handler = x.second; - if (matcher->match(req)) { - handler(req, res); - return true; + if (matcher->match(req)) { + handler(req, res); + return true; + } } - } - return false; + return false; } -inline void Server::apply_ranges(const Request &req, Response &res, - std::string &content_type, - std::string &boundary) { - if (req.ranges.size() > 1) { - boundary = detail::make_multipart_data_boundary(); +inline void Server::apply_ranges(const Request &req, Response &res, std::string &content_type, std::string &boundary) { + if (req.ranges.size() > 1) { + boundary = detail::make_multipart_data_boundary(); - auto it = res.headers.find("Content-Type"); - if (it != res.headers.end()) { - content_type = it->second; - res.headers.erase(it); - } - - res.set_header("Content-Type", - "multipart/byteranges; boundary=" + boundary); - } - - auto type = detail::encoding_type(req, res); - - if (res.body.empty()) { - if (res.content_length_ > 0) { - size_t length = 0; - if (req.ranges.empty()) { - length = res.content_length_; - } else if (req.ranges.size() == 1) { - auto offsets = - detail::get_range_offset_and_length(req, res.content_length_, 0); - auto offset = offsets.first; - length = offsets.second; - auto content_range = detail::make_content_range_header_field( - offset, length, res.content_length_); - res.set_header("Content-Range", content_range); - } else { - length = detail::get_multipart_ranges_data_length(req, res, boundary, - content_type); - } - res.set_header("Content-Length", std::to_string(length)); - } else { - if (res.content_provider_) { - if (res.is_chunked_content_provider_) { - res.set_header("Transfer-Encoding", "chunked"); - if (type == detail::EncodingType::Gzip) { - res.set_header("Content-Encoding", "gzip"); - } else if (type == detail::EncodingType::Brotli) { - res.set_header("Content-Encoding", "br"); - } + auto it = res.headers.find("Content-Type"); + if (it != res.headers.end()) { + content_type = it->second; + res.headers.erase(it); } - } + + res.set_header("Content-Type", "multipart/byteranges; boundary=" + boundary); } - } else { - if (req.ranges.empty()) { - ; - } else if (req.ranges.size() == 1) { - auto offsets = - detail::get_range_offset_and_length(req, res.body.size(), 0); - auto offset = offsets.first; - auto length = offsets.second; - auto content_range = detail::make_content_range_header_field( - offset, length, res.body.size()); - res.set_header("Content-Range", content_range); - if (offset < res.body.size()) { - res.body = res.body.substr(offset, length); - } else { - res.body.clear(); - res.status = 416; - } + + auto type = detail::encoding_type(req, res); + + if (res.body.empty()) { + if (res.content_length_ > 0) { + size_t length = 0; + if (req.ranges.empty()) { + length = res.content_length_; + } else if (req.ranges.size() == 1) { + auto offsets = detail::get_range_offset_and_length(req, res.content_length_, 0); + auto offset = offsets.first; + length = offsets.second; + auto content_range = detail::make_content_range_header_field(offset, length, res.content_length_); + res.set_header("Content-Range", content_range); + } else { + length = detail::get_multipart_ranges_data_length(req, res, boundary, content_type); + } + res.set_header("Content-Length", std::to_string(length)); + } else { + if (res.content_provider_) { + if (res.is_chunked_content_provider_) { + res.set_header("Transfer-Encoding", "chunked"); + if (type == detail::EncodingType::Gzip) { + res.set_header("Content-Encoding", "gzip"); + } else if (type == detail::EncodingType::Brotli) { + res.set_header("Content-Encoding", "br"); + } + } + } + } } else { - std::string data; - if (detail::make_multipart_ranges_data(req, res, boundary, content_type, - data)) { - res.body.swap(data); - } else { - res.body.clear(); - res.status = 416; - } - } + if (req.ranges.empty()) { + ; + } else if (req.ranges.size() == 1) { + auto offsets = detail::get_range_offset_and_length(req, res.body.size(), 0); + auto offset = offsets.first; + auto length = offsets.second; + auto content_range = detail::make_content_range_header_field(offset, length, res.body.size()); + res.set_header("Content-Range", content_range); + if (offset < res.body.size()) { + res.body = res.body.substr(offset, length); + } else { + res.body.clear(); + res.status = 416; + } + } else { + std::string data; + if (detail::make_multipart_ranges_data(req, res, boundary, content_type, data)) { + res.body.swap(data); + } else { + res.body.clear(); + res.status = 416; + } + } - if (type != detail::EncodingType::None) { - std::unique_ptr compressor; - std::string content_encoding; + if (type != detail::EncodingType::None) { + std::unique_ptr compressor; + std::string content_encoding; - if (type == detail::EncodingType::Gzip) { + if (type == detail::EncodingType::Gzip) { #ifdef CPPHTTPLIB_ZLIB_SUPPORT - compressor = detail::make_unique(); - content_encoding = "gzip"; + compressor = detail::make_unique(); + content_encoding = "gzip"; #endif - } else if (type == detail::EncodingType::Brotli) { + } else if (type == detail::EncodingType::Brotli) { #ifdef CPPHTTPLIB_BROTLI_SUPPORT - compressor = detail::make_unique(); - content_encoding = "br"; + compressor = detail::make_unique(); + content_encoding = "br"; #endif - } + } - if (compressor) { - std::string compressed; - if (compressor->compress(res.body.data(), res.body.size(), true, - [&](const char *data, size_t data_len) { - compressed.append(data, data_len); - return true; - })) { - res.body.swap(compressed); - res.set_header("Content-Encoding", content_encoding); + if (compressor) { + std::string compressed; + if (compressor->compress(res.body.data(), + res.body.size(), + true, + [&](const char *data, size_t data_len) { + compressed.append(data, data_len); + return true; + })) { + res.body.swap(compressed); + res.set_header("Content-Encoding", content_encoding); + } + } } - } - } - auto length = std::to_string(res.body.size()); - res.set_header("Content-Length", length); - } + auto length = std::to_string(res.body.size()); + res.set_header("Content-Length", length); + } } -inline bool Server::dispatch_request_for_content_reader( - Request &req, Response &res, ContentReader content_reader, - const HandlersForContentReader &handlers) { - for (const auto &x : handlers) { - const auto &matcher = x.first; - const auto &handler = x.second; +inline bool Server::dispatch_request_for_content_reader(Request &req, + Response &res, + ContentReader content_reader, + const HandlersForContentReader &handlers) { + for (const auto &x : handlers) { + const auto &matcher = x.first; + const auto &handler = x.second; - if (matcher->match(req)) { - handler(req, res, content_reader); - return true; + if (matcher->match(req)) { + handler(req, res, content_reader); + return true; + } } - } - return false; + return false; } -inline bool -Server::process_request(Stream &strm, bool close_connection, - bool &connection_closed, - const std::function &setup_request) { - std::array buf{}; +inline bool Server::process_request(Stream &strm, + bool close_connection, + bool &connection_closed, + const std::function &setup_request) { + std::array buf {}; - detail::stream_line_reader line_reader(strm, buf.data(), buf.size()); + detail::stream_line_reader line_reader(strm, buf.data(), buf.size()); - // Connection has been closed on client - if (!line_reader.getline()) { return false; } - - Request req; - Response res; - - res.version = "HTTP/1.1"; - - for (const auto &header : default_headers_) { - if (res.headers.find(header.first) == res.headers.end()) { - res.headers.insert(header); + // Connection has been closed on client + if (!line_reader.getline()) { + return false; + } + + Request req; + Response res; + + res.version = "HTTP/1.1"; + + for (const auto &header : default_headers_) { + if (res.headers.find(header.first) == res.headers.end()) { + res.headers.insert(header); + } } - } #ifdef _WIN32 - // TODO: Increase FD_SETSIZE statically (libzmq), dynamically (MySQL). + // TODO: Increase FD_SETSIZE statically (libzmq), dynamically (MySQL). #else #ifndef CPPHTTPLIB_USE_POLL - // Socket file descriptor exceeded FD_SETSIZE... - if (strm.socket() >= FD_SETSIZE) { - Headers dummy; - detail::read_headers(strm, dummy); - res.status = 500; - return write_response(strm, close_connection, req, res); - } + // Socket file descriptor exceeded FD_SETSIZE... + if (strm.socket() >= FD_SETSIZE) { + Headers dummy; + detail::read_headers(strm, dummy); + res.status = 500; + return write_response(strm, close_connection, req, res); + } #endif #endif - // Check if the request URI doesn't exceed the limit - if (line_reader.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) { - Headers dummy; - detail::read_headers(strm, dummy); - res.status = 414; - return write_response(strm, close_connection, req, res); - } - - // Request line and headers - if (!parse_request_line(line_reader.ptr(), req) || - !detail::read_headers(strm, req.headers)) { - res.status = 400; - return write_response(strm, close_connection, req, res); - } - - if (req.get_header_value("Connection") == "close") { - connection_closed = true; - } - - if (req.version == "HTTP/1.0" && - req.get_header_value("Connection") != "Keep-Alive") { - connection_closed = true; - } - - strm.get_remote_ip_and_port(req.remote_addr, req.remote_port); - req.set_header("REMOTE_ADDR", req.remote_addr); - req.set_header("REMOTE_PORT", std::to_string(req.remote_port)); - - strm.get_local_ip_and_port(req.local_addr, req.local_port); - req.set_header("LOCAL_ADDR", req.local_addr); - req.set_header("LOCAL_PORT", std::to_string(req.local_port)); - - if (req.has_header("Range")) { - const auto &range_header_value = req.get_header_value("Range"); - if (!detail::parse_range_header(range_header_value, req.ranges)) { - res.status = 416; - return write_response(strm, close_connection, req, res); + // Check if the request URI doesn't exceed the limit + if (line_reader.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) { + Headers dummy; + detail::read_headers(strm, dummy); + res.status = 414; + return write_response(strm, close_connection, req, res); } - } - if (setup_request) { setup_request(req); } - - if (req.get_header_value("Expect") == "100-continue") { - auto status = 100; - if (expect_100_continue_handler_) { - status = expect_100_continue_handler_(req, res); + // Request line and headers + if (!parse_request_line(line_reader.ptr(), req) || !detail::read_headers(strm, req.headers)) { + res.status = 400; + return write_response(strm, close_connection, req, res); } - switch (status) { - case 100: - case 417: - strm.write_format("HTTP/1.1 %d %s\r\n\r\n", status, - detail::status_message(status)); - break; - default: return write_response(strm, close_connection, req, res); - } - } - // Rounting - bool routed = false; -#ifdef CPPHTTPLIB_NO_EXCEPTIONS - routed = routing(req, res, strm); -#else - try { - routed = routing(req, res, strm); - } catch (std::exception &e) { - if (exception_handler_) { - auto ep = std::current_exception(); - exception_handler_(req, res, ep); - routed = true; - } else { - res.status = 500; - std::string val; - auto s = e.what(); - for (size_t i = 0; s[i]; i++) { - switch (s[i]) { - case '\r': val += "\\r"; break; - case '\n': val += "\\n"; break; - default: val += s[i]; break; + if (req.get_header_value("Connection") == "close") { + connection_closed = true; + } + + if (req.version == "HTTP/1.0" && req.get_header_value("Connection") != "Keep-Alive") { + connection_closed = true; + } + + strm.get_remote_ip_and_port(req.remote_addr, req.remote_port); + req.set_header("REMOTE_ADDR", req.remote_addr); + req.set_header("REMOTE_PORT", std::to_string(req.remote_port)); + + strm.get_local_ip_and_port(req.local_addr, req.local_port); + req.set_header("LOCAL_ADDR", req.local_addr); + req.set_header("LOCAL_PORT", std::to_string(req.local_port)); + + if (req.has_header("Range")) { + const auto &range_header_value = req.get_header_value("Range"); + if (!detail::parse_range_header(range_header_value, req.ranges)) { + res.status = 416; + return write_response(strm, close_connection, req, res); } - } - res.set_header("EXCEPTION_WHAT", val); } - } catch (...) { - if (exception_handler_) { - auto ep = std::current_exception(); - exception_handler_(req, res, ep); - routed = true; - } else { - res.status = 500; - res.set_header("EXCEPTION_WHAT", "UNKNOWN"); + + if (setup_request) { + setup_request(req); + } + + if (req.get_header_value("Expect") == "100-continue") { + auto status = 100; + if (expect_100_continue_handler_) { + status = expect_100_continue_handler_(req, res); + } + switch (status) { + case 100: + case 417: + strm.write_format("HTTP/1.1 %d %s\r\n\r\n", status, detail::status_message(status)); + break; + default: + return write_response(strm, close_connection, req, res); + } + } + + // Rounting + bool routed = false; +#ifdef CPPHTTPLIB_NO_EXCEPTIONS + routed = routing(req, res, strm); +#else + try { + routed = routing(req, res, strm); + } + catch (std::exception &e) { + if (exception_handler_) { + auto ep = std::current_exception(); + exception_handler_(req, res, ep); + routed = true; + } else { + res.status = 500; + std::string val; + auto s = e.what(); + for (size_t i = 0; s[i]; i++) { + switch (s[i]) { + case '\r': + val += "\\r"; + break; + case '\n': + val += "\\n"; + break; + default: + val += s[i]; + break; + } + } + res.set_header("EXCEPTION_WHAT", val); + } + } + catch (...) { + if (exception_handler_) { + auto ep = std::current_exception(); + exception_handler_(req, res, ep); + routed = true; + } else { + res.status = 500; + res.set_header("EXCEPTION_WHAT", "UNKNOWN"); + } } - } #endif - if (routed) { - if (res.status == -1) { res.status = req.ranges.empty() ? 200 : 206; } - return write_response_with_content(strm, close_connection, req, res); - } else { - if (res.status == -1) { res.status = 404; } - return write_response(strm, close_connection, req, res); - } + if (routed) { + if (res.status == -1) { + res.status = req.ranges.empty() ? 200 : 206; + } + return write_response_with_content(strm, close_connection, req, res); + } else { + if (res.status == -1) { + res.status = 404; + } + return write_response(strm, close_connection, req, res); + } } -inline bool Server::is_valid() const { return true; } +inline bool Server::is_valid() const { + return true; +} inline bool Server::process_and_close_socket(socket_t sock) { - auto ret = detail::process_server_socket( - svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_, - read_timeout_sec_, read_timeout_usec_, write_timeout_sec_, - write_timeout_usec_, - [this](Stream &strm, bool close_connection, bool &connection_closed) { - return process_request(strm, close_connection, connection_closed, - nullptr); - }); + auto ret = detail::process_server_socket( + svr_sock_, + sock, + keep_alive_max_count_, + keep_alive_timeout_sec_, + read_timeout_sec_, + read_timeout_usec_, + write_timeout_sec_, + write_timeout_usec_, + [this](Stream &strm, bool close_connection, bool &connection_closed) { + return process_request(strm, close_connection, connection_closed, nullptr); + }); - detail::shutdown_socket(sock); - detail::close_socket(sock); - return ret; + detail::shutdown_socket(sock); + detail::close_socket(sock); + return ret; } // HTTP client implementation -inline ClientImpl::ClientImpl(const std::string &host) - : ClientImpl(host, 80, std::string(), std::string()) {} - -inline ClientImpl::ClientImpl(const std::string &host, int port) - : ClientImpl(host, port, std::string(), std::string()) {} - -inline ClientImpl::ClientImpl(const std::string &host, int port, - const std::string &client_cert_path, - const std::string &client_key_path) - : host_(host), port_(port), - host_and_port_(adjust_host_string(host) + ":" + std::to_string(port)), - client_cert_path_(client_cert_path), client_key_path_(client_key_path) {} - -inline ClientImpl::~ClientImpl() { - std::lock_guard guard(socket_mutex_); - shutdown_socket(socket_); - close_socket(socket_); +inline ClientImpl::ClientImpl(const std::string &host) : ClientImpl(host, 80, std::string(), std::string()) { } -inline bool ClientImpl::is_valid() const { return true; } +inline ClientImpl::ClientImpl(const std::string &host, int port) + : ClientImpl(host, port, std::string(), std::string()) { +} + +inline ClientImpl::ClientImpl(const std::string &host, + int port, + const std::string &client_cert_path, + const std::string &client_key_path) + : host_(host), + port_(port), + host_and_port_(adjust_host_string(host) + ":" + std::to_string(port)), + client_cert_path_(client_cert_path), + client_key_path_(client_key_path) { +} + +inline ClientImpl::~ClientImpl() { + std::lock_guard guard(socket_mutex_); + shutdown_socket(socket_); + close_socket(socket_); +} + +inline bool ClientImpl::is_valid() const { + return true; +} inline void ClientImpl::copy_settings(const ClientImpl &rhs) { - client_cert_path_ = rhs.client_cert_path_; - client_key_path_ = rhs.client_key_path_; - connection_timeout_sec_ = rhs.connection_timeout_sec_; - read_timeout_sec_ = rhs.read_timeout_sec_; - read_timeout_usec_ = rhs.read_timeout_usec_; - write_timeout_sec_ = rhs.write_timeout_sec_; - write_timeout_usec_ = rhs.write_timeout_usec_; - basic_auth_username_ = rhs.basic_auth_username_; - basic_auth_password_ = rhs.basic_auth_password_; - bearer_token_auth_token_ = rhs.bearer_token_auth_token_; + client_cert_path_ = rhs.client_cert_path_; + client_key_path_ = rhs.client_key_path_; + connection_timeout_sec_ = rhs.connection_timeout_sec_; + read_timeout_sec_ = rhs.read_timeout_sec_; + read_timeout_usec_ = rhs.read_timeout_usec_; + write_timeout_sec_ = rhs.write_timeout_sec_; + write_timeout_usec_ = rhs.write_timeout_usec_; + basic_auth_username_ = rhs.basic_auth_username_; + basic_auth_password_ = rhs.basic_auth_password_; + bearer_token_auth_token_ = rhs.bearer_token_auth_token_; #ifdef CPPHTTPLIB_OPENSSL_SUPPORT - digest_auth_username_ = rhs.digest_auth_username_; - digest_auth_password_ = rhs.digest_auth_password_; + digest_auth_username_ = rhs.digest_auth_username_; + digest_auth_password_ = rhs.digest_auth_password_; #endif - keep_alive_ = rhs.keep_alive_; - follow_location_ = rhs.follow_location_; - url_encode_ = rhs.url_encode_; - address_family_ = rhs.address_family_; - tcp_nodelay_ = rhs.tcp_nodelay_; - socket_options_ = rhs.socket_options_; - compress_ = rhs.compress_; - decompress_ = rhs.decompress_; - interface_ = rhs.interface_; - proxy_host_ = rhs.proxy_host_; - proxy_port_ = rhs.proxy_port_; - proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_; - proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_; - proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_; + keep_alive_ = rhs.keep_alive_; + follow_location_ = rhs.follow_location_; + url_encode_ = rhs.url_encode_; + address_family_ = rhs.address_family_; + tcp_nodelay_ = rhs.tcp_nodelay_; + socket_options_ = rhs.socket_options_; + compress_ = rhs.compress_; + decompress_ = rhs.decompress_; + interface_ = rhs.interface_; + proxy_host_ = rhs.proxy_host_; + proxy_port_ = rhs.proxy_port_; + proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_; + proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_; + proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_; #ifdef CPPHTTPLIB_OPENSSL_SUPPORT - proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_; - proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_; + proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_; + proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_; #endif #ifdef CPPHTTPLIB_OPENSSL_SUPPORT - ca_cert_file_path_ = rhs.ca_cert_file_path_; - ca_cert_dir_path_ = rhs.ca_cert_dir_path_; - ca_cert_store_ = rhs.ca_cert_store_; + ca_cert_file_path_ = rhs.ca_cert_file_path_; + ca_cert_dir_path_ = rhs.ca_cert_dir_path_; + ca_cert_store_ = rhs.ca_cert_store_; #endif #ifdef CPPHTTPLIB_OPENSSL_SUPPORT - server_certificate_verification_ = rhs.server_certificate_verification_; + server_certificate_verification_ = rhs.server_certificate_verification_; #endif - logger_ = rhs.logger_; + logger_ = rhs.logger_; } inline socket_t ClientImpl::create_client_socket(Error &error) const { - if (!proxy_host_.empty() && proxy_port_ != -1) { - return detail::create_client_socket( - proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_, - socket_options_, connection_timeout_sec_, connection_timeout_usec_, - read_timeout_sec_, read_timeout_usec_, write_timeout_sec_, - write_timeout_usec_, interface_, error); - } + if (!proxy_host_.empty() && proxy_port_ != -1) { + return detail::create_client_socket(proxy_host_, + std::string(), + proxy_port_, + address_family_, + tcp_nodelay_, + socket_options_, + connection_timeout_sec_, + connection_timeout_usec_, + read_timeout_sec_, + read_timeout_usec_, + write_timeout_sec_, + write_timeout_usec_, + interface_, + error); + } - // Check is custom IP specified for host_ - std::string ip; - auto it = addr_map_.find(host_); - if (it != addr_map_.end()) ip = it->second; + // Check is custom IP specified for host_ + std::string ip; + auto it = addr_map_.find(host_); + if (it != addr_map_.end()) { + ip = it->second; + } - return detail::create_client_socket( - host_, ip, port_, address_family_, tcp_nodelay_, socket_options_, - connection_timeout_sec_, connection_timeout_usec_, read_timeout_sec_, - read_timeout_usec_, write_timeout_sec_, write_timeout_usec_, interface_, - error); + return detail::create_client_socket(host_, + ip, + port_, + address_family_, + tcp_nodelay_, + socket_options_, + connection_timeout_sec_, + connection_timeout_usec_, + read_timeout_sec_, + read_timeout_usec_, + write_timeout_sec_, + write_timeout_usec_, + interface_, + error); } -inline bool ClientImpl::create_and_connect_socket(Socket &socket, - Error &error) { - auto sock = create_client_socket(error); - if (sock == INVALID_SOCKET) { return false; } - socket.sock = sock; - return true; +inline bool ClientImpl::create_and_connect_socket(Socket &socket, Error &error) { + auto sock = create_client_socket(error); + if (sock == INVALID_SOCKET) { + return false; + } + + if (_postConnCb) { + _postConnCb(sock); + } + socket.sock = sock; + return true; } -inline void ClientImpl::shutdown_ssl(Socket & /*socket*/, - bool /*shutdown_gracefully*/) { - // If there are any requests in flight from threads other than us, then it's - // a thread-unsafe race because individual ssl* objects are not thread-safe. - assert(socket_requests_in_flight_ == 0 || - socket_requests_are_from_thread_ == std::this_thread::get_id()); +inline void ClientImpl::shutdown_ssl(Socket & /*socket*/, bool /*shutdown_gracefully*/) { + // If there are any requests in flight from threads other than us, then it's + // a thread-unsafe race because individual ssl* objects are not thread-safe. + assert(socket_requests_in_flight_ == 0 || socket_requests_are_from_thread_ == std::this_thread::get_id()); } inline void ClientImpl::shutdown_socket(Socket &socket) { - if (socket.sock == INVALID_SOCKET) { return; } - detail::shutdown_socket(socket.sock); + if (socket.sock == INVALID_SOCKET) { + return; + } + detail::shutdown_socket(socket.sock); } inline void ClientImpl::close_socket(Socket &socket) { - // If there are requests in flight in another thread, usually closing - // the socket will be fine and they will simply receive an error when - // using the closed socket, but it is still a bug since rarely the OS - // may reassign the socket id to be used for a new socket, and then - // suddenly they will be operating on a live socket that is different - // than the one they intended! - assert(socket_requests_in_flight_ == 0 || - socket_requests_are_from_thread_ == std::this_thread::get_id()); + // If there are requests in flight in another thread, usually closing + // the socket will be fine and they will simply receive an error when + // using the closed socket, but it is still a bug since rarely the OS + // may reassign the socket id to be used for a new socket, and then + // suddenly they will be operating on a live socket that is different + // than the one they intended! + assert(socket_requests_in_flight_ == 0 || socket_requests_are_from_thread_ == std::this_thread::get_id()); - // It is also a bug if this happens while SSL is still active + // It is also a bug if this happens while SSL is still active #ifdef CPPHTTPLIB_OPENSSL_SUPPORT - assert(socket.ssl == nullptr); + assert(socket.ssl == nullptr); #endif - if (socket.sock == INVALID_SOCKET) { return; } - detail::close_socket(socket.sock); - socket.sock = INVALID_SOCKET; + if (socket.sock == INVALID_SOCKET) { + return; + } + detail::close_socket(socket.sock); + socket.sock = INVALID_SOCKET; } -inline bool ClientImpl::read_response_line(Stream &strm, const Request &req, - Response &res) { - std::array buf{}; +inline bool ClientImpl::read_response_line(Stream &strm, const Request &req, Response &res) { + std::array buf {}; - detail::stream_line_reader line_reader(strm, buf.data(), buf.size()); + detail::stream_line_reader line_reader(strm, buf.data(), buf.size()); - if (!line_reader.getline()) { return false; } + if (!line_reader.getline()) { + return false; + } #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR - const static std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n"); + const static std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n"); #else - const static std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n"); + const static std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n"); #endif - std::cmatch m; - if (!std::regex_match(line_reader.ptr(), m, re)) { - return req.method == "CONNECT"; - } - res.version = std::string(m[1]); - res.status = std::stoi(std::string(m[2])); - res.reason = std::string(m[3]); - - // Ignore '100 Continue' - while (res.status == 100) { - if (!line_reader.getline()) { return false; } // CRLF - if (!line_reader.getline()) { return false; } // next response line - - if (!std::regex_match(line_reader.ptr(), m, re)) { return false; } + std::cmatch m; + if (!std::regex_match(line_reader.ptr(), m, re)) { + return req.method == "CONNECT"; + } res.version = std::string(m[1]); - res.status = std::stoi(std::string(m[2])); - res.reason = std::string(m[3]); - } + res.status = std::stoi(std::string(m[2])); + res.reason = std::string(m[3]); - return true; + // Ignore '100 Continue' + while (res.status == 100) { + if (!line_reader.getline()) { + return false; + } // CRLF + if (!line_reader.getline()) { + return false; + } // next response line + + if (!std::regex_match(line_reader.ptr(), m, re)) { + return false; + } + res.version = std::string(m[1]); + res.status = std::stoi(std::string(m[2])); + res.reason = std::string(m[3]); + } + + return true; } inline bool ClientImpl::send(Request &req, Response &res, Error &error) { - std::lock_guard request_mutex_guard(request_mutex_); - auto ret = send_(req, res, error); - if (error == Error::SSLPeerCouldBeClosed_) { - assert(!ret); - ret = send_(req, res, error); - } - return ret; + std::lock_guard request_mutex_guard(request_mutex_); + auto ret = send_(req, res, error); + if (error == Error::SSLPeerCouldBeClosed_) { + assert(!ret); + ret = send_(req, res, error); + } + return ret; } inline bool ClientImpl::send_(Request &req, Response &res, Error &error) { - { - std::lock_guard guard(socket_mutex_); + { + std::lock_guard guard(socket_mutex_); - // Set this to false immediately - if it ever gets set to true by the end of - // the request, we know another thread instructed us to close the socket. - socket_should_be_closed_when_request_is_done_ = false; + // Set this to false immediately - if it ever gets set to true by the end of + // the request, we know another thread instructed us to close the socket. + socket_should_be_closed_when_request_is_done_ = false; - auto is_alive = false; - if (socket_.is_open()) { - is_alive = detail::is_socket_alive(socket_.sock); - if (!is_alive) { - // Attempt to avoid sigpipe by shutting down nongracefully if it seems - // like the other side has already closed the connection Also, there - // cannot be any requests in flight from other threads since we locked - // request_mutex_, so safe to close everything immediately - const bool shutdown_gracefully = false; - shutdown_ssl(socket_, shutdown_gracefully); - shutdown_socket(socket_); - close_socket(socket_); - } - } - - if (!is_alive) { - if (!create_and_connect_socket(socket_, error)) { return false; } - -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - // TODO: refactoring - if (is_ssl()) { - auto &scli = static_cast(*this); - if (!proxy_host_.empty() && proxy_port_ != -1) { - auto success = false; - if (!scli.connect_with_proxy(socket_, res, success, error)) { - return success; - } + auto is_alive = false; + if (socket_.is_open()) { + is_alive = detail::is_socket_alive(socket_.sock); + if (!is_alive) { + // Attempt to avoid sigpipe by shutting down nongracefully if it seems + // like the other side has already closed the connection Also, there + // cannot be any requests in flight from other threads since we locked + // request_mutex_, so safe to close everything immediately + const bool shutdown_gracefully = false; + shutdown_ssl(socket_, shutdown_gracefully); + shutdown_socket(socket_); + close_socket(socket_); + } } - if (!scli.initialize_ssl(socket_, error)) { return false; } - } + if (!is_alive) { + if (!create_and_connect_socket(socket_, error)) { + return false; + } + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + // TODO: refactoring + if (is_ssl()) { + auto &scli = static_cast(*this); + if (!proxy_host_.empty() && proxy_port_ != -1) { + auto success = false; + if (!scli.connect_with_proxy(socket_, res, success, error)) { + return success; + } + } + + if (!scli.initialize_ssl(socket_, error)) { + return false; + } + } #endif + } + + // Mark the current socket as being in use so that it cannot be closed by + // anyone else while this request is ongoing, even though we will be + // releasing the mutex. + if (socket_requests_in_flight_ > 1) { + assert(socket_requests_are_from_thread_ == std::this_thread::get_id()); + } + socket_requests_in_flight_ += 1; + socket_requests_are_from_thread_ = std::this_thread::get_id(); } - // Mark the current socket as being in use so that it cannot be closed by - // anyone else while this request is ongoing, even though we will be - // releasing the mutex. - if (socket_requests_in_flight_ > 1) { - assert(socket_requests_are_from_thread_ == std::this_thread::get_id()); - } - socket_requests_in_flight_ += 1; - socket_requests_are_from_thread_ = std::this_thread::get_id(); - } - - for (const auto &header : default_headers_) { - if (req.headers.find(header.first) == req.headers.end()) { - req.headers.insert(header); - } - } - - auto ret = false; - auto close_connection = !keep_alive_; - - auto se = detail::scope_exit([&]() { - // Briefly lock mutex in order to mark that a request is no longer ongoing - std::lock_guard guard(socket_mutex_); - socket_requests_in_flight_ -= 1; - if (socket_requests_in_flight_ <= 0) { - assert(socket_requests_in_flight_ == 0); - socket_requests_are_from_thread_ = std::thread::id(); + for (const auto &header : default_headers_) { + if (req.headers.find(header.first) == req.headers.end()) { + req.headers.insert(header); + } } - if (socket_should_be_closed_when_request_is_done_ || close_connection || - !ret) { - shutdown_ssl(socket_, true); - shutdown_socket(socket_); - close_socket(socket_); + auto ret = false; + auto close_connection = !keep_alive_; + + auto se = detail::scope_exit([&]() { + // Briefly lock mutex in order to mark that a request is no longer ongoing + std::lock_guard guard(socket_mutex_); + socket_requests_in_flight_ -= 1; + if (socket_requests_in_flight_ <= 0) { + assert(socket_requests_in_flight_ == 0); + socket_requests_are_from_thread_ = std::thread::id(); + } + + if (socket_should_be_closed_when_request_is_done_ || close_connection || !ret) { + shutdown_ssl(socket_, true); + shutdown_socket(socket_); + close_socket(socket_); + } + }); + + ret = process_socket(socket_, + [&](Stream &strm) { return handle_request(strm, req, res, close_connection, error); }); + + if (!ret) { + if (error == Error::Success) { + error = Error::Unknown; + } } - }); - ret = process_socket(socket_, [&](Stream &strm) { - return handle_request(strm, req, res, close_connection, error); - }); - - if (!ret) { - if (error == Error::Success) { error = Error::Unknown; } - } - - return ret; + return ret; } inline Result ClientImpl::send(const Request &req) { - auto req2 = req; - return send_(std::move(req2)); + auto req2 = req; + return send_(std::move(req2)); } inline Result ClientImpl::send_(Request &&req) { - auto res = detail::make_unique(); - auto error = Error::Success; - auto ret = send(req, *res, error); - return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)}; + auto res = detail::make_unique(); + auto error = Error::Success; + auto ret = send(req, *res, error); + return Result {ret ? std::move(res) : nullptr, error, std::move(req.headers)}; } -inline bool ClientImpl::handle_request(Stream &strm, Request &req, - Response &res, bool close_connection, - Error &error) { - if (req.path.empty()) { - error = Error::Connection; - return false; - } +inline bool ClientImpl::handle_request(Stream &strm, Request &req, Response &res, bool close_connection, Error &error) { + if (req.path.empty()) { + error = Error::Connection; + return false; + } - auto req_save = req; + auto req_save = req; - bool ret; + bool ret; - if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) { - auto req2 = req; - req2.path = "http://" + host_and_port_ + req.path; - ret = process_request(strm, req2, res, close_connection, error); - req = req2; - req.path = req_save.path; - } else { - ret = process_request(strm, req, res, close_connection, error); - } + if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) { + auto req2 = req; + req2.path = "http://" + host_and_port_ + req.path; + ret = process_request(strm, req2, res, close_connection, error); + req = req2; + req.path = req_save.path; + } else { + ret = process_request(strm, req, res, close_connection, error); + } - if (!ret) { return false; } + if (!ret) { + return false; + } - if (300 < res.status && res.status < 400 && follow_location_) { - req = req_save; - ret = redirect(req, res, error); - } + if (300 < res.status && res.status < 400 && follow_location_) { + req = req_save; + ret = redirect(req, res, error); + } #ifdef CPPHTTPLIB_OPENSSL_SUPPORT - if ((res.status == 401 || res.status == 407) && - req.authorization_count_ < 5) { - auto is_proxy = res.status == 407; - const auto &username = - is_proxy ? proxy_digest_auth_username_ : digest_auth_username_; - const auto &password = - is_proxy ? proxy_digest_auth_password_ : digest_auth_password_; + if ((res.status == 401 || res.status == 407) && req.authorization_count_ < 5) { + auto is_proxy = res.status == 407; + const auto &username = is_proxy ? proxy_digest_auth_username_ : digest_auth_username_; + const auto &password = is_proxy ? proxy_digest_auth_password_ : digest_auth_password_; - if (!username.empty() && !password.empty()) { - std::map auth; - if (detail::parse_www_authenticate(res, auth, is_proxy)) { - Request new_req = req; - new_req.authorization_count_ += 1; - new_req.headers.erase(is_proxy ? "Proxy-Authorization" - : "Authorization"); - new_req.headers.insert(detail::make_digest_authentication_header( - req, auth, new_req.authorization_count_, detail::random_string(10), - username, password, is_proxy)); + if (!username.empty() && !password.empty()) { + std::map auth; + if (detail::parse_www_authenticate(res, auth, is_proxy)) { + Request new_req = req; + new_req.authorization_count_ += 1; + new_req.headers.erase(is_proxy ? "Proxy-Authorization" : "Authorization"); + new_req.headers.insert(detail::make_digest_authentication_header(req, + auth, + new_req.authorization_count_, + detail::random_string(10), + username, + password, + is_proxy)); - Response new_res; + Response new_res; - ret = send(new_req, new_res, error); - if (ret) { res = new_res; } - } + ret = send(new_req, new_res, error); + if (ret) { + res = new_res; + } + } + } } - } #endif - return ret; + return ret; } inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) { - if (req.redirect_count_ == 0) { - error = Error::ExceedRedirectCount; - return false; - } + if (req.redirect_count_ == 0) { + error = Error::ExceedRedirectCount; + return false; + } - auto location = res.get_header_value("location"); - if (location.empty()) { return false; } + auto location = res.get_header_value("location"); + if (location.empty()) { + return false; + } - const static std::regex re( - R"((?:(https?):)?(?://(?:\[([\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*)(\?[^#]*)?(?:#.*)?)"); + const static std::regex re( + R"((?:(https?):)?(?://(?:\[([\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*)(\?[^#]*)?(?:#.*)?)"); - std::smatch m; - if (!std::regex_match(location, m, re)) { return false; } + std::smatch m; + if (!std::regex_match(location, m, re)) { + return false; + } - auto scheme = is_ssl() ? "https" : "http"; + auto scheme = is_ssl() ? "https" : "http"; - auto next_scheme = m[1].str(); - auto next_host = m[2].str(); - if (next_host.empty()) { next_host = m[3].str(); } - auto port_str = m[4].str(); - auto next_path = m[5].str(); - auto next_query = m[6].str(); + auto next_scheme = m[1].str(); + auto next_host = m[2].str(); + if (next_host.empty()) { + next_host = m[3].str(); + } + auto port_str = m[4].str(); + auto next_path = m[5].str(); + auto next_query = m[6].str(); - auto next_port = port_; - if (!port_str.empty()) { - next_port = std::stoi(port_str); - } else if (!next_scheme.empty()) { - next_port = next_scheme == "https" ? 443 : 80; - } + auto next_port = port_; + if (!port_str.empty()) { + next_port = std::stoi(port_str); + } else if (!next_scheme.empty()) { + next_port = next_scheme == "https" ? 443 : 80; + } - if (next_scheme.empty()) { next_scheme = scheme; } - if (next_host.empty()) { next_host = host_; } - if (next_path.empty()) { next_path = "/"; } + if (next_scheme.empty()) { + next_scheme = scheme; + } + if (next_host.empty()) { + next_host = host_; + } + if (next_path.empty()) { + next_path = "/"; + } - auto path = detail::decode_url(next_path, true) + next_query; + auto path = detail::decode_url(next_path, true) + next_query; - if (next_scheme == scheme && next_host == host_ && next_port == port_) { - return detail::redirect(*this, req, res, path, location, error); - } else { - if (next_scheme == "https") { + if (next_scheme == scheme && next_host == host_ && next_port == port_) { + return detail::redirect(*this, req, res, path, location, error); + } else { + if (next_scheme == "https") { #ifdef CPPHTTPLIB_OPENSSL_SUPPORT - SSLClient cli(next_host.c_str(), next_port); - cli.copy_settings(*this); - if (ca_cert_store_) { cli.set_ca_cert_store(ca_cert_store_); } - return detail::redirect(cli, req, res, path, location, error); + SSLClient cli(next_host.c_str(), next_port); + cli.copy_settings(*this); + if (ca_cert_store_) { + cli.set_ca_cert_store(ca_cert_store_); + } + return detail::redirect(cli, req, res, path, location, error); #else - return false; + return false; #endif - } else { - ClientImpl cli(next_host.c_str(), next_port); - cli.copy_settings(*this); - return detail::redirect(cli, req, res, path, location, error); + } else { + ClientImpl cli(next_host.c_str(), next_port); + cli.copy_settings(*this); + return detail::redirect(cli, req, res, path, location, error); + } } - } } -inline bool ClientImpl::write_content_with_provider(Stream &strm, - const Request &req, - Error &error) { - auto is_shutting_down = []() { return false; }; +inline bool ClientImpl::write_content_with_provider(Stream &strm, const Request &req, Error &error) { + auto is_shutting_down = []() { return false; }; - if (req.is_chunked_content_provider_) { - // TODO: Brotli support - std::unique_ptr compressor; + if (req.is_chunked_content_provider_) { + // TODO: Brotli support + std::unique_ptr compressor; #ifdef CPPHTTPLIB_ZLIB_SUPPORT - if (compress_) { - compressor = detail::make_unique(); - } else + if (compress_) { + compressor = detail::make_unique(); + } else #endif - { - compressor = detail::make_unique(); - } + { + compressor = detail::make_unique(); + } - return detail::write_content_chunked(strm, req.content_provider_, - is_shutting_down, *compressor, error); - } else { - return detail::write_content(strm, req.content_provider_, 0, - req.content_length_, is_shutting_down, error); - } + return detail::write_content_chunked(strm, req.content_provider_, is_shutting_down, *compressor, error); + } else { + return detail::write_content(strm, req.content_provider_, 0, req.content_length_, is_shutting_down, error); + } } -inline bool ClientImpl::write_request(Stream &strm, Request &req, - bool close_connection, Error &error) { - // Prepare additional headers - if (close_connection) { - if (!req.has_header("Connection")) { - req.set_header("Connection", "close"); +inline bool ClientImpl::write_request(Stream &strm, Request &req, bool close_connection, Error &error) { + // Prepare additional headers + if (close_connection) { + if (!req.has_header("Connection")) { + req.set_header("Connection", "close"); + } } - } - if (!req.has_header("Host")) { - if (is_ssl()) { - if (port_ == 443) { - req.set_header("Host", host_); - } else { - req.set_header("Host", host_and_port_); - } - } else { - if (port_ == 80) { - req.set_header("Host", host_); - } else { - req.set_header("Host", host_and_port_); - } + if (!req.has_header("Host")) { + if (is_ssl()) { + if (port_ == 443) { + req.set_header("Host", host_); + } else { + req.set_header("Host", host_and_port_); + } + } else { + if (port_ == 80) { + req.set_header("Host", host_); + } else { + req.set_header("Host", host_and_port_); + } + } } - } - if (!req.has_header("Accept")) { req.set_header("Accept", "*/*"); } + if (!req.has_header("Accept")) { + req.set_header("Accept", "*/*"); + } #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT - if (!req.has_header("User-Agent")) { - auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION; - req.set_header("User-Agent", agent); - } + if (!req.has_header("User-Agent")) { + auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION; + req.set_header("User-Agent", agent); + } #endif - if (req.body.empty()) { - if (req.content_provider_) { - if (!req.is_chunked_content_provider_) { - if (!req.has_header("Content-Length")) { - auto length = std::to_string(req.content_length_); - req.set_header("Content-Length", length); + if (req.body.empty()) { + if (req.content_provider_) { + if (!req.is_chunked_content_provider_) { + if (!req.has_header("Content-Length")) { + auto length = std::to_string(req.content_length_); + req.set_header("Content-Length", length); + } + } + } else { + if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH") { + req.set_header("Content-Length", "0"); + } } - } } else { - if (req.method == "POST" || req.method == "PUT" || - req.method == "PATCH") { - req.set_header("Content-Length", "0"); - } - } - } else { - if (!req.has_header("Content-Type")) { - req.set_header("Content-Type", "text/plain"); + if (!req.has_header("Content-Type")) { + req.set_header("Content-Type", "text/plain"); + } + + if (!req.has_header("Content-Length")) { + auto length = std::to_string(req.body.size()); + req.set_header("Content-Length", length); + } } - if (!req.has_header("Content-Length")) { - auto length = std::to_string(req.body.size()); - req.set_header("Content-Length", length); + if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) { + if (!req.has_header("Authorization")) { + req.headers.insert(make_basic_authentication_header(basic_auth_username_, basic_auth_password_, false)); + } } - } - if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) { - if (!req.has_header("Authorization")) { - req.headers.insert(make_basic_authentication_header( - basic_auth_username_, basic_auth_password_, false)); + if (!proxy_basic_auth_username_.empty() && !proxy_basic_auth_password_.empty()) { + if (!req.has_header("Proxy-Authorization")) { + req.headers.insert( + make_basic_authentication_header(proxy_basic_auth_username_, proxy_basic_auth_password_, true)); + } } - } - if (!proxy_basic_auth_username_.empty() && - !proxy_basic_auth_password_.empty()) { - if (!req.has_header("Proxy-Authorization")) { - req.headers.insert(make_basic_authentication_header( - proxy_basic_auth_username_, proxy_basic_auth_password_, true)); + if (!bearer_token_auth_token_.empty()) { + if (!req.has_header("Authorization")) { + req.headers.insert(make_bearer_token_authentication_header(bearer_token_auth_token_, false)); + } } - } - if (!bearer_token_auth_token_.empty()) { - if (!req.has_header("Authorization")) { - req.headers.insert(make_bearer_token_authentication_header( - bearer_token_auth_token_, false)); + if (!proxy_bearer_token_auth_token_.empty()) { + if (!req.has_header("Proxy-Authorization")) { + req.headers.insert(make_bearer_token_authentication_header(proxy_bearer_token_auth_token_, true)); + } } - } - if (!proxy_bearer_token_auth_token_.empty()) { - if (!req.has_header("Proxy-Authorization")) { - req.headers.insert(make_bearer_token_authentication_header( - proxy_bearer_token_auth_token_, true)); + // Request line and headers + { + detail::BufferStream bstrm; + + const auto &path = url_encode_ ? detail::encode_url(req.path) : req.path; + bstrm.write_format("%s %s HTTP/1.1\r\n", req.method.c_str(), path.c_str()); + + detail::write_headers(bstrm, req.headers); + + // Flush buffer + auto &data = bstrm.get_buffer(); + if (!detail::write_data(strm, data.data(), data.size())) { + error = Error::Write; + return false; + } } - } - // Request line and headers - { - detail::BufferStream bstrm; - - const auto &path = url_encode_ ? detail::encode_url(req.path) : req.path; - bstrm.write_format("%s %s HTTP/1.1\r\n", req.method.c_str(), path.c_str()); - - detail::write_headers(bstrm, req.headers); - - // Flush buffer - auto &data = bstrm.get_buffer(); - if (!detail::write_data(strm, data.data(), data.size())) { - error = Error::Write; - return false; + // Body + if (req.body.empty()) { + return write_content_with_provider(strm, req, error); } - } - // Body - if (req.body.empty()) { - return write_content_with_provider(strm, req, error); - } + if (!detail::write_data(strm, req.body.data(), req.body.size())) { + error = Error::Write; + return false; + } - if (!detail::write_data(strm, req.body.data(), req.body.size())) { - error = Error::Write; - return false; - } - - return true; + return true; } inline std::unique_ptr ClientImpl::send_with_content_provider( - Request &req, const char *body, size_t content_length, - ContentProvider content_provider, + Request &req, + const char *body, + size_t content_length, + ContentProvider content_provider, ContentProviderWithoutLength content_provider_without_length, - const std::string &content_type, Error &error) { - if (!content_type.empty()) { req.set_header("Content-Type", content_type); } + const std::string &content_type, + Error &error) { + if (!content_type.empty()) { + req.set_header("Content-Type", content_type); + } #ifdef CPPHTTPLIB_ZLIB_SUPPORT - if (compress_) { req.set_header("Content-Encoding", "gzip"); } + if (compress_) { + req.set_header("Content-Encoding", "gzip"); + } #endif #ifdef CPPHTTPLIB_ZLIB_SUPPORT - if (compress_ && !content_provider_without_length) { - // TODO: Brotli support - detail::gzip_compressor compressor; + if (compress_ && !content_provider_without_length) { + // TODO: Brotli support + detail::gzip_compressor compressor; - if (content_provider) { - auto ok = true; - size_t offset = 0; - DataSink data_sink; + if (content_provider) { + auto ok = true; + size_t offset = 0; + DataSink data_sink; - data_sink.write = [&](const char *data, size_t data_len) -> bool { - if (ok) { - auto last = offset + data_len == content_length; + data_sink.write = [&](const char *data, size_t data_len) -> bool { + if (ok) { + auto last = offset + data_len == content_length; - auto ret = compressor.compress( - data, data_len, last, - [&](const char *compressed_data, size_t compressed_data_len) { - req.body.append(compressed_data, compressed_data_len); - return true; - }); + auto ret = compressor.compress(data, + data_len, + last, + [&](const char *compressed_data, size_t compressed_data_len) { + req.body.append(compressed_data, compressed_data_len); + return true; + }); - if (ret) { - offset += data_len; - } else { - ok = false; - } + if (ret) { + offset += data_len; + } else { + ok = false; + } + } + return ok; + }; + + while (ok && offset < content_length) { + if (!content_provider(offset, content_length - offset, data_sink)) { + error = Error::Canceled; + return nullptr; + } + } + } else { + if (!compressor.compress(body, content_length, true, [&](const char *data, size_t data_len) { + req.body.append(data, data_len); + return true; + })) { + error = Error::Compression; + return nullptr; + } } - return ok; - }; - - while (ok && offset < content_length) { - if (!content_provider(offset, content_length - offset, data_sink)) { - error = Error::Canceled; - return nullptr; - } - } - } else { - if (!compressor.compress(body, content_length, true, - [&](const char *data, size_t data_len) { - req.body.append(data, data_len); - return true; - })) { - error = Error::Compression; - return nullptr; - } - } - } else + } else #endif - { - if (content_provider) { - req.content_length_ = content_length; - req.content_provider_ = std::move(content_provider); - req.is_chunked_content_provider_ = false; - } else if (content_provider_without_length) { - req.content_length_ = 0; - req.content_provider_ = detail::ContentProviderAdapter( - std::move(content_provider_without_length)); - req.is_chunked_content_provider_ = true; - req.set_header("Transfer-Encoding", "chunked"); - } else { - req.body.assign(body, content_length); + { + if (content_provider) { + req.content_length_ = content_length; + req.content_provider_ = std::move(content_provider); + req.is_chunked_content_provider_ = false; + } else if (content_provider_without_length) { + req.content_length_ = 0; + req.content_provider_ = detail::ContentProviderAdapter(std::move(content_provider_without_length)); + req.is_chunked_content_provider_ = true; + req.set_header("Transfer-Encoding", "chunked"); + } else { + req.body.assign(body, content_length); + } } - } - auto res = detail::make_unique(); - return send(req, *res, error) ? std::move(res) : nullptr; + auto res = detail::make_unique(); + return send(req, *res, error) ? std::move(res) : nullptr; } -inline Result ClientImpl::send_with_content_provider( - const std::string &method, const std::string &path, const Headers &headers, - const char *body, size_t content_length, ContentProvider content_provider, - ContentProviderWithoutLength content_provider_without_length, - const std::string &content_type) { - Request req; - req.method = method; - req.headers = headers; - req.path = path; +inline Result ClientImpl::send_with_content_provider(const std::string &method, + const std::string &path, + const Headers &headers, + const char *body, + size_t content_length, + ContentProvider content_provider, + ContentProviderWithoutLength content_provider_without_length, + const std::string &content_type) { + Request req; + req.method = method; + req.headers = headers; + req.path = path; - auto error = Error::Success; + auto error = Error::Success; - auto res = send_with_content_provider( - req, body, content_length, std::move(content_provider), - std::move(content_provider_without_length), content_type, error); + auto res = send_with_content_provider(req, + body, + content_length, + std::move(content_provider), + std::move(content_provider_without_length), + content_type, + error); - return Result{std::move(res), error, std::move(req.headers)}; + return Result {std::move(res), error, std::move(req.headers)}; } -inline std::string -ClientImpl::adjust_host_string(const std::string &host) const { - if (host.find(':') != std::string::npos) { return "[" + host + "]"; } - return host; +inline std::string ClientImpl::adjust_host_string(const std::string &host) const { + if (host.find(':') != std::string::npos) { + return "[" + host + "]"; + } + return host; } -inline bool ClientImpl::process_request(Stream &strm, Request &req, - Response &res, bool close_connection, - Error &error) { - // Send request - if (!write_request(strm, req, close_connection, error)) { return false; } +inline bool ClientImpl::process_request(Stream &strm, + Request &req, + Response &res, + bool close_connection, + Error &error) { + // Send request + if (!write_request(strm, req, close_connection, error)) { + return false; + } #ifdef CPPHTTPLIB_OPENSSL_SUPPORT - if (is_ssl()) { - auto is_proxy_enabled = !proxy_host_.empty() && proxy_port_ != -1; - if (!is_proxy_enabled) { - char buf[1]; - if (SSL_peek(socket_.ssl, buf, 1) == 0 && - SSL_get_error(socket_.ssl, 0) == SSL_ERROR_ZERO_RETURN) { - error = Error::SSLPeerCouldBeClosed_; - return false; - } + if (is_ssl()) { + auto is_proxy_enabled = !proxy_host_.empty() && proxy_port_ != -1; + if (!is_proxy_enabled) { + char buf[1]; + if (SSL_peek(socket_.ssl, buf, 1) == 0 && SSL_get_error(socket_.ssl, 0) == SSL_ERROR_ZERO_RETURN) { + error = Error::SSLPeerCouldBeClosed_; + return false; + } + } } - } #endif - // Receive response and headers - if (!read_response_line(strm, req, res) || - !detail::read_headers(strm, res.headers)) { - error = Error::Read; - return false; - } - - // Body - if ((res.status != 204) && req.method != "HEAD" && req.method != "CONNECT") { - auto redirect = 300 < res.status && res.status < 400 && follow_location_; - - if (req.response_handler && !redirect) { - if (!req.response_handler(res)) { - error = Error::Canceled; + // Receive response and headers + if (!read_response_line(strm, req, res) || !detail::read_headers(strm, res.headers)) { + error = Error::Read; return false; - } } - auto out = - req.content_receiver - ? static_cast( - [&](const char *buf, size_t n, uint64_t off, uint64_t len) { - if (redirect) { return true; } - auto ret = req.content_receiver(buf, n, off, len); - if (!ret) { error = Error::Canceled; } - return ret; - }) + // Body + if ((res.status != 204) && req.method != "HEAD" && req.method != "CONNECT") { + auto redirect = 300 < res.status && res.status < 400 && follow_location_; + + if (req.response_handler && !redirect) { + if (!req.response_handler(res)) { + error = Error::Canceled; + return false; + } + } + + auto out = req.content_receiver + ? static_cast([&](const char *buf, size_t n, uint64_t off, uint64_t len) { + if (redirect) { + return true; + } + auto ret = req.content_receiver(buf, n, off, len); + if (!ret) { + error = Error::Canceled; + } + return ret; + }) : static_cast( - [&](const char *buf, size_t n, uint64_t /*off*/, - uint64_t /*len*/) { - if (res.body.size() + n > res.body.max_size()) { - return false; - } - res.body.append(buf, n); - return true; + [&](const char *buf, size_t n, uint64_t /*off*/, uint64_t /*len*/) { + if (res.body.size() + n > res.body.max_size()) { + return false; + } + res.body.append(buf, n); + return true; }); - auto progress = [&](uint64_t current, uint64_t total) { - if (!req.progress || redirect) { return true; } - auto ret = req.progress(current, total); - if (!ret) { error = Error::Canceled; } - return ret; - }; + auto progress = [&](uint64_t current, uint64_t total) { + if (!req.progress || redirect) { + return true; + } + auto ret = req.progress(current, total); + if (!ret) { + error = Error::Canceled; + } + return ret; + }; - int dummy_status; - if (!detail::read_content(strm, res, (std::numeric_limits::max)(), - dummy_status, std::move(progress), std::move(out), - decompress_)) { - if (error != Error::Canceled) { error = Error::Read; } - return false; + int dummy_status; + if (!detail::read_content(strm, + res, + (std::numeric_limits::max)(), + dummy_status, + std::move(progress), + std::move(out), + decompress_)) { + if (error != Error::Canceled) { + error = Error::Read; + } + return false; + } } - } - if (res.get_header_value("Connection") == "close" || - (res.version == "HTTP/1.0" && res.reason != "Connection established")) { - // TODO this requires a not-entirely-obvious chain of calls to be correct - // for this to be safe. Maybe a code refactor (such as moving this out to - // the send function and getting rid of the recursiveness of the mutex) - // could make this more obvious. + if (res.get_header_value("Connection") == "close" || + (res.version == "HTTP/1.0" && res.reason != "Connection established")) { + // TODO this requires a not-entirely-obvious chain of calls to be correct + // for this to be safe. Maybe a code refactor (such as moving this out to + // the send function and getting rid of the recursiveness of the mutex) + // could make this more obvious. - // This is safe to call because process_request is only called by - // handle_request which is only called by send, which locks the request - // mutex during the process. It would be a bug to call it from a different - // thread since it's a thread-safety issue to do these things to the socket - // if another thread is using the socket. - std::lock_guard guard(socket_mutex_); - shutdown_ssl(socket_, true); - shutdown_socket(socket_); - close_socket(socket_); - } + // This is safe to call because process_request is only called by + // handle_request which is only called by send, which locks the request + // mutex during the process. It would be a bug to call it from a different + // thread since it's a thread-safety issue to do these things to the socket + // if another thread is using the socket. + std::lock_guard guard(socket_mutex_); + shutdown_ssl(socket_, true); + shutdown_socket(socket_); + close_socket(socket_); + } - // Log - if (logger_) { logger_(req, res); } + // Log + if (logger_) { + logger_(req, res); + } - return true; + return true; } inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider( - const std::string &boundary, const MultipartFormDataItems &items, + const std::string &boundary, + const MultipartFormDataItems &items, const MultipartFormDataProviderItems &provider_items) { - size_t cur_item = 0, cur_start = 0; - // cur_item and cur_start are copied to within the std::function and maintain - // state between successive calls - return [&, cur_item, cur_start](size_t offset, - DataSink &sink) mutable -> bool { - if (!offset && items.size()) { - sink.os << detail::serialize_multipart_formdata(items, boundary, false); - return true; - } else if (cur_item < provider_items.size()) { - if (!cur_start) { - const auto &begin = detail::serialize_multipart_formdata_item_begin( - provider_items[cur_item], boundary); - offset += begin.size(); - cur_start = offset; - sink.os << begin; - } + size_t cur_item = 0, cur_start = 0; + // cur_item and cur_start are copied to within the std::function and maintain + // state between successive calls + return [&, cur_item, cur_start](size_t offset, DataSink &sink) mutable -> bool { + if (!offset && items.size()) { + sink.os << detail::serialize_multipart_formdata(items, boundary, false); + return true; + } else if (cur_item < provider_items.size()) { + if (!cur_start) { + const auto &begin = detail::serialize_multipart_formdata_item_begin(provider_items[cur_item], boundary); + offset += begin.size(); + cur_start = offset; + sink.os << begin; + } - DataSink cur_sink; - bool has_data = true; - cur_sink.write = sink.write; - cur_sink.done = [&]() { has_data = false; }; + DataSink cur_sink; + bool has_data = true; + cur_sink.write = sink.write; + cur_sink.done = [&]() { has_data = false; }; - if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) - return false; + if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) { + return false; + } - if (!has_data) { - sink.os << detail::serialize_multipart_formdata_item_end(); - cur_item++; - cur_start = 0; - } - return true; - } else { - sink.os << detail::serialize_multipart_formdata_finish(boundary); - sink.done(); - return true; - } - }; + if (!has_data) { + sink.os << detail::serialize_multipart_formdata_item_end(); + cur_item++; + cur_start = 0; + } + return true; + } else { + sink.os << detail::serialize_multipart_formdata_finish(boundary); + sink.done(); + return true; + } + }; } -inline bool -ClientImpl::process_socket(const Socket &socket, - std::function callback) { - return detail::process_client_socket( - socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_, - write_timeout_usec_, std::move(callback)); +inline bool ClientImpl::process_socket(const Socket &socket, std::function callback) { + return detail::process_client_socket(socket.sock, + read_timeout_sec_, + read_timeout_usec_, + write_timeout_sec_, + write_timeout_usec_, + std::move(callback)); } -inline bool ClientImpl::is_ssl() const { return false; } +inline bool ClientImpl::is_ssl() const { + return false; +} inline Result ClientImpl::Get(const std::string &path) { - return Get(path, Headers(), Progress()); + return Get(path, Headers(), Progress()); } inline Result ClientImpl::Get(const std::string &path, Progress progress) { - return Get(path, Headers(), std::move(progress)); + return Get(path, Headers(), std::move(progress)); } inline Result ClientImpl::Get(const std::string &path, const Headers &headers) { - return Get(path, headers, Progress()); + return Get(path, headers, Progress()); } -inline Result ClientImpl::Get(const std::string &path, const Headers &headers, - Progress progress) { - Request req; - req.method = "GET"; - req.path = path; - req.headers = headers; - req.progress = std::move(progress); +inline Result ClientImpl::Get(const std::string &path, const Headers &headers, Progress progress) { + Request req; + req.method = "GET"; + req.path = path; + req.headers = headers; + req.progress = std::move(progress); - return send_(std::move(req)); + return send_(std::move(req)); +} + +inline Result ClientImpl::Get(const std::string &path, ContentReceiver content_receiver) { + return Get(path, Headers(), nullptr, std::move(content_receiver), nullptr); +} + +inline Result ClientImpl::Get(const std::string &path, ContentReceiver content_receiver, Progress progress) { + return Get(path, Headers(), nullptr, std::move(content_receiver), std::move(progress)); +} + +inline Result ClientImpl::Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver) { + return Get(path, headers, nullptr, std::move(content_receiver), nullptr); } inline Result ClientImpl::Get(const std::string &path, - ContentReceiver content_receiver) { - return Get(path, Headers(), nullptr, std::move(content_receiver), nullptr); + const Headers &headers, + ContentReceiver content_receiver, + Progress progress) { + return Get(path, headers, nullptr, std::move(content_receiver), std::move(progress)); } inline Result ClientImpl::Get(const std::string &path, - ContentReceiver content_receiver, - Progress progress) { - return Get(path, Headers(), nullptr, std::move(content_receiver), - std::move(progress)); -} - -inline Result ClientImpl::Get(const std::string &path, const Headers &headers, - ContentReceiver content_receiver) { - return Get(path, headers, nullptr, std::move(content_receiver), nullptr); -} - -inline Result ClientImpl::Get(const std::string &path, const Headers &headers, - ContentReceiver content_receiver, - Progress progress) { - return Get(path, headers, nullptr, std::move(content_receiver), - std::move(progress)); + ResponseHandler response_handler, + ContentReceiver content_receiver) { + return Get(path, Headers(), std::move(response_handler), std::move(content_receiver), nullptr); } inline Result ClientImpl::Get(const std::string &path, - ResponseHandler response_handler, - ContentReceiver content_receiver) { - return Get(path, Headers(), std::move(response_handler), - std::move(content_receiver), nullptr); -} - -inline Result ClientImpl::Get(const std::string &path, const Headers &headers, - ResponseHandler response_handler, - ContentReceiver content_receiver) { - return Get(path, headers, std::move(response_handler), - std::move(content_receiver), nullptr); + const Headers &headers, + ResponseHandler response_handler, + ContentReceiver content_receiver) { + return Get(path, headers, std::move(response_handler), std::move(content_receiver), nullptr); } inline Result ClientImpl::Get(const std::string &path, - ResponseHandler response_handler, - ContentReceiver content_receiver, - Progress progress) { - return Get(path, Headers(), std::move(response_handler), - std::move(content_receiver), std::move(progress)); + ResponseHandler response_handler, + ContentReceiver content_receiver, + Progress progress) { + return Get(path, Headers(), std::move(response_handler), std::move(content_receiver), std::move(progress)); } -inline Result ClientImpl::Get(const std::string &path, const Headers &headers, - ResponseHandler response_handler, - ContentReceiver content_receiver, - Progress progress) { - Request req; - req.method = "GET"; - req.path = path; - req.headers = headers; - req.response_handler = std::move(response_handler); - req.content_receiver = - [content_receiver](const char *data, size_t data_length, - uint64_t /*offset*/, uint64_t /*total_length*/) { - return content_receiver(data, data_length); - }; - req.progress = std::move(progress); +inline Result ClientImpl::Get(const std::string &path, + const Headers &headers, + ResponseHandler response_handler, + ContentReceiver content_receiver, + Progress progress) { + Request req; + req.method = "GET"; + req.path = path; + req.headers = headers; + req.response_handler = std::move(response_handler); + req.content_receiver = + [content_receiver](const char *data, size_t data_length, uint64_t /*offset*/, uint64_t /*total_length*/) { + return content_receiver(data, data_length); + }; + req.progress = std::move(progress); - return send_(std::move(req)); + return send_(std::move(req)); } -inline Result ClientImpl::Get(const std::string &path, const Params ¶ms, - const Headers &headers, Progress progress) { - if (params.empty()) { return Get(path, headers); } +inline Result ClientImpl::Get(const std::string &path, + const Params ¶ms, + const Headers &headers, + Progress progress) { + if (params.empty()) { + return Get(path, headers); + } - std::string path_with_query = append_query_params(path, params); - return Get(path_with_query.c_str(), headers, progress); + std::string path_with_query = append_query_params(path, params); + return Get(path_with_query.c_str(), headers, progress); } -inline Result ClientImpl::Get(const std::string &path, const Params ¶ms, - const Headers &headers, - ContentReceiver content_receiver, - Progress progress) { - return Get(path, params, headers, nullptr, content_receiver, progress); +inline Result ClientImpl::Get(const std::string &path, + const Params ¶ms, + const Headers &headers, + ContentReceiver content_receiver, + Progress progress) { + return Get(path, params, headers, nullptr, content_receiver, progress); } -inline Result ClientImpl::Get(const std::string &path, const Params ¶ms, - const Headers &headers, - ResponseHandler response_handler, - ContentReceiver content_receiver, - Progress progress) { - if (params.empty()) { - return Get(path, headers, response_handler, content_receiver, progress); - } +inline Result ClientImpl::Get(const std::string &path, + const Params ¶ms, + const Headers &headers, + ResponseHandler response_handler, + ContentReceiver content_receiver, + Progress progress) { + if (params.empty()) { + return Get(path, headers, response_handler, content_receiver, progress); + } - std::string path_with_query = append_query_params(path, params); - return Get(path_with_query.c_str(), headers, response_handler, - content_receiver, progress); + std::string path_with_query = append_query_params(path, params); + return Get(path_with_query.c_str(), headers, response_handler, content_receiver, progress); } inline Result ClientImpl::Head(const std::string &path) { - return Head(path, Headers()); + return Head(path, Headers()); } -inline Result ClientImpl::Head(const std::string &path, - const Headers &headers) { - Request req; - req.method = "HEAD"; - req.headers = headers; - req.path = path; +inline Result ClientImpl::Head(const std::string &path, const Headers &headers) { + Request req; + req.method = "HEAD"; + req.headers = headers; + req.path = path; - return send_(std::move(req)); + return send_(std::move(req)); } inline Result ClientImpl::Post(const std::string &path) { - return Post(path, std::string(), std::string()); + return Post(path, std::string(), std::string()); +} + +inline Result ClientImpl::Post(const std::string &path, const Headers &headers) { + return Post(path, headers, nullptr, 0, std::string()); } inline Result ClientImpl::Post(const std::string &path, - const Headers &headers) { - return Post(path, headers, nullptr, 0, std::string()); -} - -inline Result ClientImpl::Post(const std::string &path, const char *body, - size_t content_length, + const char *body, + size_t content_length, const std::string &content_type) { - return Post(path, Headers(), body, content_length, content_type); + return Post(path, Headers(), body, content_length, content_type); } -inline Result ClientImpl::Post(const std::string &path, const Headers &headers, - const char *body, size_t content_length, +inline Result ClientImpl::Post(const std::string &path, + const Headers &headers, + const char *body, + size_t content_length, const std::string &content_type) { - return send_with_content_provider("POST", path, headers, body, content_length, - nullptr, nullptr, content_type); + return send_with_content_provider("POST", path, headers, body, content_length, nullptr, nullptr, content_type); } -inline Result ClientImpl::Post(const std::string &path, const std::string &body, - const std::string &content_type) { - return Post(path, Headers(), body, content_type); +inline Result ClientImpl::Post(const std::string &path, const std::string &body, const std::string &content_type) { + return Post(path, Headers(), body, content_type); } -inline Result ClientImpl::Post(const std::string &path, const Headers &headers, +inline Result ClientImpl::Post(const std::string &path, + const Headers &headers, const std::string &body, const std::string &content_type) { - return send_with_content_provider("POST", path, headers, body.data(), - body.size(), nullptr, nullptr, - content_type); + return send_with_content_provider("POST", path, headers, body.data(), body.size(), nullptr, nullptr, content_type); } inline Result ClientImpl::Post(const std::string &path, const Params ¶ms) { - return Post(path, Headers(), params); -} - -inline Result ClientImpl::Post(const std::string &path, size_t content_length, - ContentProvider content_provider, - const std::string &content_type) { - return Post(path, Headers(), content_length, std::move(content_provider), - content_type); + return Post(path, Headers(), params); } inline Result ClientImpl::Post(const std::string &path, + size_t content_length, + ContentProvider content_provider, + const std::string &content_type) { + return Post(path, Headers(), content_length, std::move(content_provider), content_type); +} + +inline Result ClientImpl::Post(const std::string &path, ContentProviderWithoutLength content_provider, - const std::string &content_type) { - return Post(path, Headers(), std::move(content_provider), content_type); -} - -inline Result ClientImpl::Post(const std::string &path, const Headers &headers, - size_t content_length, - ContentProvider content_provider, - const std::string &content_type) { - return send_with_content_provider("POST", path, headers, nullptr, - content_length, std::move(content_provider), - nullptr, content_type); -} - -inline Result ClientImpl::Post(const std::string &path, const Headers &headers, - ContentProviderWithoutLength content_provider, - const std::string &content_type) { - return send_with_content_provider("POST", path, headers, nullptr, 0, nullptr, - std::move(content_provider), content_type); -} - -inline Result ClientImpl::Post(const std::string &path, const Headers &headers, - const Params ¶ms) { - auto query = detail::params_to_query_str(params); - return Post(path, headers, query, "application/x-www-form-urlencoded"); + const std::string &content_type) { + return Post(path, Headers(), std::move(content_provider), content_type); } inline Result ClientImpl::Post(const std::string &path, - const MultipartFormDataItems &items) { - return Post(path, Headers(), items); + const Headers &headers, + size_t content_length, + ContentProvider content_provider, + const std::string &content_type) { + return send_with_content_provider("POST", + path, + headers, + nullptr, + content_length, + std::move(content_provider), + nullptr, + content_type); } -inline Result ClientImpl::Post(const std::string &path, const Headers &headers, - const MultipartFormDataItems &items) { - const auto &boundary = detail::make_multipart_data_boundary(); - const auto &content_type = - detail::serialize_multipart_formdata_get_content_type(boundary); - const auto &body = detail::serialize_multipart_formdata(items, boundary); - return Post(path, headers, body, content_type.c_str()); +inline Result ClientImpl::Post(const std::string &path, + const Headers &headers, + ContentProviderWithoutLength content_provider, + const std::string &content_type) { + return send_with_content_provider("POST", + path, + headers, + nullptr, + 0, + nullptr, + std::move(content_provider), + content_type); } -inline Result ClientImpl::Post(const std::string &path, const Headers &headers, +inline Result ClientImpl::Post(const std::string &path, const Headers &headers, const Params ¶ms) { + auto query = detail::params_to_query_str(params); + return Post(path, headers, query, "application/x-www-form-urlencoded"); +} + +inline Result ClientImpl::Post(const std::string &path, const MultipartFormDataItems &items) { + return Post(path, Headers(), items); +} + +inline Result ClientImpl::Post(const std::string &path, const Headers &headers, const MultipartFormDataItems &items) { + const auto &boundary = detail::make_multipart_data_boundary(); + const auto &content_type = detail::serialize_multipart_formdata_get_content_type(boundary); + const auto &body = detail::serialize_multipart_formdata(items, boundary); + return Post(path, headers, body, content_type.c_str()); +} + +inline Result ClientImpl::Post(const std::string &path, + const Headers &headers, const MultipartFormDataItems &items, - const std::string &boundary) { - if (!detail::is_multipart_boundary_chars_valid(boundary)) { - return Result{nullptr, Error::UnsupportedMultipartBoundaryChars}; - } + const std::string &boundary) { + if (!detail::is_multipart_boundary_chars_valid(boundary)) { + return Result {nullptr, Error::UnsupportedMultipartBoundaryChars}; + } - const auto &content_type = - detail::serialize_multipart_formdata_get_content_type(boundary); - const auto &body = detail::serialize_multipart_formdata(items, boundary); - return Post(path, headers, body, content_type.c_str()); + const auto &content_type = detail::serialize_multipart_formdata_get_content_type(boundary); + const auto &body = detail::serialize_multipart_formdata(items, boundary); + return Post(path, headers, body, content_type.c_str()); } -inline Result -ClientImpl::Post(const std::string &path, const Headers &headers, - const MultipartFormDataItems &items, - const MultipartFormDataProviderItems &provider_items) { - const auto &boundary = detail::make_multipart_data_boundary(); - const auto &content_type = - detail::serialize_multipart_formdata_get_content_type(boundary); - return send_with_content_provider( - "POST", path, headers, nullptr, 0, nullptr, - get_multipart_content_provider(boundary, items, provider_items), - content_type); +inline Result ClientImpl::Post(const std::string &path, + const Headers &headers, + const MultipartFormDataItems &items, + const MultipartFormDataProviderItems &provider_items) { + const auto &boundary = detail::make_multipart_data_boundary(); + const auto &content_type = detail::serialize_multipart_formdata_get_content_type(boundary); + return send_with_content_provider("POST", + path, + headers, + nullptr, + 0, + nullptr, + get_multipart_content_provider(boundary, items, provider_items), + content_type); } inline Result ClientImpl::Put(const std::string &path) { - return Put(path, std::string(), std::string()); -} - -inline Result ClientImpl::Put(const std::string &path, const char *body, - size_t content_length, - const std::string &content_type) { - return Put(path, Headers(), body, content_length, content_type); -} - -inline Result ClientImpl::Put(const std::string &path, const Headers &headers, - const char *body, size_t content_length, - const std::string &content_type) { - return send_with_content_provider("PUT", path, headers, body, content_length, - nullptr, nullptr, content_type); -} - -inline Result ClientImpl::Put(const std::string &path, const std::string &body, - const std::string &content_type) { - return Put(path, Headers(), body, content_type); -} - -inline Result ClientImpl::Put(const std::string &path, const Headers &headers, - const std::string &body, - const std::string &content_type) { - return send_with_content_provider("PUT", path, headers, body.data(), - body.size(), nullptr, nullptr, - content_type); -} - -inline Result ClientImpl::Put(const std::string &path, size_t content_length, - ContentProvider content_provider, - const std::string &content_type) { - return Put(path, Headers(), content_length, std::move(content_provider), - content_type); + return Put(path, std::string(), std::string()); } inline Result ClientImpl::Put(const std::string &path, - ContentProviderWithoutLength content_provider, + const char *body, + size_t content_length, const std::string &content_type) { - return Put(path, Headers(), std::move(content_provider), content_type); + return Put(path, Headers(), body, content_length, content_type); } -inline Result ClientImpl::Put(const std::string &path, const Headers &headers, - size_t content_length, - ContentProvider content_provider, +inline Result ClientImpl::Put(const std::string &path, + const Headers &headers, + const char *body, + size_t content_length, const std::string &content_type) { - return send_with_content_provider("PUT", path, headers, nullptr, - content_length, std::move(content_provider), - nullptr, content_type); + return send_with_content_provider("PUT", path, headers, body, content_length, nullptr, nullptr, content_type); } -inline Result ClientImpl::Put(const std::string &path, const Headers &headers, - ContentProviderWithoutLength content_provider, +inline Result ClientImpl::Put(const std::string &path, const std::string &body, const std::string &content_type) { + return Put(path, Headers(), body, content_type); +} + +inline Result ClientImpl::Put(const std::string &path, + const Headers &headers, + const std::string &body, const std::string &content_type) { - return send_with_content_provider("PUT", path, headers, nullptr, 0, nullptr, - std::move(content_provider), content_type); + return send_with_content_provider("PUT", path, headers, body.data(), body.size(), nullptr, nullptr, content_type); +} + +inline Result ClientImpl::Put(const std::string &path, + size_t content_length, + ContentProvider content_provider, + const std::string &content_type) { + return Put(path, Headers(), content_length, std::move(content_provider), content_type); +} + +inline Result ClientImpl::Put(const std::string &path, + ContentProviderWithoutLength content_provider, + const std::string &content_type) { + return Put(path, Headers(), std::move(content_provider), content_type); +} + +inline Result ClientImpl::Put(const std::string &path, + const Headers &headers, + size_t content_length, + ContentProvider content_provider, + const std::string &content_type) { + return send_with_content_provider("PUT", + path, + headers, + nullptr, + content_length, + std::move(content_provider), + nullptr, + content_type); +} + +inline Result ClientImpl::Put(const std::string &path, + const Headers &headers, + ContentProviderWithoutLength content_provider, + const std::string &content_type) { + return send_with_content_provider("PUT", + path, + headers, + nullptr, + 0, + nullptr, + std::move(content_provider), + content_type); } inline Result ClientImpl::Put(const std::string &path, const Params ¶ms) { - return Put(path, Headers(), params); + return Put(path, Headers(), params); } -inline Result ClientImpl::Put(const std::string &path, const Headers &headers, - const Params ¶ms) { - auto query = detail::params_to_query_str(params); - return Put(path, headers, query, "application/x-www-form-urlencoded"); +inline Result ClientImpl::Put(const std::string &path, const Headers &headers, const Params ¶ms) { + auto query = detail::params_to_query_str(params); + return Put(path, headers, query, "application/x-www-form-urlencoded"); } -inline Result ClientImpl::Put(const std::string &path, - const MultipartFormDataItems &items) { - return Put(path, Headers(), items); +inline Result ClientImpl::Put(const std::string &path, const MultipartFormDataItems &items) { + return Put(path, Headers(), items); } -inline Result ClientImpl::Put(const std::string &path, const Headers &headers, - const MultipartFormDataItems &items) { - const auto &boundary = detail::make_multipart_data_boundary(); - const auto &content_type = - detail::serialize_multipart_formdata_get_content_type(boundary); - const auto &body = detail::serialize_multipart_formdata(items, boundary); - return Put(path, headers, body, content_type); +inline Result ClientImpl::Put(const std::string &path, const Headers &headers, const MultipartFormDataItems &items) { + const auto &boundary = detail::make_multipart_data_boundary(); + const auto &content_type = detail::serialize_multipart_formdata_get_content_type(boundary); + const auto &body = detail::serialize_multipart_formdata(items, boundary); + return Put(path, headers, body, content_type); } -inline Result ClientImpl::Put(const std::string &path, const Headers &headers, +inline Result ClientImpl::Put(const std::string &path, + const Headers &headers, const MultipartFormDataItems &items, - const std::string &boundary) { - if (!detail::is_multipart_boundary_chars_valid(boundary)) { - return Result{nullptr, Error::UnsupportedMultipartBoundaryChars}; - } + const std::string &boundary) { + if (!detail::is_multipart_boundary_chars_valid(boundary)) { + return Result {nullptr, Error::UnsupportedMultipartBoundaryChars}; + } - const auto &content_type = - detail::serialize_multipart_formdata_get_content_type(boundary); - const auto &body = detail::serialize_multipart_formdata(items, boundary); - return Put(path, headers, body, content_type); + const auto &content_type = detail::serialize_multipart_formdata_get_content_type(boundary); + const auto &body = detail::serialize_multipart_formdata(items, boundary); + return Put(path, headers, body, content_type); } -inline Result -ClientImpl::Put(const std::string &path, const Headers &headers, - const MultipartFormDataItems &items, - const MultipartFormDataProviderItems &provider_items) { - const auto &boundary = detail::make_multipart_data_boundary(); - const auto &content_type = - detail::serialize_multipart_formdata_get_content_type(boundary); - return send_with_content_provider( - "PUT", path, headers, nullptr, 0, nullptr, - get_multipart_content_provider(boundary, items, provider_items), - content_type); +inline Result ClientImpl::Put(const std::string &path, + const Headers &headers, + const MultipartFormDataItems &items, + const MultipartFormDataProviderItems &provider_items) { + const auto &boundary = detail::make_multipart_data_boundary(); + const auto &content_type = detail::serialize_multipart_formdata_get_content_type(boundary); + return send_with_content_provider("PUT", + path, + headers, + nullptr, + 0, + nullptr, + get_multipart_content_provider(boundary, items, provider_items), + content_type); } + inline Result ClientImpl::Patch(const std::string &path) { - return Patch(path, std::string(), std::string()); -} - -inline Result ClientImpl::Patch(const std::string &path, const char *body, - size_t content_length, - const std::string &content_type) { - return Patch(path, Headers(), body, content_length, content_type); -} - -inline Result ClientImpl::Patch(const std::string &path, const Headers &headers, - const char *body, size_t content_length, - const std::string &content_type) { - return send_with_content_provider("PATCH", path, headers, body, - content_length, nullptr, nullptr, - content_type); + return Patch(path, std::string(), std::string()); } inline Result ClientImpl::Patch(const std::string &path, - const std::string &body, + const char *body, + size_t content_length, const std::string &content_type) { - return Patch(path, Headers(), body, content_type); -} - -inline Result ClientImpl::Patch(const std::string &path, const Headers &headers, - const std::string &body, - const std::string &content_type) { - return send_with_content_provider("PATCH", path, headers, body.data(), - body.size(), nullptr, nullptr, - content_type); -} - -inline Result ClientImpl::Patch(const std::string &path, size_t content_length, - ContentProvider content_provider, - const std::string &content_type) { - return Patch(path, Headers(), content_length, std::move(content_provider), - content_type); + return Patch(path, Headers(), body, content_length, content_type); } inline Result ClientImpl::Patch(const std::string &path, - ContentProviderWithoutLength content_provider, + const Headers &headers, + const char *body, + size_t content_length, const std::string &content_type) { - return Patch(path, Headers(), std::move(content_provider), content_type); + return send_with_content_provider("PATCH", path, headers, body, content_length, nullptr, nullptr, content_type); } -inline Result ClientImpl::Patch(const std::string &path, const Headers &headers, - size_t content_length, - ContentProvider content_provider, - const std::string &content_type) { - return send_with_content_provider("PATCH", path, headers, nullptr, - content_length, std::move(content_provider), - nullptr, content_type); +inline Result ClientImpl::Patch(const std::string &path, const std::string &body, const std::string &content_type) { + return Patch(path, Headers(), body, content_type); } -inline Result ClientImpl::Patch(const std::string &path, const Headers &headers, - ContentProviderWithoutLength content_provider, +inline Result ClientImpl::Patch(const std::string &path, + const Headers &headers, + const std::string &body, const std::string &content_type) { - return send_with_content_provider("PATCH", path, headers, nullptr, 0, nullptr, - std::move(content_provider), content_type); + return send_with_content_provider("PATCH", path, headers, body.data(), body.size(), nullptr, nullptr, content_type); +} + +inline Result ClientImpl::Patch(const std::string &path, + size_t content_length, + ContentProvider content_provider, + const std::string &content_type) { + return Patch(path, Headers(), content_length, std::move(content_provider), content_type); +} + +inline Result ClientImpl::Patch(const std::string &path, + ContentProviderWithoutLength content_provider, + const std::string &content_type) { + return Patch(path, Headers(), std::move(content_provider), content_type); +} + +inline Result ClientImpl::Patch(const std::string &path, + const Headers &headers, + size_t content_length, + ContentProvider content_provider, + const std::string &content_type) { + return send_with_content_provider("PATCH", + path, + headers, + nullptr, + content_length, + std::move(content_provider), + nullptr, + content_type); +} + +inline Result ClientImpl::Patch(const std::string &path, + const Headers &headers, + ContentProviderWithoutLength content_provider, + const std::string &content_type) { + return send_with_content_provider("PATCH", + path, + headers, + nullptr, + 0, + nullptr, + std::move(content_provider), + content_type); } inline Result ClientImpl::Delete(const std::string &path) { - return Delete(path, Headers(), std::string(), std::string()); + return Delete(path, Headers(), std::string(), std::string()); +} + +inline Result ClientImpl::Delete(const std::string &path, const Headers &headers) { + return Delete(path, headers, std::string(), std::string()); } inline Result ClientImpl::Delete(const std::string &path, - const Headers &headers) { - return Delete(path, headers, std::string(), std::string()); -} - -inline Result ClientImpl::Delete(const std::string &path, const char *body, - size_t content_length, + const char *body, + size_t content_length, const std::string &content_type) { - return Delete(path, Headers(), body, content_length, content_type); + return Delete(path, Headers(), body, content_length, content_type); } inline Result ClientImpl::Delete(const std::string &path, - const Headers &headers, const char *body, - size_t content_length, + const Headers &headers, + const char *body, + size_t content_length, const std::string &content_type) { - Request req; - req.method = "DELETE"; - req.headers = headers; - req.path = path; + Request req; + req.method = "DELETE"; + req.headers = headers; + req.path = path; - if (!content_type.empty()) { req.set_header("Content-Type", content_type); } - req.body.assign(body, content_length); + if (!content_type.empty()) { + req.set_header("Content-Type", content_type); + } + req.body.assign(body, content_length); - return send_(std::move(req)); + return send_(std::move(req)); +} + +inline Result ClientImpl::Delete(const std::string &path, const std::string &body, const std::string &content_type) { + return Delete(path, Headers(), body.data(), body.size(), content_type); } inline Result ClientImpl::Delete(const std::string &path, + const Headers &headers, const std::string &body, const std::string &content_type) { - return Delete(path, Headers(), body.data(), body.size(), content_type); -} - -inline Result ClientImpl::Delete(const std::string &path, - const Headers &headers, - const std::string &body, - const std::string &content_type) { - return Delete(path, headers, body.data(), body.size(), content_type); + return Delete(path, headers, body.data(), body.size(), content_type); } inline Result ClientImpl::Options(const std::string &path) { - return Options(path, Headers()); + return Options(path, Headers()); } -inline Result ClientImpl::Options(const std::string &path, - const Headers &headers) { - Request req; - req.method = "OPTIONS"; - req.headers = headers; - req.path = path; +inline Result ClientImpl::Options(const std::string &path, const Headers &headers) { + Request req; + req.method = "OPTIONS"; + req.headers = headers; + req.path = path; - return send_(std::move(req)); + return send_(std::move(req)); } inline void ClientImpl::stop() { - std::lock_guard guard(socket_mutex_); + std::lock_guard guard(socket_mutex_); - // If there is anything ongoing right now, the ONLY thread-safe thing we can - // do is to shutdown_socket, so that threads using this socket suddenly - // discover they can't read/write any more and error out. Everything else - // (closing the socket, shutting ssl down) is unsafe because these actions are - // not thread-safe. - if (socket_requests_in_flight_ > 0) { + // If there is anything ongoing right now, the ONLY thread-safe thing we can + // do is to shutdown_socket, so that threads using this socket suddenly + // discover they can't read/write any more and error out. Everything else + // (closing the socket, shutting ssl down) is unsafe because these actions are + // not thread-safe. + if (socket_requests_in_flight_ > 0) { + shutdown_socket(socket_); + + // Aside from that, we set a flag for the socket to be closed when we're + // done. + socket_should_be_closed_when_request_is_done_ = true; + return; + } + + // Otherwise, still holding the mutex, we can shut everything down ourselves + shutdown_ssl(socket_, true); shutdown_socket(socket_); - - // Aside from that, we set a flag for the socket to be closed when we're - // done. - socket_should_be_closed_when_request_is_done_ = true; - return; - } - - // Otherwise, still holding the mutex, we can shut everything down ourselves - shutdown_ssl(socket_, true); - shutdown_socket(socket_); - close_socket(socket_); + close_socket(socket_); } -inline std::string ClientImpl::host() const { return host_; } +inline std::string ClientImpl::host() const { + return host_; +} -inline int ClientImpl::port() const { return port_; } +inline int ClientImpl::port() const { + return port_; +} inline size_t ClientImpl::is_socket_open() const { - std::lock_guard guard(socket_mutex_); - return socket_.is_open(); + std::lock_guard guard(socket_mutex_); + return socket_.is_open(); } -inline socket_t ClientImpl::socket() const { return socket_.sock; } +inline socket_t ClientImpl::socket() const { + return socket_.sock; +} inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) { - connection_timeout_sec_ = sec; - connection_timeout_usec_ = usec; + connection_timeout_sec_ = sec; + connection_timeout_usec_ = usec; } inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) { - read_timeout_sec_ = sec; - read_timeout_usec_ = usec; + read_timeout_sec_ = sec; + read_timeout_usec_ = usec; } inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) { - write_timeout_sec_ = sec; - write_timeout_usec_ = usec; + write_timeout_sec_ = sec; + write_timeout_usec_ = usec; } -inline void ClientImpl::set_basic_auth(const std::string &username, - const std::string &password) { - basic_auth_username_ = username; - basic_auth_password_ = password; +inline void ClientImpl::set_basic_auth(const std::string &username, const std::string &password) { + basic_auth_username_ = username; + basic_auth_password_ = password; } inline void ClientImpl::set_bearer_token_auth(const std::string &token) { - bearer_token_auth_token_ = token; + bearer_token_auth_token_ = token; } #ifdef CPPHTTPLIB_OPENSSL_SUPPORT -inline void ClientImpl::set_digest_auth(const std::string &username, - const std::string &password) { - digest_auth_username_ = username; - digest_auth_password_ = password; +inline void ClientImpl::set_digest_auth(const std::string &username, const std::string &password) { + digest_auth_username_ = username; + digest_auth_password_ = password; } #endif -inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; } +inline void ClientImpl::set_keep_alive(bool on) { + keep_alive_ = on; +} -inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; } +inline void ClientImpl::set_follow_location(bool on) { + follow_location_ = on; +} -inline void ClientImpl::set_url_encode(bool on) { url_encode_ = on; } +inline void ClientImpl::set_url_encode(bool on) { + url_encode_ = on; +} -inline void -ClientImpl::set_hostname_addr_map(std::map addr_map) { - addr_map_ = std::move(addr_map); +inline void ClientImpl::set_hostname_addr_map(std::map addr_map) { + addr_map_ = std::move(addr_map); } inline void ClientImpl::set_default_headers(Headers headers) { - default_headers_ = std::move(headers); + default_headers_ = std::move(headers); } inline void ClientImpl::set_address_family(int family) { - address_family_ = family; + address_family_ = family; } -inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; } +inline void ClientImpl::set_tcp_nodelay(bool on) { + tcp_nodelay_ = on; +} inline void ClientImpl::set_socket_options(SocketOptions socket_options) { - socket_options_ = std::move(socket_options); + socket_options_ = std::move(socket_options); } -inline void ClientImpl::set_compress(bool on) { compress_ = on; } +inline void ClientImpl::set_compress(bool on) { + compress_ = on; +} -inline void ClientImpl::set_decompress(bool on) { decompress_ = on; } +inline void ClientImpl::set_decompress(bool on) { + decompress_ = on; +} inline void ClientImpl::set_interface(const std::string &intf) { - interface_ = intf; + interface_ = intf; } inline void ClientImpl::set_proxy(const std::string &host, int port) { - proxy_host_ = host; - proxy_port_ = port; + proxy_host_ = host; + proxy_port_ = port; } -inline void ClientImpl::set_proxy_basic_auth(const std::string &username, - const std::string &password) { - proxy_basic_auth_username_ = username; - proxy_basic_auth_password_ = password; +inline void ClientImpl::set_post_connect_callback(detail::POSTSOCKETCONNECTCB cb) { + _postConnCb = cb; +} + +inline void ClientImpl::set_proxy_basic_auth(const std::string &username, const std::string &password) { + proxy_basic_auth_username_ = username; + proxy_basic_auth_password_ = password; } inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) { - proxy_bearer_token_auth_token_ = token; + proxy_bearer_token_auth_token_ = token; } #ifdef CPPHTTPLIB_OPENSSL_SUPPORT -inline void ClientImpl::set_proxy_digest_auth(const std::string &username, - const std::string &password) { - proxy_digest_auth_username_ = username; - proxy_digest_auth_password_ = password; +inline void ClientImpl::set_proxy_digest_auth(const std::string &username, const std::string &password) { + proxy_digest_auth_username_ = username; + proxy_digest_auth_password_ = password; } -inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path, - const std::string &ca_cert_dir_path) { - ca_cert_file_path_ = ca_cert_file_path; - ca_cert_dir_path_ = ca_cert_dir_path; +inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path, const std::string &ca_cert_dir_path) { + ca_cert_file_path_ = ca_cert_file_path; + ca_cert_dir_path_ = ca_cert_dir_path; } inline void ClientImpl::set_ca_cert_store(X509_STORE *ca_cert_store) { - if (ca_cert_store && ca_cert_store != ca_cert_store_) { - ca_cert_store_ = ca_cert_store; - } + if (ca_cert_store && ca_cert_store != ca_cert_store_) { + ca_cert_store_ = ca_cert_store; + } } -inline X509_STORE *ClientImpl::create_ca_cert_store(const char *ca_cert, - std::size_t size) { - auto mem = BIO_new_mem_buf(ca_cert, static_cast(size)); - if (!mem) return nullptr; - - auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr); - if (!inf) { - BIO_free_all(mem); - return nullptr; - } - - auto cts = X509_STORE_new(); - if (cts) { - for (auto i = 0; i < static_cast(sk_X509_INFO_num(inf)); i++) { - auto itmp = sk_X509_INFO_value(inf, i); - if (!itmp) { continue; } - - if (itmp->x509) { X509_STORE_add_cert(cts, itmp->x509); } - if (itmp->crl) { X509_STORE_add_crl(cts, itmp->crl); } +inline X509_STORE *ClientImpl::create_ca_cert_store(const char *ca_cert, std::size_t size) { + auto mem = BIO_new_mem_buf(ca_cert, static_cast(size)); + if (!mem) { + return nullptr; } - } - sk_X509_INFO_pop_free(inf, X509_INFO_free); - BIO_free_all(mem); - return cts; + auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr); + if (!inf) { + BIO_free_all(mem); + return nullptr; + } + + auto cts = X509_STORE_new(); + if (cts) { + for (auto i = 0; i < static_cast(sk_X509_INFO_num(inf)); i++) { + auto itmp = sk_X509_INFO_value(inf, i); + if (!itmp) { + continue; + } + + if (itmp->x509) { + X509_STORE_add_cert(cts, itmp->x509); + } + if (itmp->crl) { + X509_STORE_add_crl(cts, itmp->crl); + } + } + } + + sk_X509_INFO_pop_free(inf, X509_INFO_free); + BIO_free_all(mem); + return cts; } inline void ClientImpl::enable_server_certificate_verification(bool enabled) { - server_certificate_verification_ = enabled; + server_certificate_verification_ = enabled; } #endif inline void ClientImpl::set_logger(Logger logger) { - logger_ = std::move(logger); + logger_ = std::move(logger); } /* @@ -7841,587 +8395,623 @@ inline void ClientImpl::set_logger(Logger logger) { #ifdef CPPHTTPLIB_OPENSSL_SUPPORT namespace detail { -template -inline SSL *ssl_new(socket_t sock, SSL_CTX *ctx, std::mutex &ctx_mutex, - U SSL_connect_or_accept, V setup) { - SSL *ssl = nullptr; - { - std::lock_guard guard(ctx_mutex); - ssl = SSL_new(ctx); - } - - if (ssl) { - set_nonblocking(sock, true); - auto bio = BIO_new_socket(static_cast(sock), BIO_NOCLOSE); - BIO_set_nbio(bio, 1); - SSL_set_bio(ssl, bio, bio); - - if (!setup(ssl) || SSL_connect_or_accept(ssl) != 1) { - SSL_shutdown(ssl); - { +template +inline SSL *ssl_new(socket_t sock, SSL_CTX *ctx, std::mutex &ctx_mutex, U SSL_connect_or_accept, V setup) { + SSL *ssl = nullptr; + { std::lock_guard guard(ctx_mutex); - SSL_free(ssl); - } - set_nonblocking(sock, false); - return nullptr; + ssl = SSL_new(ctx); } - BIO_set_nbio(bio, 0); - set_nonblocking(sock, false); - } - return ssl; -} + if (ssl) { + set_nonblocking(sock, true); + auto bio = BIO_new_socket(static_cast(sock), BIO_NOCLOSE); + BIO_set_nbio(bio, 1); + SSL_set_bio(ssl, bio, bio); -inline void ssl_delete(std::mutex &ctx_mutex, SSL *ssl, - bool shutdown_gracefully) { - // sometimes we may want to skip this to try to avoid SIGPIPE if we know - // the remote has closed the network connection - // Note that it is not always possible to avoid SIGPIPE, this is merely a - // best-efforts. - if (shutdown_gracefully) { SSL_shutdown(ssl); } - - std::lock_guard guard(ctx_mutex); - SSL_free(ssl); -} - -template -bool ssl_connect_or_accept_nonblocking(socket_t sock, SSL *ssl, - U ssl_connect_or_accept, - time_t timeout_sec, - time_t timeout_usec) { - auto res = 0; - while ((res = ssl_connect_or_accept(ssl)) != 1) { - auto err = SSL_get_error(ssl, res); - switch (err) { - case SSL_ERROR_WANT_READ: - if (select_read(sock, timeout_sec, timeout_usec) > 0) { continue; } - break; - case SSL_ERROR_WANT_WRITE: - if (select_write(sock, timeout_sec, timeout_usec) > 0) { continue; } - break; - default: break; + if (!setup(ssl) || SSL_connect_or_accept(ssl) != 1) { + SSL_shutdown(ssl); + { + std::lock_guard guard(ctx_mutex); + SSL_free(ssl); + } + set_nonblocking(sock, false); + return nullptr; + } + BIO_set_nbio(bio, 0); + set_nonblocking(sock, false); } - return false; - } - return true; + + return ssl; } -template -inline bool process_server_socket_ssl( - const std::atomic &svr_sock, SSL *ssl, socket_t sock, - size_t keep_alive_max_count, time_t keep_alive_timeout_sec, - time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec, - time_t write_timeout_usec, T callback) { - return process_server_socket_core( - svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec, - [&](bool close_connection, bool &connection_closed) { - SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec, - write_timeout_sec, write_timeout_usec); - return callback(strm, close_connection, connection_closed); - }); +inline void ssl_delete(std::mutex &ctx_mutex, SSL *ssl, bool shutdown_gracefully) { + // sometimes we may want to skip this to try to avoid SIGPIPE if we know + // the remote has closed the network connection + // Note that it is not always possible to avoid SIGPIPE, this is merely a + // best-efforts. + if (shutdown_gracefully) { + SSL_shutdown(ssl); + } + + std::lock_guard guard(ctx_mutex); + SSL_free(ssl); } -template -inline bool -process_client_socket_ssl(SSL *ssl, socket_t sock, time_t read_timeout_sec, - time_t read_timeout_usec, time_t write_timeout_sec, - time_t write_timeout_usec, T callback) { - SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec, - write_timeout_sec, write_timeout_usec); - return callback(strm); +template +bool ssl_connect_or_accept_nonblocking(socket_t sock, + SSL *ssl, + U ssl_connect_or_accept, + time_t timeout_sec, + time_t timeout_usec) { + auto res = 0; + while ((res = ssl_connect_or_accept(ssl)) != 1) { + auto err = SSL_get_error(ssl, res); + switch (err) { + case SSL_ERROR_WANT_READ: + if (select_read(sock, timeout_sec, timeout_usec) > 0) { + continue; + } + break; + case SSL_ERROR_WANT_WRITE: + if (select_write(sock, timeout_sec, timeout_usec) > 0) { + continue; + } + break; + default: + break; + } + return false; + } + return true; +} + +template +inline bool process_server_socket_ssl(const std::atomic &svr_sock, + SSL *ssl, + socket_t sock, + size_t keep_alive_max_count, + time_t keep_alive_timeout_sec, + time_t read_timeout_sec, + time_t read_timeout_usec, + time_t write_timeout_sec, + time_t write_timeout_usec, + T callback) { + return process_server_socket_core( + svr_sock, + sock, + keep_alive_max_count, + keep_alive_timeout_sec, + [&](bool close_connection, bool &connection_closed) { + SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec, write_timeout_sec, write_timeout_usec); + return callback(strm, close_connection, connection_closed); + }); +} + +template +inline bool process_client_socket_ssl(SSL *ssl, + socket_t sock, + time_t read_timeout_sec, + time_t read_timeout_usec, + time_t write_timeout_sec, + time_t write_timeout_usec, + T callback) { + SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec, write_timeout_sec, write_timeout_usec); + return callback(strm); } class SSLInit { public: - SSLInit() { - OPENSSL_init_ssl( - OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL); - } + SSLInit() { + OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL); + } }; // SSL socket stream implementation -inline SSLSocketStream::SSLSocketStream(socket_t sock, SSL *ssl, - time_t read_timeout_sec, - time_t read_timeout_usec, - time_t write_timeout_sec, - time_t write_timeout_usec) - : sock_(sock), ssl_(ssl), read_timeout_sec_(read_timeout_sec), +inline SSLSocketStream::SSLSocketStream(socket_t sock, + SSL *ssl, + time_t read_timeout_sec, + time_t read_timeout_usec, + time_t write_timeout_sec, + time_t write_timeout_usec) + : sock_(sock), + ssl_(ssl), + read_timeout_sec_(read_timeout_sec), read_timeout_usec_(read_timeout_usec), write_timeout_sec_(write_timeout_sec), write_timeout_usec_(write_timeout_usec) { - SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY); + SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY); } -inline SSLSocketStream::~SSLSocketStream() {} +inline SSLSocketStream::~SSLSocketStream() { +} inline bool SSLSocketStream::is_readable() const { - return detail::select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0; + return detail::select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0; } inline bool SSLSocketStream::is_writable() const { - return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 && - is_socket_alive(sock_); + return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 && is_socket_alive(sock_); } inline ssize_t SSLSocketStream::read(char *ptr, size_t size) { - if (SSL_pending(ssl_) > 0) { - return SSL_read(ssl_, ptr, static_cast(size)); - } else if (is_readable()) { - auto ret = SSL_read(ssl_, ptr, static_cast(size)); - if (ret < 0) { - auto err = SSL_get_error(ssl_, ret); - auto n = 1000; + if (SSL_pending(ssl_) > 0) { + return SSL_read(ssl_, ptr, static_cast(size)); + } else if (is_readable()) { + auto ret = SSL_read(ssl_, ptr, static_cast(size)); + if (ret < 0) { + auto err = SSL_get_error(ssl_, ret); + auto n = 1000; #ifdef _WIN32 - while (--n >= 0 && (err == SSL_ERROR_WANT_READ || - (err == SSL_ERROR_SYSCALL && - WSAGetLastError() == WSAETIMEDOUT))) { + while (--n >= 0 && + (err == SSL_ERROR_WANT_READ || (err == SSL_ERROR_SYSCALL && WSAGetLastError() == WSAETIMEDOUT))) { #else - while (--n >= 0 && err == SSL_ERROR_WANT_READ) { + while (--n >= 0 && err == SSL_ERROR_WANT_READ) { #endif - if (SSL_pending(ssl_) > 0) { - return SSL_read(ssl_, ptr, static_cast(size)); - } else if (is_readable()) { - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - ret = SSL_read(ssl_, ptr, static_cast(size)); - if (ret >= 0) { return ret; } - err = SSL_get_error(ssl_, ret); - } else { - return -1; + if (SSL_pending(ssl_) > 0) { + return SSL_read(ssl_, ptr, static_cast(size)); + } else if (is_readable()) { + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + ret = SSL_read(ssl_, ptr, static_cast(size)); + if (ret >= 0) { + return ret; + } + err = SSL_get_error(ssl_, ret); + } else { + return -1; + } + } } - } + return ret; } - return ret; - } - return -1; + return -1; } inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) { - if (is_writable()) { - auto handle_size = static_cast( - std::min(size, (std::numeric_limits::max)())); + if (is_writable()) { + auto handle_size = static_cast(std::min(size, (std::numeric_limits::max)())); - auto ret = SSL_write(ssl_, ptr, static_cast(handle_size)); - if (ret < 0) { - auto err = SSL_get_error(ssl_, ret); - auto n = 1000; + auto ret = SSL_write(ssl_, ptr, static_cast(handle_size)); + if (ret < 0) { + auto err = SSL_get_error(ssl_, ret); + auto n = 1000; #ifdef _WIN32 - while (--n >= 0 && (err == SSL_ERROR_WANT_WRITE || - (err == SSL_ERROR_SYSCALL && - WSAGetLastError() == WSAETIMEDOUT))) { + while (--n >= 0 && + (err == SSL_ERROR_WANT_WRITE || (err == SSL_ERROR_SYSCALL && WSAGetLastError() == WSAETIMEDOUT))) { #else - while (--n >= 0 && err == SSL_ERROR_WANT_WRITE) { + while (--n >= 0 && err == SSL_ERROR_WANT_WRITE) { #endif - if (is_writable()) { - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - ret = SSL_write(ssl_, ptr, static_cast(handle_size)); - if (ret >= 0) { return ret; } - err = SSL_get_error(ssl_, ret); - } else { - return -1; + if (is_writable()) { + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + ret = SSL_write(ssl_, ptr, static_cast(handle_size)); + if (ret >= 0) { + return ret; + } + err = SSL_get_error(ssl_, ret); + } else { + return -1; + } + } } - } + return ret; } - return ret; - } - return -1; + return -1; } -inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip, - int &port) const { - detail::get_remote_ip_and_port(sock_, ip, port); +inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip, int &port) const { + detail::get_remote_ip_and_port(sock_, ip, port); } -inline void SSLSocketStream::get_local_ip_and_port(std::string &ip, - int &port) const { - detail::get_local_ip_and_port(sock_, ip, port); +inline void SSLSocketStream::get_local_ip_and_port(std::string &ip, int &port) const { + detail::get_local_ip_and_port(sock_, ip, port); } -inline socket_t SSLSocketStream::socket() const { return sock_; } +inline socket_t SSLSocketStream::socket() const { + return sock_; +} static SSLInit sslinit_; -} // namespace detail +} // namespace detail // SSL HTTP server implementation -inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path, +inline SSLServer::SSLServer(const char *cert_path, + const char *private_key_path, const char *client_ca_cert_file_path, const char *client_ca_cert_dir_path, const char *private_key_password) { - ctx_ = SSL_CTX_new(TLS_server_method()); + ctx_ = SSL_CTX_new(TLS_server_method()); - if (ctx_) { - SSL_CTX_set_options(ctx_, - SSL_OP_NO_COMPRESSION | - SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION); + if (ctx_) { + SSL_CTX_set_options(ctx_, SSL_OP_NO_COMPRESSION | SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION); - SSL_CTX_set_min_proto_version(ctx_, TLS1_1_VERSION); + SSL_CTX_set_min_proto_version(ctx_, TLS1_1_VERSION); - // add default password callback before opening encrypted private key - if (private_key_password != nullptr && (private_key_password[0] != '\0')) { - SSL_CTX_set_default_passwd_cb_userdata( - ctx_, - reinterpret_cast(const_cast(private_key_password))); + // add default password callback before opening encrypted private key + if (private_key_password != nullptr && (private_key_password[0] != '\0')) { + SSL_CTX_set_default_passwd_cb_userdata(ctx_, + reinterpret_cast(const_cast(private_key_password))); + } + + if (SSL_CTX_use_certificate_chain_file(ctx_, cert_path) != 1 || + SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) != 1) { + SSL_CTX_free(ctx_); + ctx_ = nullptr; + } else if (client_ca_cert_file_path || client_ca_cert_dir_path) { + SSL_CTX_load_verify_locations(ctx_, client_ca_cert_file_path, client_ca_cert_dir_path); + + SSL_CTX_set_verify(ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr); + } } - - if (SSL_CTX_use_certificate_chain_file(ctx_, cert_path) != 1 || - SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) != - 1) { - SSL_CTX_free(ctx_); - ctx_ = nullptr; - } else if (client_ca_cert_file_path || client_ca_cert_dir_path) { - SSL_CTX_load_verify_locations(ctx_, client_ca_cert_file_path, - client_ca_cert_dir_path); - - SSL_CTX_set_verify( - ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr); - } - } } -inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key, - X509_STORE *client_ca_cert_store) { - ctx_ = SSL_CTX_new(TLS_server_method()); +inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key, X509_STORE *client_ca_cert_store) { + ctx_ = SSL_CTX_new(TLS_server_method()); - if (ctx_) { - SSL_CTX_set_options(ctx_, - SSL_OP_NO_COMPRESSION | - SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION); + if (ctx_) { + SSL_CTX_set_options(ctx_, SSL_OP_NO_COMPRESSION | SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION); - SSL_CTX_set_min_proto_version(ctx_, TLS1_1_VERSION); + SSL_CTX_set_min_proto_version(ctx_, TLS1_1_VERSION); - if (SSL_CTX_use_certificate(ctx_, cert) != 1 || - SSL_CTX_use_PrivateKey(ctx_, private_key) != 1) { - SSL_CTX_free(ctx_); - ctx_ = nullptr; - } else if (client_ca_cert_store) { - SSL_CTX_set_cert_store(ctx_, client_ca_cert_store); + if (SSL_CTX_use_certificate(ctx_, cert) != 1 || SSL_CTX_use_PrivateKey(ctx_, private_key) != 1) { + SSL_CTX_free(ctx_); + ctx_ = nullptr; + } else if (client_ca_cert_store) { + SSL_CTX_set_cert_store(ctx_, client_ca_cert_store); - SSL_CTX_set_verify( - ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr); + SSL_CTX_set_verify(ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr); + } } - } } -inline SSLServer::SSLServer( - const std::function &setup_ssl_ctx_callback) { - ctx_ = SSL_CTX_new(TLS_method()); - if (ctx_) { - if (!setup_ssl_ctx_callback(*ctx_)) { - SSL_CTX_free(ctx_); - ctx_ = nullptr; +inline SSLServer::SSLServer(const std::function &setup_ssl_ctx_callback) { + ctx_ = SSL_CTX_new(TLS_method()); + if (ctx_) { + if (!setup_ssl_ctx_callback(*ctx_)) { + SSL_CTX_free(ctx_); + ctx_ = nullptr; + } } - } } inline SSLServer::~SSLServer() { - if (ctx_) { SSL_CTX_free(ctx_); } + if (ctx_) { + SSL_CTX_free(ctx_); + } } -inline bool SSLServer::is_valid() const { return ctx_; } +inline bool SSLServer::is_valid() const { + return ctx_; +} -inline SSL_CTX *SSLServer::ssl_context() const { return ctx_; } +inline SSL_CTX *SSLServer::ssl_context() const { + return ctx_; +} inline bool SSLServer::process_and_close_socket(socket_t sock) { - auto ssl = detail::ssl_new( - sock, ctx_, ctx_mutex_, - [&](SSL *ssl2) { - return detail::ssl_connect_or_accept_nonblocking( - sock, ssl2, SSL_accept, read_timeout_sec_, read_timeout_usec_); - }, - [](SSL * /*ssl2*/) { return true; }); + auto ssl = detail::ssl_new( + sock, + ctx_, + ctx_mutex_, + [&](SSL *ssl2) { + return detail::ssl_connect_or_accept_nonblocking(sock, + ssl2, + SSL_accept, + read_timeout_sec_, + read_timeout_usec_); + }, + [](SSL * /*ssl2*/) { return true; }); - auto ret = false; - if (ssl) { - ret = detail::process_server_socket_ssl( - svr_sock_, ssl, sock, keep_alive_max_count_, keep_alive_timeout_sec_, - read_timeout_sec_, read_timeout_usec_, write_timeout_sec_, - write_timeout_usec_, - [this, ssl](Stream &strm, bool close_connection, - bool &connection_closed) { - return process_request(strm, close_connection, connection_closed, - [&](Request &req) { req.ssl = ssl; }); - }); + auto ret = false; + if (ssl) { + ret = detail::process_server_socket_ssl( + svr_sock_, + ssl, + sock, + keep_alive_max_count_, + keep_alive_timeout_sec_, + read_timeout_sec_, + read_timeout_usec_, + write_timeout_sec_, + write_timeout_usec_, + [this, ssl](Stream &strm, bool close_connection, bool &connection_closed) { + return process_request(strm, close_connection, connection_closed, [&](Request &req) { req.ssl = ssl; }); + }); - // Shutdown gracefully if the result seemed successful, non-gracefully if - // the connection appeared to be closed. - const bool shutdown_gracefully = ret; - detail::ssl_delete(ctx_mutex_, ssl, shutdown_gracefully); - } + // Shutdown gracefully if the result seemed successful, non-gracefully if + // the connection appeared to be closed. + const bool shutdown_gracefully = ret; + detail::ssl_delete(ctx_mutex_, ssl, shutdown_gracefully); + } - detail::shutdown_socket(sock); - detail::close_socket(sock); - return ret; + detail::shutdown_socket(sock); + detail::close_socket(sock); + return ret; } // SSL HTTP client implementation -inline SSLClient::SSLClient(const std::string &host) - : SSLClient(host, 443, std::string(), std::string()) {} +inline SSLClient::SSLClient(const std::string &host) : SSLClient(host, 443, std::string(), std::string()) { +} -inline SSLClient::SSLClient(const std::string &host, int port) - : SSLClient(host, port, std::string(), std::string()) {} +inline SSLClient::SSLClient(const std::string &host, int port) : SSLClient(host, port, std::string(), std::string()) { +} -inline SSLClient::SSLClient(const std::string &host, int port, +inline SSLClient::SSLClient(const std::string &host, + int port, const std::string &client_cert_path, const std::string &client_key_path) : ClientImpl(host, port, client_cert_path, client_key_path) { - ctx_ = SSL_CTX_new(TLS_client_method()); + ctx_ = SSL_CTX_new(TLS_client_method()); - detail::split(&host_[0], &host_[host_.size()], '.', - [&](const char *b, const char *e) { - host_components_.emplace_back(std::string(b, e)); - }); + detail::split(&host_[0], &host_[host_.size()], '.', [&](const char *b, const char *e) { + host_components_.emplace_back(std::string(b, e)); + }); - if (!client_cert_path.empty() && !client_key_path.empty()) { - if (SSL_CTX_use_certificate_file(ctx_, client_cert_path.c_str(), - SSL_FILETYPE_PEM) != 1 || - SSL_CTX_use_PrivateKey_file(ctx_, client_key_path.c_str(), - SSL_FILETYPE_PEM) != 1) { - SSL_CTX_free(ctx_); - ctx_ = nullptr; + if (!client_cert_path.empty() && !client_key_path.empty()) { + if (SSL_CTX_use_certificate_file(ctx_, client_cert_path.c_str(), SSL_FILETYPE_PEM) != 1 || + SSL_CTX_use_PrivateKey_file(ctx_, client_key_path.c_str(), SSL_FILETYPE_PEM) != 1) { + SSL_CTX_free(ctx_); + ctx_ = nullptr; + } } - } } -inline SSLClient::SSLClient(const std::string &host, int port, - X509 *client_cert, EVP_PKEY *client_key) +inline SSLClient::SSLClient(const std::string &host, int port, X509 *client_cert, EVP_PKEY *client_key) : ClientImpl(host, port) { - ctx_ = SSL_CTX_new(TLS_client_method()); + ctx_ = SSL_CTX_new(TLS_client_method()); - detail::split(&host_[0], &host_[host_.size()], '.', - [&](const char *b, const char *e) { - host_components_.emplace_back(std::string(b, e)); - }); + detail::split(&host_[0], &host_[host_.size()], '.', [&](const char *b, const char *e) { + host_components_.emplace_back(std::string(b, e)); + }); - if (client_cert != nullptr && client_key != nullptr) { - if (SSL_CTX_use_certificate(ctx_, client_cert) != 1 || - SSL_CTX_use_PrivateKey(ctx_, client_key) != 1) { - SSL_CTX_free(ctx_); - ctx_ = nullptr; + if (client_cert != nullptr && client_key != nullptr) { + if (SSL_CTX_use_certificate(ctx_, client_cert) != 1 || SSL_CTX_use_PrivateKey(ctx_, client_key) != 1) { + SSL_CTX_free(ctx_); + ctx_ = nullptr; + } } - } } inline SSLClient::~SSLClient() { - if (ctx_) { SSL_CTX_free(ctx_); } - // Make sure to shut down SSL since shutdown_ssl will resolve to the - // base function rather than the derived function once we get to the - // base class destructor, and won't free the SSL (causing a leak). - shutdown_ssl_impl(socket_, true); + if (ctx_) { + SSL_CTX_free(ctx_); + } + // Make sure to shut down SSL since shutdown_ssl will resolve to the + // base function rather than the derived function once we get to the + // base class destructor, and won't free the SSL (causing a leak). + shutdown_ssl_impl(socket_, true); } -inline bool SSLClient::is_valid() const { return ctx_; } +inline bool SSLClient::is_valid() const { + return ctx_; +} inline void SSLClient::set_ca_cert_store(X509_STORE *ca_cert_store) { - if (ca_cert_store) { - if (ctx_) { - if (SSL_CTX_get_cert_store(ctx_) != ca_cert_store) { - // Free memory allocated for old cert and use new store `ca_cert_store` - SSL_CTX_set_cert_store(ctx_, ca_cert_store); - } - } else { - X509_STORE_free(ca_cert_store); + if (ca_cert_store) { + if (ctx_) { + if (SSL_CTX_get_cert_store(ctx_) != ca_cert_store) { + // Free memory allocated for old cert and use new store `ca_cert_store` + SSL_CTX_set_cert_store(ctx_, ca_cert_store); + } + } else { + X509_STORE_free(ca_cert_store); + } } - } } -inline void SSLClient::load_ca_cert_store(const char *ca_cert, - std::size_t size) { - set_ca_cert_store(ClientImpl::create_ca_cert_store(ca_cert, size)); +inline void SSLClient::load_ca_cert_store(const char *ca_cert, std::size_t size) { + set_ca_cert_store(ClientImpl::create_ca_cert_store(ca_cert, size)); } inline long SSLClient::get_openssl_verify_result() const { - return verify_result_; + return verify_result_; } -inline SSL_CTX *SSLClient::ssl_context() const { return ctx_; } +inline SSL_CTX *SSLClient::ssl_context() const { + return ctx_; +} inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) { - return is_valid() && ClientImpl::create_and_connect_socket(socket, error); + return is_valid() && ClientImpl::create_and_connect_socket(socket, error); } // Assumes that socket_mutex_ is locked and that there are no requests in flight -inline bool SSLClient::connect_with_proxy(Socket &socket, Response &res, - bool &success, Error &error) { - success = true; - Response res2; - if (!detail::process_client_socket( - socket.sock, read_timeout_sec_, read_timeout_usec_, - write_timeout_sec_, write_timeout_usec_, [&](Stream &strm) { - Request req2; - req2.method = "CONNECT"; - req2.path = host_and_port_; - return process_request(strm, req2, res2, false, error); - })) { - // Thread-safe to close everything because we are assuming there are no - // requests in flight - shutdown_ssl(socket, true); - shutdown_socket(socket); - close_socket(socket); - success = false; - return false; - } - - if (res2.status == 407) { - if (!proxy_digest_auth_username_.empty() && - !proxy_digest_auth_password_.empty()) { - std::map auth; - if (detail::parse_www_authenticate(res2, auth, true)) { - Response res3; - if (!detail::process_client_socket( - socket.sock, read_timeout_sec_, read_timeout_usec_, - write_timeout_sec_, write_timeout_usec_, [&](Stream &strm) { - Request req3; - req3.method = "CONNECT"; - req3.path = host_and_port_; - req3.headers.insert(detail::make_digest_authentication_header( - req3, auth, 1, detail::random_string(10), - proxy_digest_auth_username_, proxy_digest_auth_password_, - true)); - return process_request(strm, req3, res3, false, error); - })) { - // Thread-safe to close everything because we are assuming there are - // no requests in flight - shutdown_ssl(socket, true); - shutdown_socket(socket); - close_socket(socket); - success = false; - return false; - } - } - } else { - res = res2; - return false; +inline bool SSLClient::connect_with_proxy(Socket &socket, Response &res, bool &success, Error &error) { + success = true; + Response res2; + if (!detail::process_client_socket(socket.sock, + read_timeout_sec_, + read_timeout_usec_, + write_timeout_sec_, + write_timeout_usec_, + [&](Stream &strm) { + Request req2; + req2.method = "CONNECT"; + req2.path = host_and_port_; + return process_request(strm, req2, res2, false, error); + })) { + // Thread-safe to close everything because we are assuming there are no + // requests in flight + shutdown_ssl(socket, true); + shutdown_socket(socket); + close_socket(socket); + success = false; + return false; } - } - return true; + if (res2.status == 407) { + if (!proxy_digest_auth_username_.empty() && !proxy_digest_auth_password_.empty()) { + std::map auth; + if (detail::parse_www_authenticate(res2, auth, true)) { + Response res3; + if (!detail::process_client_socket(socket.sock, + read_timeout_sec_, + read_timeout_usec_, + write_timeout_sec_, + write_timeout_usec_, + [&](Stream &strm) { + Request req3; + req3.method = "CONNECT"; + req3.path = host_and_port_; + req3.headers.insert(detail::make_digest_authentication_header( + req3, + auth, + 1, + detail::random_string(10), + proxy_digest_auth_username_, + proxy_digest_auth_password_, + true)); + return process_request(strm, req3, res3, false, error); + })) { + // Thread-safe to close everything because we are assuming there are + // no requests in flight + shutdown_ssl(socket, true); + shutdown_socket(socket); + close_socket(socket); + success = false; + return false; + } + } + } else { + res = res2; + return false; + } + } + + return true; } inline bool SSLClient::load_certs() { - bool ret = true; + bool ret = true; - std::call_once(initialize_cert_, [&]() { - std::lock_guard guard(ctx_mutex_); - if (!ca_cert_file_path_.empty()) { - if (!SSL_CTX_load_verify_locations(ctx_, ca_cert_file_path_.c_str(), - nullptr)) { - ret = false; - } - } else if (!ca_cert_dir_path_.empty()) { - if (!SSL_CTX_load_verify_locations(ctx_, nullptr, - ca_cert_dir_path_.c_str())) { - ret = false; - } - } else { - auto loaded = false; + std::call_once(initialize_cert_, [&]() { + std::lock_guard guard(ctx_mutex_); + if (!ca_cert_file_path_.empty()) { + if (!SSL_CTX_load_verify_locations(ctx_, ca_cert_file_path_.c_str(), nullptr)) { + ret = false; + } + } else if (!ca_cert_dir_path_.empty()) { + if (!SSL_CTX_load_verify_locations(ctx_, nullptr, ca_cert_dir_path_.c_str())) { + ret = false; + } + } else { + auto loaded = false; #ifdef _WIN32 - loaded = - detail::load_system_certs_on_windows(SSL_CTX_get_cert_store(ctx_)); + loaded = detail::load_system_certs_on_windows(SSL_CTX_get_cert_store(ctx_)); #elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && defined(__APPLE__) #if TARGET_OS_OSX loaded = detail::load_system_certs_on_macos(SSL_CTX_get_cert_store(ctx_)); -#endif // TARGET_OS_OSX -#endif // _WIN32 - if (!loaded) { SSL_CTX_set_default_verify_paths(ctx_); } - } - }); +#endif // TARGET_OS_OSX +#endif // _WIN32 + if (!loaded) { + SSL_CTX_set_default_verify_paths(ctx_); + } + } + }); - return ret; + return ret; } inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) { - auto ssl = detail::ssl_new( - socket.sock, ctx_, ctx_mutex_, - [&](SSL *ssl2) { - if (server_certificate_verification_) { - if (!load_certs()) { - error = Error::SSLLoadingCerts; - return false; - } - SSL_set_verify(ssl2, SSL_VERIFY_NONE, nullptr); - } + auto ssl = detail::ssl_new( + socket.sock, + ctx_, + ctx_mutex_, + [&](SSL *ssl2) { + if (server_certificate_verification_) { + if (!load_certs()) { + error = Error::SSLLoadingCerts; + return false; + } + SSL_set_verify(ssl2, SSL_VERIFY_NONE, nullptr); + } - if (!detail::ssl_connect_or_accept_nonblocking( - socket.sock, ssl2, SSL_connect, connection_timeout_sec_, - connection_timeout_usec_)) { - error = Error::SSLConnection; - return false; - } + if (!detail::ssl_connect_or_accept_nonblocking(socket.sock, + ssl2, + SSL_connect, + connection_timeout_sec_, + connection_timeout_usec_)) { + error = Error::SSLConnection; + return false; + } - if (server_certificate_verification_) { - verify_result_ = SSL_get_verify_result(ssl2); + if (server_certificate_verification_) { + verify_result_ = SSL_get_verify_result(ssl2); - if (verify_result_ != X509_V_OK) { - error = Error::SSLServerVerification; - return false; - } + if (verify_result_ != X509_V_OK) { + error = Error::SSLServerVerification; + return false; + } - auto server_cert = SSL_get1_peer_certificate(ssl2); + auto server_cert = SSL_get1_peer_certificate(ssl2); - if (server_cert == nullptr) { - error = Error::SSLServerVerification; - return false; - } + if (server_cert == nullptr) { + error = Error::SSLServerVerification; + return false; + } - if (!verify_host(server_cert)) { - X509_free(server_cert); - error = Error::SSLServerVerification; - return false; - } - X509_free(server_cert); - } + if (!verify_host(server_cert)) { + X509_free(server_cert); + error = Error::SSLServerVerification; + return false; + } + X509_free(server_cert); + } + return true; + }, + [&](SSL *ssl2) { + // NOTE: With -Wold-style-cast, this can produce a warning, since + // SSL_set_tlsext_host_name is a macro (in OpenSSL), which contains + // an old style cast. Short of doing compiler specific pragma's + // here, we can't get rid of this warning. :'( + SSL_set_tlsext_host_name(ssl2, host_.c_str()); + return true; + }); + + if (ssl) { + socket.ssl = ssl; return true; - }, - [&](SSL *ssl2) { - // NOTE: With -Wold-style-cast, this can produce a warning, since - // SSL_set_tlsext_host_name is a macro (in OpenSSL), which contains - // an old style cast. Short of doing compiler specific pragma's - // here, we can't get rid of this warning. :'( - SSL_set_tlsext_host_name(ssl2, host_.c_str()); - return true; - }); + } - if (ssl) { - socket.ssl = ssl; - return true; - } - - shutdown_socket(socket); - close_socket(socket); - return false; + shutdown_socket(socket); + close_socket(socket); + return false; } inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) { - shutdown_ssl_impl(socket, shutdown_gracefully); + shutdown_ssl_impl(socket, shutdown_gracefully); } -inline void SSLClient::shutdown_ssl_impl(Socket &socket, - bool shutdown_gracefully) { - if (socket.sock == INVALID_SOCKET) { +inline void SSLClient::shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully) { + if (socket.sock == INVALID_SOCKET) { + assert(socket.ssl == nullptr); + return; + } + if (socket.ssl) { + detail::ssl_delete(ctx_mutex_, socket.ssl, shutdown_gracefully); + socket.ssl = nullptr; + } assert(socket.ssl == nullptr); - return; - } - if (socket.ssl) { - detail::ssl_delete(ctx_mutex_, socket.ssl, shutdown_gracefully); - socket.ssl = nullptr; - } - assert(socket.ssl == nullptr); } -inline bool -SSLClient::process_socket(const Socket &socket, - std::function callback) { - assert(socket.ssl); - return detail::process_client_socket_ssl( - socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_, - write_timeout_sec_, write_timeout_usec_, std::move(callback)); +inline bool SSLClient::process_socket(const Socket &socket, std::function callback) { + assert(socket.ssl); + return detail::process_client_socket_ssl(socket.ssl, + socket.sock, + read_timeout_sec_, + read_timeout_usec_, + write_timeout_sec_, + write_timeout_usec_, + std::move(callback)); } -inline bool SSLClient::is_ssl() const { return true; } +inline bool SSLClient::is_ssl() const { + return true; +} inline bool SSLClient::verify_host(X509 *server_cert) const { - /* Quote from RFC2818 section 3.1 "Server Identity" + /* Quote from RFC2818 section 3.1 "Server Identity" If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name @@ -8442,609 +9032,715 @@ inline bool SSLClient::verify_host(X509 *server_cert) const { in the certificate and must exactly match the IP in the URI. */ - return verify_host_with_subject_alt_name(server_cert) || - verify_host_with_common_name(server_cert); + return verify_host_with_subject_alt_name(server_cert) || verify_host_with_common_name(server_cert); } -inline bool -SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const { - auto ret = false; +inline bool SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const { + auto ret = false; - auto type = GEN_DNS; + auto type = GEN_DNS; - struct in6_addr addr6; - struct in_addr addr; - size_t addr_len = 0; + struct in6_addr addr6; + struct in_addr addr; + size_t addr_len = 0; #ifndef __MINGW32__ - if (inet_pton(AF_INET6, host_.c_str(), &addr6)) { - type = GEN_IPADD; - addr_len = sizeof(struct in6_addr); - } else if (inet_pton(AF_INET, host_.c_str(), &addr)) { - type = GEN_IPADD; - addr_len = sizeof(struct in_addr); - } + if (inet_pton(AF_INET6, host_.c_str(), &addr6)) { + type = GEN_IPADD; + addr_len = sizeof(struct in6_addr); + } else if (inet_pton(AF_INET, host_.c_str(), &addr)) { + type = GEN_IPADD; + addr_len = sizeof(struct in_addr); + } #endif - auto alt_names = static_cast( - X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr)); + auto alt_names = static_cast( + X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr)); - if (alt_names) { - auto dsn_matched = false; - auto ip_matched = false; + if (alt_names) { + auto dsn_matched = false; + auto ip_matched = false; - auto count = sk_GENERAL_NAME_num(alt_names); + auto count = sk_GENERAL_NAME_num(alt_names); - for (decltype(count) i = 0; i < count && !dsn_matched; i++) { - auto val = sk_GENERAL_NAME_value(alt_names, i); - if (val->type == type) { - auto name = - reinterpret_cast(ASN1_STRING_get0_data(val->d.ia5)); - auto name_len = static_cast(ASN1_STRING_length(val->d.ia5)); + for (decltype(count) i = 0; i < count && !dsn_matched; i++) { + auto val = sk_GENERAL_NAME_value(alt_names, i); + if (val->type == type) { + auto name = reinterpret_cast(ASN1_STRING_get0_data(val->d.ia5)); + auto name_len = static_cast(ASN1_STRING_length(val->d.ia5)); - switch (type) { - case GEN_DNS: dsn_matched = check_host_name(name, name_len); break; + switch (type) { + case GEN_DNS: + dsn_matched = check_host_name(name, name_len); + break; - case GEN_IPADD: - if (!memcmp(&addr6, name, addr_len) || - !memcmp(&addr, name, addr_len)) { - ip_matched = true; - } - break; + case GEN_IPADD: + if (!memcmp(&addr6, name, addr_len) || !memcmp(&addr, name, addr_len)) { + ip_matched = true; + } + break; + } + } + } + + if (dsn_matched || ip_matched) { + ret = true; } - } } - if (dsn_matched || ip_matched) { ret = true; } - } - - GENERAL_NAMES_free(const_cast( - reinterpret_cast(alt_names))); - return ret; + GENERAL_NAMES_free( + const_cast(reinterpret_cast(alt_names))); + return ret; } inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const { - const auto subject_name = X509_get_subject_name(server_cert); + const auto subject_name = X509_get_subject_name(server_cert); - if (subject_name != nullptr) { - char name[BUFSIZ]; - auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName, - name, sizeof(name)); + if (subject_name != nullptr) { + char name[BUFSIZ]; + auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName, name, sizeof(name)); - if (name_len != -1) { - return check_host_name(name, static_cast(name_len)); + if (name_len != -1) { + return check_host_name(name, static_cast(name_len)); + } } - } - return false; + return false; } -inline bool SSLClient::check_host_name(const char *pattern, - size_t pattern_len) const { - if (host_.size() == pattern_len && host_ == pattern) { return true; } - - // Wildcard match - // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484 - std::vector pattern_components; - detail::split(&pattern[0], &pattern[pattern_len], '.', - [&](const char *b, const char *e) { - pattern_components.emplace_back(std::string(b, e)); - }); - - if (host_components_.size() != pattern_components.size()) { return false; } - - auto itr = pattern_components.begin(); - for (const auto &h : host_components_) { - auto &p = *itr; - if (p != h && p != "*") { - auto partial_match = (p.size() > 0 && p[p.size() - 1] == '*' && - !p.compare(0, p.size() - 1, h)); - if (!partial_match) { return false; } +inline bool SSLClient::check_host_name(const char *pattern, size_t pattern_len) const { + if (host_.size() == pattern_len && host_ == pattern) { + return true; } - ++itr; - } - return true; + // Wildcard match + // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484 + std::vector pattern_components; + detail::split(&pattern[0], &pattern[pattern_len], '.', [&](const char *b, const char *e) { + pattern_components.emplace_back(std::string(b, e)); + }); + + if (host_components_.size() != pattern_components.size()) { + return false; + } + + auto itr = pattern_components.begin(); + for (const auto &h : host_components_) { + auto &p = *itr; + if (p != h && p != "*") { + auto partial_match = (p.size() > 0 && p[p.size() - 1] == '*' && !p.compare(0, p.size() - 1, h)); + if (!partial_match) { + return false; + } + } + ++itr; + } + + return true; } #endif // Universal client implementation -inline Client::Client(const std::string &scheme_host_port) - : Client(scheme_host_port, std::string(), std::string()) {} +inline Client::Client(const std::string &scheme_host_port) : Client(scheme_host_port, std::string(), std::string()) { +} inline Client::Client(const std::string &scheme_host_port, const std::string &client_cert_path, const std::string &client_key_path) { - const static std::regex re( - R"((?:([a-z]+):\/\/)?(?:\[([\d:]+)\]|([^:/?#]+))(?::(\d+))?)"); + const static std::regex re(R"((?:([a-z]+):\/\/)?(?:\[([\d:]+)\]|([^:/?#]+))(?::(\d+))?)"); - std::smatch m; - if (std::regex_match(scheme_host_port, m, re)) { - auto scheme = m[1].str(); + std::smatch m; + if (std::regex_match(scheme_host_port, m, re)) { + auto scheme = m[1].str(); #ifdef CPPHTTPLIB_OPENSSL_SUPPORT - if (!scheme.empty() && (scheme != "http" && scheme != "https")) { + if (!scheme.empty() && (scheme != "http" && scheme != "https")) { #else - if (!scheme.empty() && scheme != "http") { + if (!scheme.empty() && scheme != "http") { #endif #ifndef CPPHTTPLIB_NO_EXCEPTIONS - std::string msg = "'" + scheme + "' scheme is not supported."; - throw std::invalid_argument(msg); + std::string msg = "'" + scheme + "' scheme is not supported."; + throw std::invalid_argument(msg); #endif - return; - } + return; + } - auto is_ssl = scheme == "https"; + auto is_ssl = scheme == "https"; - auto host = m[2].str(); - if (host.empty()) { host = m[3].str(); } + auto host = m[2].str(); + if (host.empty()) { + host = m[3].str(); + } - auto port_str = m[4].str(); - auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80); + auto port_str = m[4].str(); + auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80); - if (is_ssl) { + if (is_ssl) { #ifdef CPPHTTPLIB_OPENSSL_SUPPORT - cli_ = detail::make_unique(host, port, client_cert_path, - client_key_path); - is_ssl_ = is_ssl; + cli_ = detail::make_unique(host, port, client_cert_path, client_key_path); + is_ssl_ = is_ssl; #endif + } else { + cli_ = detail::make_unique(host, port, client_cert_path, client_key_path); + } } else { - cli_ = detail::make_unique(host, port, client_cert_path, - client_key_path); + cli_ = detail::make_unique(scheme_host_port, 80, client_cert_path, client_key_path); } - } else { - cli_ = detail::make_unique(scheme_host_port, 80, - client_cert_path, client_key_path); - } } -inline Client::Client(const std::string &host, int port) - : cli_(detail::make_unique(host, port)) {} +inline Client::Client(const std::string &host, int port) : cli_(detail::make_unique(host, port)) { +} -inline Client::Client(const std::string &host, int port, +inline Client::Client(const std::string &host, + int port, const std::string &client_cert_path, const std::string &client_key_path) - : cli_(detail::make_unique(host, port, client_cert_path, - client_key_path)) {} + : cli_(detail::make_unique(host, port, client_cert_path, client_key_path)) { +} -inline Client::~Client() {} +inline Client::~Client() { +} inline bool Client::is_valid() const { - return cli_ != nullptr && cli_->is_valid(); + return cli_ != nullptr && cli_->is_valid(); +} + +inline Result Client::Get(const std::string &path) { + return cli_->Get(path); } -inline Result Client::Get(const std::string &path) { return cli_->Get(path); } inline Result Client::Get(const std::string &path, const Headers &headers) { - return cli_->Get(path, headers); + return cli_->Get(path, headers); } + inline Result Client::Get(const std::string &path, Progress progress) { - return cli_->Get(path, std::move(progress)); -} -inline Result Client::Get(const std::string &path, const Headers &headers, - Progress progress) { - return cli_->Get(path, headers, std::move(progress)); -} -inline Result Client::Get(const std::string &path, - ContentReceiver content_receiver) { - return cli_->Get(path, std::move(content_receiver)); -} -inline Result Client::Get(const std::string &path, const Headers &headers, - ContentReceiver content_receiver) { - return cli_->Get(path, headers, std::move(content_receiver)); -} -inline Result Client::Get(const std::string &path, - ContentReceiver content_receiver, Progress progress) { - return cli_->Get(path, std::move(content_receiver), std::move(progress)); -} -inline Result Client::Get(const std::string &path, const Headers &headers, - ContentReceiver content_receiver, Progress progress) { - return cli_->Get(path, headers, std::move(content_receiver), - std::move(progress)); -} -inline Result Client::Get(const std::string &path, - ResponseHandler response_handler, - ContentReceiver content_receiver) { - return cli_->Get(path, std::move(response_handler), - std::move(content_receiver)); -} -inline Result Client::Get(const std::string &path, const Headers &headers, - ResponseHandler response_handler, - ContentReceiver content_receiver) { - return cli_->Get(path, headers, std::move(response_handler), - std::move(content_receiver)); -} -inline Result Client::Get(const std::string &path, - ResponseHandler response_handler, - ContentReceiver content_receiver, Progress progress) { - return cli_->Get(path, std::move(response_handler), - std::move(content_receiver), std::move(progress)); -} -inline Result Client::Get(const std::string &path, const Headers &headers, - ResponseHandler response_handler, - ContentReceiver content_receiver, Progress progress) { - return cli_->Get(path, headers, std::move(response_handler), - std::move(content_receiver), std::move(progress)); -} -inline Result Client::Get(const std::string &path, const Params ¶ms, - const Headers &headers, Progress progress) { - return cli_->Get(path, params, headers, progress); -} -inline Result Client::Get(const std::string &path, const Params ¶ms, - const Headers &headers, - ContentReceiver content_receiver, Progress progress) { - return cli_->Get(path, params, headers, content_receiver, progress); -} -inline Result Client::Get(const std::string &path, const Params ¶ms, - const Headers &headers, - ResponseHandler response_handler, - ContentReceiver content_receiver, Progress progress) { - return cli_->Get(path, params, headers, response_handler, content_receiver, - progress); + return cli_->Get(path, std::move(progress)); +} + +inline Result Client::Get(const std::string &path, const Headers &headers, Progress progress) { + return cli_->Get(path, headers, std::move(progress)); +} + +inline Result Client::Get(const std::string &path, ContentReceiver content_receiver) { + return cli_->Get(path, std::move(content_receiver)); +} + +inline Result Client::Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver) { + return cli_->Get(path, headers, std::move(content_receiver)); +} + +inline Result Client::Get(const std::string &path, ContentReceiver content_receiver, Progress progress) { + return cli_->Get(path, std::move(content_receiver), std::move(progress)); +} + +inline Result Client::Get(const std::string &path, + const Headers &headers, + ContentReceiver content_receiver, + Progress progress) { + return cli_->Get(path, headers, std::move(content_receiver), std::move(progress)); +} + +inline Result Client::Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver) { + return cli_->Get(path, std::move(response_handler), std::move(content_receiver)); +} + +inline Result Client::Get(const std::string &path, + const Headers &headers, + ResponseHandler response_handler, + ContentReceiver content_receiver) { + return cli_->Get(path, headers, std::move(response_handler), std::move(content_receiver)); +} + +inline Result Client::Get(const std::string &path, + ResponseHandler response_handler, + ContentReceiver content_receiver, + Progress progress) { + return cli_->Get(path, std::move(response_handler), std::move(content_receiver), std::move(progress)); +} + +inline Result Client::Get(const std::string &path, + const Headers &headers, + ResponseHandler response_handler, + ContentReceiver content_receiver, + Progress progress) { + return cli_->Get(path, headers, std::move(response_handler), std::move(content_receiver), std::move(progress)); +} + +inline Result Client::Get(const std::string &path, const Params ¶ms, const Headers &headers, Progress progress) { + return cli_->Get(path, params, headers, progress); +} + +inline Result Client::Get(const std::string &path, + const Params ¶ms, + const Headers &headers, + ContentReceiver content_receiver, + Progress progress) { + return cli_->Get(path, params, headers, content_receiver, progress); +} + +inline Result Client::Get(const std::string &path, + const Params ¶ms, + const Headers &headers, + ResponseHandler response_handler, + ContentReceiver content_receiver, + Progress progress) { + return cli_->Get(path, params, headers, response_handler, content_receiver, progress); +} + +inline Result Client::Head(const std::string &path) { + return cli_->Head(path); } -inline Result Client::Head(const std::string &path) { return cli_->Head(path); } inline Result Client::Head(const std::string &path, const Headers &headers) { - return cli_->Head(path, headers); + return cli_->Head(path, headers); +} + +inline Result Client::Post(const std::string &path) { + return cli_->Post(path); } -inline Result Client::Post(const std::string &path) { return cli_->Post(path); } inline Result Client::Post(const std::string &path, const Headers &headers) { - return cli_->Post(path, headers); + return cli_->Post(path, headers); } -inline Result Client::Post(const std::string &path, const char *body, - size_t content_length, + +inline Result Client::Post(const std::string &path, + const char *body, + size_t content_length, const std::string &content_type) { - return cli_->Post(path, body, content_length, content_type); + return cli_->Post(path, body, content_length, content_type); } -inline Result Client::Post(const std::string &path, const Headers &headers, - const char *body, size_t content_length, + +inline Result Client::Post(const std::string &path, + const Headers &headers, + const char *body, + size_t content_length, const std::string &content_type) { - return cli_->Post(path, headers, body, content_length, content_type); + return cli_->Post(path, headers, body, content_length, content_type); } -inline Result Client::Post(const std::string &path, const std::string &body, - const std::string &content_type) { - return cli_->Post(path, body, content_type); + +inline Result Client::Post(const std::string &path, const std::string &body, const std::string &content_type) { + return cli_->Post(path, body, content_type); } -inline Result Client::Post(const std::string &path, const Headers &headers, + +inline Result Client::Post(const std::string &path, + const Headers &headers, const std::string &body, const std::string &content_type) { - return cli_->Post(path, headers, body, content_type); -} -inline Result Client::Post(const std::string &path, size_t content_length, - ContentProvider content_provider, - const std::string &content_type) { - return cli_->Post(path, content_length, std::move(content_provider), - content_type); + return cli_->Post(path, headers, body, content_type); } + inline Result Client::Post(const std::string &path, + size_t content_length, + ContentProvider content_provider, + const std::string &content_type) { + return cli_->Post(path, content_length, std::move(content_provider), content_type); +} + +inline Result Client::Post(const std::string &path, ContentProviderWithoutLength content_provider, - const std::string &content_type) { - return cli_->Post(path, std::move(content_provider), content_type); + const std::string &content_type) { + return cli_->Post(path, std::move(content_provider), content_type); } -inline Result Client::Post(const std::string &path, const Headers &headers, - size_t content_length, - ContentProvider content_provider, + +inline Result Client::Post(const std::string &path, + const Headers &headers, + size_t content_length, + ContentProvider content_provider, const std::string &content_type) { - return cli_->Post(path, headers, content_length, std::move(content_provider), - content_type); + return cli_->Post(path, headers, content_length, std::move(content_provider), content_type); } -inline Result Client::Post(const std::string &path, const Headers &headers, + +inline Result Client::Post(const std::string &path, + const Headers &headers, ContentProviderWithoutLength content_provider, - const std::string &content_type) { - return cli_->Post(path, headers, std::move(content_provider), content_type); + const std::string &content_type) { + return cli_->Post(path, headers, std::move(content_provider), content_type); } + inline Result Client::Post(const std::string &path, const Params ¶ms) { - return cli_->Post(path, params); + return cli_->Post(path, params); } -inline Result Client::Post(const std::string &path, const Headers &headers, - const Params ¶ms) { - return cli_->Post(path, headers, params); + +inline Result Client::Post(const std::string &path, const Headers &headers, const Params ¶ms) { + return cli_->Post(path, headers, params); } -inline Result Client::Post(const std::string &path, - const MultipartFormDataItems &items) { - return cli_->Post(path, items); + +inline Result Client::Post(const std::string &path, const MultipartFormDataItems &items) { + return cli_->Post(path, items); } -inline Result Client::Post(const std::string &path, const Headers &headers, - const MultipartFormDataItems &items) { - return cli_->Post(path, headers, items); + +inline Result Client::Post(const std::string &path, const Headers &headers, const MultipartFormDataItems &items) { + return cli_->Post(path, headers, items); } -inline Result Client::Post(const std::string &path, const Headers &headers, + +inline Result Client::Post(const std::string &path, + const Headers &headers, const MultipartFormDataItems &items, - const std::string &boundary) { - return cli_->Post(path, headers, items, boundary); + const std::string &boundary) { + return cli_->Post(path, headers, items, boundary); } -inline Result -Client::Post(const std::string &path, const Headers &headers, - const MultipartFormDataItems &items, - const MultipartFormDataProviderItems &provider_items) { - return cli_->Post(path, headers, items, provider_items); + +inline Result Client::Post(const std::string &path, + const Headers &headers, + const MultipartFormDataItems &items, + const MultipartFormDataProviderItems &provider_items) { + return cli_->Post(path, headers, items, provider_items); } -inline Result Client::Put(const std::string &path) { return cli_->Put(path); } -inline Result Client::Put(const std::string &path, const char *body, - size_t content_length, + +inline Result Client::Put(const std::string &path) { + return cli_->Put(path); +} + +inline Result Client::Put(const std::string &path, + const char *body, + size_t content_length, const std::string &content_type) { - return cli_->Put(path, body, content_length, content_type); + return cli_->Put(path, body, content_length, content_type); } -inline Result Client::Put(const std::string &path, const Headers &headers, - const char *body, size_t content_length, + +inline Result Client::Put(const std::string &path, + const Headers &headers, + const char *body, + size_t content_length, const std::string &content_type) { - return cli_->Put(path, headers, body, content_length, content_type); + return cli_->Put(path, headers, body, content_length, content_type); } -inline Result Client::Put(const std::string &path, const std::string &body, - const std::string &content_type) { - return cli_->Put(path, body, content_type); + +inline Result Client::Put(const std::string &path, const std::string &body, const std::string &content_type) { + return cli_->Put(path, body, content_type); } -inline Result Client::Put(const std::string &path, const Headers &headers, + +inline Result Client::Put(const std::string &path, + const Headers &headers, const std::string &body, const std::string &content_type) { - return cli_->Put(path, headers, body, content_type); -} -inline Result Client::Put(const std::string &path, size_t content_length, - ContentProvider content_provider, - const std::string &content_type) { - return cli_->Put(path, content_length, std::move(content_provider), - content_type); + return cli_->Put(path, headers, body, content_type); } + inline Result Client::Put(const std::string &path, + size_t content_length, + ContentProvider content_provider, + const std::string &content_type) { + return cli_->Put(path, content_length, std::move(content_provider), content_type); +} + +inline Result Client::Put(const std::string &path, ContentProviderWithoutLength content_provider, - const std::string &content_type) { - return cli_->Put(path, std::move(content_provider), content_type); + const std::string &content_type) { + return cli_->Put(path, std::move(content_provider), content_type); } -inline Result Client::Put(const std::string &path, const Headers &headers, - size_t content_length, - ContentProvider content_provider, + +inline Result Client::Put(const std::string &path, + const Headers &headers, + size_t content_length, + ContentProvider content_provider, const std::string &content_type) { - return cli_->Put(path, headers, content_length, std::move(content_provider), - content_type); + return cli_->Put(path, headers, content_length, std::move(content_provider), content_type); } -inline Result Client::Put(const std::string &path, const Headers &headers, + +inline Result Client::Put(const std::string &path, + const Headers &headers, ContentProviderWithoutLength content_provider, - const std::string &content_type) { - return cli_->Put(path, headers, std::move(content_provider), content_type); + const std::string &content_type) { + return cli_->Put(path, headers, std::move(content_provider), content_type); } + inline Result Client::Put(const std::string &path, const Params ¶ms) { - return cli_->Put(path, params); + return cli_->Put(path, params); } -inline Result Client::Put(const std::string &path, const Headers &headers, - const Params ¶ms) { - return cli_->Put(path, headers, params); + +inline Result Client::Put(const std::string &path, const Headers &headers, const Params ¶ms) { + return cli_->Put(path, headers, params); } -inline Result Client::Put(const std::string &path, - const MultipartFormDataItems &items) { - return cli_->Put(path, items); + +inline Result Client::Put(const std::string &path, const MultipartFormDataItems &items) { + return cli_->Put(path, items); } -inline Result Client::Put(const std::string &path, const Headers &headers, - const MultipartFormDataItems &items) { - return cli_->Put(path, headers, items); + +inline Result Client::Put(const std::string &path, const Headers &headers, const MultipartFormDataItems &items) { + return cli_->Put(path, headers, items); } -inline Result Client::Put(const std::string &path, const Headers &headers, + +inline Result Client::Put(const std::string &path, + const Headers &headers, const MultipartFormDataItems &items, - const std::string &boundary) { - return cli_->Put(path, headers, items, boundary); + const std::string &boundary) { + return cli_->Put(path, headers, items, boundary); } -inline Result -Client::Put(const std::string &path, const Headers &headers, - const MultipartFormDataItems &items, - const MultipartFormDataProviderItems &provider_items) { - return cli_->Put(path, headers, items, provider_items); + +inline Result Client::Put(const std::string &path, + const Headers &headers, + const MultipartFormDataItems &items, + const MultipartFormDataProviderItems &provider_items) { + return cli_->Put(path, headers, items, provider_items); } + inline Result Client::Patch(const std::string &path) { - return cli_->Patch(path); + return cli_->Patch(path); } -inline Result Client::Patch(const std::string &path, const char *body, - size_t content_length, + +inline Result Client::Patch(const std::string &path, + const char *body, + size_t content_length, const std::string &content_type) { - return cli_->Patch(path, body, content_length, content_type); + return cli_->Patch(path, body, content_length, content_type); } -inline Result Client::Patch(const std::string &path, const Headers &headers, - const char *body, size_t content_length, + +inline Result Client::Patch(const std::string &path, + const Headers &headers, + const char *body, + size_t content_length, const std::string &content_type) { - return cli_->Patch(path, headers, body, content_length, content_type); + return cli_->Patch(path, headers, body, content_length, content_type); } -inline Result Client::Patch(const std::string &path, const std::string &body, - const std::string &content_type) { - return cli_->Patch(path, body, content_type); + +inline Result Client::Patch(const std::string &path, const std::string &body, const std::string &content_type) { + return cli_->Patch(path, body, content_type); } -inline Result Client::Patch(const std::string &path, const Headers &headers, + +inline Result Client::Patch(const std::string &path, + const Headers &headers, const std::string &body, const std::string &content_type) { - return cli_->Patch(path, headers, body, content_type); -} -inline Result Client::Patch(const std::string &path, size_t content_length, - ContentProvider content_provider, - const std::string &content_type) { - return cli_->Patch(path, content_length, std::move(content_provider), - content_type); + return cli_->Patch(path, headers, body, content_type); } + inline Result Client::Patch(const std::string &path, + size_t content_length, + ContentProvider content_provider, + const std::string &content_type) { + return cli_->Patch(path, content_length, std::move(content_provider), content_type); +} + +inline Result Client::Patch(const std::string &path, ContentProviderWithoutLength content_provider, - const std::string &content_type) { - return cli_->Patch(path, std::move(content_provider), content_type); + const std::string &content_type) { + return cli_->Patch(path, std::move(content_provider), content_type); } -inline Result Client::Patch(const std::string &path, const Headers &headers, - size_t content_length, - ContentProvider content_provider, + +inline Result Client::Patch(const std::string &path, + const Headers &headers, + size_t content_length, + ContentProvider content_provider, const std::string &content_type) { - return cli_->Patch(path, headers, content_length, std::move(content_provider), - content_type); + return cli_->Patch(path, headers, content_length, std::move(content_provider), content_type); } -inline Result Client::Patch(const std::string &path, const Headers &headers, + +inline Result Client::Patch(const std::string &path, + const Headers &headers, ContentProviderWithoutLength content_provider, - const std::string &content_type) { - return cli_->Patch(path, headers, std::move(content_provider), content_type); + const std::string &content_type) { + return cli_->Patch(path, headers, std::move(content_provider), content_type); } + inline Result Client::Delete(const std::string &path) { - return cli_->Delete(path); + return cli_->Delete(path); } + inline Result Client::Delete(const std::string &path, const Headers &headers) { - return cli_->Delete(path, headers); + return cli_->Delete(path, headers); } -inline Result Client::Delete(const std::string &path, const char *body, - size_t content_length, + +inline Result Client::Delete(const std::string &path, + const char *body, + size_t content_length, const std::string &content_type) { - return cli_->Delete(path, body, content_length, content_type); + return cli_->Delete(path, body, content_length, content_type); } -inline Result Client::Delete(const std::string &path, const Headers &headers, - const char *body, size_t content_length, + +inline Result Client::Delete(const std::string &path, + const Headers &headers, + const char *body, + size_t content_length, const std::string &content_type) { - return cli_->Delete(path, headers, body, content_length, content_type); + return cli_->Delete(path, headers, body, content_length, content_type); } -inline Result Client::Delete(const std::string &path, const std::string &body, - const std::string &content_type) { - return cli_->Delete(path, body, content_type); + +inline Result Client::Delete(const std::string &path, const std::string &body, const std::string &content_type) { + return cli_->Delete(path, body, content_type); } -inline Result Client::Delete(const std::string &path, const Headers &headers, + +inline Result Client::Delete(const std::string &path, + const Headers &headers, const std::string &body, const std::string &content_type) { - return cli_->Delete(path, headers, body, content_type); + return cli_->Delete(path, headers, body, content_type); } + inline Result Client::Options(const std::string &path) { - return cli_->Options(path); + return cli_->Options(path); } + inline Result Client::Options(const std::string &path, const Headers &headers) { - return cli_->Options(path, headers); + return cli_->Options(path, headers); } inline bool Client::send(Request &req, Response &res, Error &error) { - return cli_->send(req, res, error); + return cli_->send(req, res, error); } -inline Result Client::send(const Request &req) { return cli_->send(req); } +inline Result Client::send(const Request &req) { + return cli_->send(req); +} -inline void Client::stop() { cli_->stop(); } +inline void Client::stop() { + cli_->stop(); +} -inline std::string Client::host() const { return cli_->host(); } +inline std::string Client::host() const { + return cli_->host(); +} -inline int Client::port() const { return cli_->port(); } +inline int Client::port() const { + return cli_->port(); +} -inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); } +inline size_t Client::is_socket_open() const { + return cli_->is_socket_open(); +} -inline socket_t Client::socket() const { return cli_->socket(); } +inline socket_t Client::socket() const { + return cli_->socket(); +} -inline void -Client::set_hostname_addr_map(std::map addr_map) { - cli_->set_hostname_addr_map(std::move(addr_map)); +inline void Client::set_hostname_addr_map(std::map addr_map) { + cli_->set_hostname_addr_map(std::move(addr_map)); } inline void Client::set_default_headers(Headers headers) { - cli_->set_default_headers(std::move(headers)); + cli_->set_default_headers(std::move(headers)); } inline void Client::set_address_family(int family) { - cli_->set_address_family(family); + cli_->set_address_family(family); } -inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); } +inline void Client::set_tcp_nodelay(bool on) { + cli_->set_tcp_nodelay(on); +} inline void Client::set_socket_options(SocketOptions socket_options) { - cli_->set_socket_options(std::move(socket_options)); + cli_->set_socket_options(std::move(socket_options)); } inline void Client::set_connection_timeout(time_t sec, time_t usec) { - cli_->set_connection_timeout(sec, usec); + cli_->set_connection_timeout(sec, usec); } inline void Client::set_read_timeout(time_t sec, time_t usec) { - cli_->set_read_timeout(sec, usec); + cli_->set_read_timeout(sec, usec); } inline void Client::set_write_timeout(time_t sec, time_t usec) { - cli_->set_write_timeout(sec, usec); + cli_->set_write_timeout(sec, usec); } -inline void Client::set_basic_auth(const std::string &username, - const std::string &password) { - cli_->set_basic_auth(username, password); +inline void Client::set_basic_auth(const std::string &username, const std::string &password) { + cli_->set_basic_auth(username, password); } + inline void Client::set_bearer_token_auth(const std::string &token) { - cli_->set_bearer_token_auth(token); + cli_->set_bearer_token_auth(token); } #ifdef CPPHTTPLIB_OPENSSL_SUPPORT -inline void Client::set_digest_auth(const std::string &username, - const std::string &password) { - cli_->set_digest_auth(username, password); +inline void Client::set_digest_auth(const std::string &username, const std::string &password) { + cli_->set_digest_auth(username, password); } #endif -inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); } -inline void Client::set_follow_location(bool on) { - cli_->set_follow_location(on); +inline void Client::set_keep_alive(bool on) { + cli_->set_keep_alive(on); } -inline void Client::set_url_encode(bool on) { cli_->set_url_encode(on); } +inline void Client::set_follow_location(bool on) { + cli_->set_follow_location(on); +} -inline void Client::set_compress(bool on) { cli_->set_compress(on); } +inline void Client::set_url_encode(bool on) { + cli_->set_url_encode(on); +} -inline void Client::set_decompress(bool on) { cli_->set_decompress(on); } +inline void Client::set_compress(bool on) { + cli_->set_compress(on); +} + +inline void Client::set_decompress(bool on) { + cli_->set_decompress(on); +} inline void Client::set_interface(const std::string &intf) { - cli_->set_interface(intf); + cli_->set_interface(intf); } inline void Client::set_proxy(const std::string &host, int port) { - cli_->set_proxy(host, port); + cli_->set_proxy(host, port); } -inline void Client::set_proxy_basic_auth(const std::string &username, - const std::string &password) { - cli_->set_proxy_basic_auth(username, password); + +inline void Client::set_post_connect_cb(detail::POSTSOCKETCONNECTCB cb) { + cli_->set_post_connect_callback(cb); } + +inline void Client::set_proxy_basic_auth(const std::string &username, const std::string &password) { + cli_->set_proxy_basic_auth(username, password); +} + inline void Client::set_proxy_bearer_token_auth(const std::string &token) { - cli_->set_proxy_bearer_token_auth(token); + cli_->set_proxy_bearer_token_auth(token); } #ifdef CPPHTTPLIB_OPENSSL_SUPPORT -inline void Client::set_proxy_digest_auth(const std::string &username, - const std::string &password) { - cli_->set_proxy_digest_auth(username, password); +inline void Client::set_proxy_digest_auth(const std::string &username, const std::string &password) { + cli_->set_proxy_digest_auth(username, password); } #endif #ifdef CPPHTTPLIB_OPENSSL_SUPPORT inline void Client::enable_server_certificate_verification(bool enabled) { - cli_->enable_server_certificate_verification(enabled); + cli_->enable_server_certificate_verification(enabled); } #endif inline void Client::set_logger(Logger logger) { - cli_->set_logger(std::move(logger)); + cli_->set_logger(std::move(logger)); } #ifdef CPPHTTPLIB_OPENSSL_SUPPORT -inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path, - const std::string &ca_cert_dir_path) { - cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path); +inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path, const std::string &ca_cert_dir_path) { + cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path); } inline void Client::set_ca_cert_store(X509_STORE *ca_cert_store) { - if (is_ssl_) { - static_cast(*cli_).set_ca_cert_store(ca_cert_store); - } else { - cli_->set_ca_cert_store(ca_cert_store); - } + if (is_ssl_) { + static_cast(*cli_).set_ca_cert_store(ca_cert_store); + } else { + cli_->set_ca_cert_store(ca_cert_store); + } } inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) { - set_ca_cert_store(cli_->create_ca_cert_store(ca_cert, size)); + set_ca_cert_store(cli_->create_ca_cert_store(ca_cert, size)); } inline long Client::get_openssl_verify_result() const { - if (is_ssl_) { - return static_cast(*cli_).get_openssl_verify_result(); - } - return -1; // NOTE: -1 doesn't match any of X509_V_ERR_??? + if (is_ssl_) { + return static_cast(*cli_).get_openssl_verify_result(); + } + return -1; // NOTE: -1 doesn't match any of X509_V_ERR_??? } inline SSL_CTX *Client::ssl_context() const { - if (is_ssl_) { return static_cast(*cli_).ssl_context(); } - return nullptr; + if (is_ssl_) { + return static_cast(*cli_).ssl_context(); + } + return nullptr; } #endif // ---------------------------------------------------------------------------- -} // namespace httplib +} // namespace httplib #if defined(_WIN32) && defined(CPPHTTPLIB_USE_POLL) #undef poll #endif -#endif // CPPHTTPLIB_HTTPLIB_H +#endif // CPPHTTPLIB_HTTPLIB_H \ No newline at end of file diff --git a/NetTunnelSDK/ipcalc.cpp b/NetTunnelSDK/ipcalc.cpp index e154034..0646068 100644 --- a/NetTunnelSDK/ipcalc.cpp +++ b/NetTunnelSDK/ipcalc.cpp @@ -7,6 +7,7 @@ #include "usrerr.h" #include "misc.h" +#include "tunnel.h" static const TCHAR *p2_table(unsigned pow) { static const TCHAR *pow2[] = { @@ -145,22 +146,6 @@ static const TCHAR *p2_table(unsigned pow) { return TEXT(""); } -TCHAR *safe_strdup(const TCHAR *str) { - TCHAR *ret; - - if (!str) { - return nullptr; - } - - ret = _strdup(str); - if (!ret) { - SPDLOG_ERROR(TEXT("Memory allocation string failure:{0}"), str); - return nullptr; - } - - return ret; -} - static int vasprintf(TCHAR **strp, const TCHAR *fmt, va_list ap) { // _vscprintf tells you how big the buffer needs to be const int len = _vscprintf(fmt, ap); @@ -331,8 +316,8 @@ static int GetIpV4Info(const TCHAR *pIpStr, int prefix, PIP_INFO pInfo, unsigned /* Handle CIDR entries such as 172/8 */ if (prefix >= 0) { - auto tmp = const_cast(ipStr); - int i; + auto tmp = const_cast(ipStr); + int i; for (i = 3; i > 0; i--) { tmp = strchr(tmp, '.'); @@ -367,7 +352,7 @@ static int GetIpV4Info(const TCHAR *pIpStr, int prefix, PIP_INFO pInfo, unsigned free(ipStr); return -ERR_UN_SUPPORT; } - pInfo->ip = safe_strdup(namebuf); + StringCbCopy(pInfo->ip, MAX_IP_LEN, namebuf); netmask.s_addr = prefix2mask(prefix); memset(namebuf, '\0', sizeof(namebuf)); @@ -377,8 +362,9 @@ static int GetIpV4Info(const TCHAR *pIpStr, int prefix, PIP_INFO pInfo, unsigned free(ipStr); return -ERR_UN_SUPPORT; } - pInfo->netmask = safe_strdup(namebuf); - pInfo->prefix = prefix; + StringCbCopy(pInfo->netmask, MAX_IP_LEN, namebuf); + + pInfo->prefix = prefix; broadcast = calc_broadcast(ip, prefix); @@ -388,7 +374,8 @@ static int GetIpV4Info(const TCHAR *pIpStr, int prefix, PIP_INFO pInfo, unsigned free(ipStr); return -ERR_UN_SUPPORT; } - pInfo->broadcast = safe_strdup(namebuf); + + StringCbCopy(pInfo->broadcast, MAX_IP_LEN, namebuf); network = calc_network(ip, prefix); @@ -399,7 +386,7 @@ static int GetIpV4Info(const TCHAR *pIpStr, int prefix, PIP_INFO pInfo, unsigned return -ERR_UN_SUPPORT; } - pInfo->network = safe_strdup(namebuf); + StringCbCopy(pInfo->network, MAX_IP_LEN, namebuf); if (prefix < 32) { memcpy(&minhost, &network, sizeof(minhost)); @@ -412,7 +399,7 @@ static int GetIpV4Info(const TCHAR *pIpStr, int prefix, PIP_INFO pInfo, unsigned free(ipStr); return -ERR_UN_SUPPORT; } - pInfo->hostmin = safe_strdup(namebuf); + StringCbCopy(pInfo->hostmin, MAX_IP_LEN, namebuf); memcpy(&maxhost, &network, sizeof(minhost)); maxhost.s_addr |= ~netmask.s_addr; @@ -425,10 +412,10 @@ static int GetIpV4Info(const TCHAR *pIpStr, int prefix, PIP_INFO pInfo, unsigned return -ERR_UN_SUPPORT; } - pInfo->hostmax = safe_strdup(namebuf); + StringCbCopy(pInfo->hostmax, MAX_IP_LEN, namebuf); } else { - pInfo->hostmin = pInfo->network; - pInfo->hostmax = pInfo->network; + StringCbCopy(pInfo->hostmin, MAX_IP_LEN, pInfo->network); + StringCbCopy(pInfo->hostmax, MAX_IP_LEN, pInfo->network); } ipv4_prefix_to_hosts(pInfo->hosts, sizeof(pInfo->hosts), prefix); @@ -452,7 +439,7 @@ int GetIpV4InfoFromCIDR(const TCHAR *pIpStr, PIP_INFO pInfo) { TCHAR *prefixStr; TCHAR *ipStr = _strdup(pIpStr); - if (pIpStr == nullptr || lstrlen(pIpStr) < 8) { + if (pIpStr == nullptr || lstrlen(pIpStr) < MIN_IP_LEN) { SPDLOG_ERROR(TEXT("Input pIpStr format error: {}."), pIpStr); return -ERR_INPUT_PARAMS; } @@ -498,12 +485,12 @@ int GetIpV4InfoFromCIDR(const TCHAR *pIpStr, PIP_INFO pInfo) { int GetIpV4InfoFromNetmask(const TCHAR *pIpStr, const TCHAR *pNetmask, PIP_INFO pInfo) { int prefix; - if (pIpStr == nullptr || lstrlen(pIpStr) < 8) { + if (pIpStr == nullptr || lstrlen(pIpStr) < MIN_IP_LEN) { SPDLOG_ERROR(TEXT("Input pIpStr format error: {}."), pIpStr); return -ERR_INPUT_PARAMS; } - if (pNetmask == nullptr || lstrlen(pNetmask) < 8) { + if (pNetmask == nullptr || lstrlen(pNetmask) < MIN_IP_LEN) { SPDLOG_ERROR(TEXT("Input pNetmask format error: {}."), pNetmask); return -ERR_INPUT_PARAMS; } @@ -513,6 +500,39 @@ int GetIpV4InfoFromNetmask(const TCHAR *pIpStr, const TCHAR *pNetmask, PIP_INFO return -ERR_INPUT_PARAMS; } - prefix = ipv4_mask_to_int(pNetmask); + prefix = ipv4_mask_to_int(pNetmask); return GetIpV4Info(pIpStr, prefix, pInfo, 0); +} + +int GetIpV4InfoFromHostname(int family, const char *host, PIP_INFO pInfo) { + addrinfo *res, *rp; + addrinfo hints {}; + int err; + static char ipname[64]; + void *addr; + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = family; + + err = getaddrinfo(host, nullptr, &hints, &res); + if (err != 0) { + return -ERR_INPUT_PARAMS; + } + + for (rp = res; rp != nullptr; rp = rp->ai_next) { + if (rp->ai_family == AF_INET) { + addr = (&reinterpret_cast(rp->ai_addr)->sin_addr); + } else { + addr = (&reinterpret_cast(rp->ai_addr)->sin6_addr); + } + + if (inet_ntop(rp->ai_family, addr, ipname, sizeof(ipname)) != nullptr) { + freeaddrinfo(res); + StringCbCopy(pInfo->hostip, MAX_IP_LEN, ipname); + return ERR_SUCCESS; + } + } + + freeaddrinfo(res); + return ERR_ITEM_EXISTS; } \ No newline at end of file diff --git a/NetTunnelSDK/misc.h b/NetTunnelSDK/misc.h index a8ac87b..7e47ed9 100644 --- a/NetTunnelSDK/misc.h +++ b/NetTunnelSDK/misc.h @@ -1,5 +1,7 @@ #pragma once +#include "tunnel.h" + #include #define CFG_WIREGUARD_SECTION TEXT("WireGuard") @@ -20,14 +22,15 @@ typedef struct { * @brief IPv4 网络信息 */ typedef struct { - TCHAR *ip; ///< IP 地址 - TCHAR *network; ///< 网络地址 - TCHAR *broadcast; ///< 网络广播地址 - TCHAR *netmask; ///< 网络子网掩码 - TCHAR hosts[64]; ///< number of hosts in text - unsigned int prefix; ///< 网络前缀 - TCHAR *hostmin; ///< 最小网络主机 IP - TCHAR *hostmax; ///< 最大网络主机 IP + unsigned int prefix; ///< 网络前缀 + TCHAR hostip[MAX_IP_LEN]; ///< IP 地址 + TCHAR ip[MAX_IP_LEN]; ///< IP 地址 + TCHAR network[MAX_IP_LEN]; ///< 网络地址 + TCHAR broadcast[MAX_IP_LEN]; ///< 网络广播地址 + TCHAR netmask[MAX_IP_LEN]; ///< 网络子网掩码 + TCHAR hosts[64]; ///< number of hosts in text + TCHAR hostmin[MAX_IP_LEN]; ///< 最小网络主机 IP + TCHAR hostmax[MAX_IP_LEN]; ///< 最大网络主机 IP } IP_INFO, *PIP_INFO; #ifdef __cplusplus // If used by C++ code, @@ -103,6 +106,8 @@ int GetIpV4InfoFromNetmask(const TCHAR *pIpStr, const TCHAR *pNetmask, PIP_INFO * - ERR_SUCCESS 成功 */ int GetIpV4InfoFromCIDR(const TCHAR *pIpStr, PIP_INFO pInfo); + +int GetIpV4InfoFromHostname(int family, const char *host, PIP_INFO pInfo); #ifdef __cplusplus } #endif \ No newline at end of file diff --git a/NetTunnelSDK/network.cpp b/NetTunnelSDK/network.cpp index 09101f9..95747ca 100644 --- a/NetTunnelSDK/network.cpp +++ b/NetTunnelSDK/network.cpp @@ -21,34 +21,67 @@ static NIC_CONTENT g_NetAdapterInfo[NET_CARD_MAX]; -static const TCHAR *g_TabCIDR[] = { - TEXT("128.0.0.0"), TEXT("192.0.0.0"), TEXT("224.0.0.0"), TEXT("240.0.0.0"), - TEXT("248.0.0.0"), TEXT("252.0.0.0"), TEXT("254.0.0.0"), TEXT("255.0.0.0"), - TEXT("255.128.0.0"), TEXT("255.192.0.0"), TEXT("255.224.0.0"), TEXT("255.240.0.0"), - TEXT("255.248.0.0"), TEXT("255.252.0.0"), TEXT("255.254.0.0"), TEXT("255.255.0.0"), - TEXT("255.255.128.0"), TEXT("255.255.192.0"), TEXT("255.255.224.0"), TEXT("255.255.240.0"), - TEXT("255.255.248.0"), TEXT("255.255.252.0"), TEXT("255.255.254.0"), TEXT("255.255.255.0"), - TEXT("255.255.255.128"), TEXT("255.255.255.192"), TEXT("255.255.255.224"), TEXT("255.255.255.240"), - TEXT("255.255.255.248"), TEXT("255.255.255.252"), TEXT("255.255.255.254"), TEXT("255.255.255.255")}; +int GetInterfaceIfIndexByIpAddr(const TCHAR *pIpAddr, ULONG *pIfIndex) { + PIP_ADAPTER_INFO pAdapterInfo; + DWORD dwRetVal; + ULONG ulOutBufLen; -int NetmaskToCIDR(const TCHAR *pNetMask) { + if (pIpAddr == nullptr || lstrlen(pIpAddr) == 0) { + SPDLOG_ERROR(TEXT("Input pIpAddr error: {0}"), pIpAddr); + return -ERR_INPUT_PARAMS; + } - for (int i = 0; i < static_cast(std::size(g_TabCIDR)); i++) { - if (lstrcmp(g_TabCIDR[i], pNetMask) == 0) { - return i + 1; + if (pIfIndex == nullptr) { + SPDLOG_ERROR(TEXT("Input pIfIndex params error")); + return -ERR_INPUT_PARAMS; + } + + ulOutBufLen = sizeof(IP_ADAPTER_INFO); + pAdapterInfo = static_cast(HeapAlloc(GetProcessHeap(), 0, sizeof(IP_ADAPTER_INFO))); + + if (pAdapterInfo == nullptr) { + SPDLOG_ERROR(TEXT("Error allocating memory needed to call GetAdaptersinfo")); + return -ERR_MALLOC_MEMORY; + } + + if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) { + HeapFree(GetProcessHeap(), 0, pAdapterInfo); + pAdapterInfo = static_cast(HeapAlloc(GetProcessHeap(), 0, ulOutBufLen)); + if (pAdapterInfo == nullptr) { + SPDLOG_ERROR(TEXT("Error allocating memory needed to call GetAdaptersinfo\n")); + return -ERR_MALLOC_MEMORY; } } - return 0xFF; -} + *pIfIndex = -1; -const TCHAR *CIDRToNetmask(const UINT8 cidr) { + if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen)) == NO_ERROR) { + PIP_ADAPTER_INFO pAdapter = pAdapterInfo; + while (pAdapter) { + PIP_ADDR_STRING ipAddressListPointer = &(pAdapter->IpAddressList); - if (cidr >= 1 && cidr <= std::size(g_TabCIDR)) { - return g_TabCIDR[cidr - 1]; + while (ipAddressListPointer != nullptr) { + if (StrCmp((ipAddressListPointer->IpAddress).String, pIpAddr) == 0) { + *pIfIndex = pAdapter->Index; + HeapFree(GetProcessHeap(), 0, pAdapterInfo); + return ERR_SUCCESS; + } else { + ipAddressListPointer = ipAddressListPointer->Next; + } + } + pAdapter = pAdapter->Next; + } + } else { + SPDLOG_ERROR(TEXT("GetAdaptersInfo failed with error: {0}\n"), dwRetVal); + HeapFree(GetProcessHeap(), 0, pAdapterInfo); + return -ERR_SYS_CALL; } - return TEXT(""); + if (pAdapterInfo) { + HeapFree(GetProcessHeap(), 0, pAdapterInfo); + } + + return -ERR_ITEM_UNEXISTS; } int GetInterfaceIfIndexByGUID(const TCHAR *pGUID, int *pIfIndex) { @@ -87,7 +120,6 @@ int GetInterfaceIfIndexByGUID(const TCHAR *pGUID, int *pIfIndex) { if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen)) == NO_ERROR) { PIP_ADAPTER_INFO pAdapter = pAdapterInfo; while (pAdapter) { - if (StrCmp(pAdapter->AdapterName, pGUID) == 0) { *pIfIndex = static_cast(pAdapter->Index); HeapFree(GetProcessHeap(), 0, pAdapterInfo); @@ -202,52 +234,266 @@ int GetInterfaceNameByGUID(const TCHAR *pGUID, TCHAR ifName[MAX_NETCARD_NAME]) { return ERR_ITEM_UNEXISTS; } -int GetInternetIfName(TCHAR ifName[MAX_NETCARD_NAME]) { - for (int i = 0; i < NET_CARD_MAX; i++) { - const PNIC_CONTENT pNic = &g_NetAdapterInfo[i]; +int GetInternetIfIndex(int *pIfIndex) { + PIP_ADAPTER_INFO pAdapterInfo; + DWORD dwRetVal; + ULONG ulOutBufLen; - bool bIsInternel; + if (pIfIndex == nullptr) { + SPDLOG_ERROR(TEXT("Input pIfIndex params error")); + return -ERR_INPUT_PARAMS; + } - if (ERR_SUCCESS == IsInternetConnectAdapter(pNic->InterfaceIndex, &bIsInternel) && bIsInternel) { - StringCbCopy(ifName, MAX_NETCARD_NAME, pNic->NetCardName); - return ERR_SUCCESS; + ulOutBufLen = sizeof(IP_ADAPTER_INFO); + pAdapterInfo = static_cast(HeapAlloc(GetProcessHeap(), 0, sizeof(IP_ADAPTER_INFO))); + + if (pAdapterInfo == nullptr) { + SPDLOG_ERROR(TEXT("Error allocating memory needed to call GetAdaptersinfo")); + return -ERR_MALLOC_MEMORY; + } + + if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) { + HeapFree(GetProcessHeap(), 0, pAdapterInfo); + pAdapterInfo = static_cast(HeapAlloc(GetProcessHeap(), 0, ulOutBufLen)); + if (pAdapterInfo == nullptr) { + SPDLOG_ERROR(TEXT("Error allocating memory needed to call GetAdaptersinfo\n")); + return -ERR_MALLOC_MEMORY; } } + *pIfIndex = -1; + + if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen)) == NO_ERROR) { + PIP_ADAPTER_INFO pAdapter = pAdapterInfo; + while (pAdapter) { + bool bIsInternel; + int index = static_cast(pAdapter->Index); + + int ret = IsInternetConnectAdapter(index, &bIsInternel); + + if (ret != ERR_SUCCESS) { + SPDLOG_ERROR(TEXT("IsInternetConnectAdapter {0} : {1}\n"), index, ret); + } + + if (ret == ERR_SUCCESS && bIsInternel) { + *pIfIndex = index; + HeapFree(GetProcessHeap(), 0, pAdapterInfo); + return ERR_SUCCESS; + } + + pAdapter = pAdapter->Next; + } + } else { + SPDLOG_ERROR(TEXT("GetAdaptersInfo failed with error: {0}\n"), dwRetVal); + HeapFree(GetProcessHeap(), 0, pAdapterInfo); + return -ERR_SYS_CALL; + } + + if (pAdapterInfo) { + HeapFree(GetProcessHeap(), 0, pAdapterInfo); + } + + return -ERR_ITEM_UNEXISTS; +} + +int GetInterfaceGUIDByIfIndex(const int ifIndex, GUID *pGuid) { + PIP_ADAPTER_INFO pAdapterInfo; + DWORD dwRetVal; + ULONG ulOutBufLen; + if (pGuid == nullptr) { + SPDLOG_ERROR(TEXT("Input pGuid error.")); + return -ERR_INPUT_PARAMS; + } + + ulOutBufLen = sizeof(IP_ADAPTER_INFO); + pAdapterInfo = static_cast(HeapAlloc(GetProcessHeap(), 0, sizeof(IP_ADAPTER_INFO))); + + if (pAdapterInfo == nullptr) { + SPDLOG_ERROR(TEXT("Error allocating memory needed to call GetAdaptersinfo")); + return -ERR_MALLOC_MEMORY; + } + + if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) { + HeapFree(GetProcessHeap(), 0, pAdapterInfo); + pAdapterInfo = static_cast(HeapAlloc(GetProcessHeap(), 0, ulOutBufLen)); + if (pAdapterInfo == nullptr) { + SPDLOG_ERROR(TEXT("Error allocating memory needed to call GetAdaptersinfo")); + return -ERR_MALLOC_MEMORY; + } + } + + if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen)) == NO_ERROR) { + PIP_ADAPTER_INFO pAdapter = pAdapterInfo; + while (pAdapter) { + if (ifIndex == static_cast(pAdapter->Index)) { + int ret; + WCHAR strGuid[MAX_PATH]; + + if ((ret = TCharToWideChar(pAdapter->AdapterName, strGuid, MAX_PATH)) != ERR_SUCCESS) { + HeapFree(GetProcessHeap(), 0, pAdapterInfo); + return ret; + } + + if (CLSIDFromString(strGuid, pGuid) != NOERROR) { + HeapFree(GetProcessHeap(), 0, pAdapterInfo); + return -ERR_MEMORY_STR; + } + + HeapFree(GetProcessHeap(), 0, pAdapterInfo); + return ERR_SUCCESS; + } + pAdapter = pAdapter->Next; + } + } else { + SPDLOG_ERROR(TEXT("GetAdaptersInfo failed with error: {0}"), dwRetVal); + HeapFree(GetProcessHeap(), 0, pAdapterInfo); + return -ERR_SYS_CALL; + } + + if (pAdapterInfo) { + HeapFree(GetProcessHeap(), 0, pAdapterInfo); + } + + return -ERR_ITEM_UNEXISTS; +} + +/** + * @brief ȡ + * @param[in] pInterfaceName + * @param[out] pIfIndex Index + * @return ִн 0: ɹ С0 ʧ @see USER_ERRNO + * - -ERR_INPUT_PARAMS + * - -ERR_ITEM_UNEXISTS + * - -ERR_SYS_CALL ȡϵͳʧ + * - -ERR_MALLOC_MEMORY ڴʧ + * - ERR_SUCCESS ɹ + */ +int GetInterfaceIfIndexByName(const TCHAR *pInterfaceName, int *pIfIndex) { + PIP_ADAPTER_INFO pAdapterInfo; + DWORD dwRetVal; + ULONG ulOutBufLen; + + if (pInterfaceName == nullptr || lstrlen(pInterfaceName) == 0) { + SPDLOG_ERROR(TEXT("Input pInterfaceName error: {0}"), pInterfaceName); + return -ERR_INPUT_PARAMS; + } + + if (pIfIndex == nullptr) { + SPDLOG_ERROR(TEXT("Input pIfIndex params error.")); + return -ERR_INPUT_PARAMS; + } + + ulOutBufLen = sizeof(IP_ADAPTER_INFO); + pAdapterInfo = static_cast(HeapAlloc(GetProcessHeap(), 0, sizeof(IP_ADAPTER_INFO))); + + if (pAdapterInfo == nullptr) { + SPDLOG_ERROR(TEXT("Error allocating memory needed to call GetAdaptersinfo")); + return -ERR_MALLOC_MEMORY; + } + + if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) { + HeapFree(GetProcessHeap(), 0, pAdapterInfo); + pAdapterInfo = static_cast(HeapAlloc(GetProcessHeap(), 0, ulOutBufLen)); + if (pAdapterInfo == nullptr) { + SPDLOG_ERROR(TEXT("Error allocating memory needed to call GetAdaptersinfo\n")); + return -ERR_MALLOC_MEMORY; + } + } + + *pIfIndex = -1; + + if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen)) == NO_ERROR) { + PIP_ADAPTER_INFO pAdapter = pAdapterInfo; + while (pAdapter) { + TCHAR NetCardName[MAX_NETCARD_NAME] = {}; + GetInterfaceNameByGUID(pAdapter->AdapterName, NetCardName); + + if (StrCmp(pInterfaceName, NetCardName) == 0) { + *pIfIndex = static_cast(pAdapter->Index); + HeapFree(GetProcessHeap(), 0, pAdapterInfo); + return ERR_SUCCESS; + } + + pAdapter = pAdapter->Next; + } + } else { + SPDLOG_ERROR(TEXT("GetAdaptersInfo failed with error: {0}\n"), dwRetVal); + HeapFree(GetProcessHeap(), 0, pAdapterInfo); + return -ERR_SYS_CALL; + } + + if (pAdapterInfo) { + HeapFree(GetProcessHeap(), 0, pAdapterInfo); + } + return -ERR_ITEM_UNEXISTS; } int GetInterfaceGUIDByName(const TCHAR *pInterfaceName, GUID *pGuid) { - int ret; + PIP_ADAPTER_INFO pAdapterInfo; + DWORD dwRetVal; + ULONG ulOutBufLen; if (pInterfaceName == nullptr || lstrlen(pInterfaceName) == 0) { - SPDLOG_ERROR(TEXT("Input pInterfaceName params error: {0}"), pInterfaceName); + SPDLOG_ERROR(TEXT("Input pInterfaceName error: {0}"), pInterfaceName); return -ERR_INPUT_PARAMS; } - if (lstrlen(g_NetAdapterInfo[0].NetCardUUID) == 0) { - PNIC_CONTENT nic; - int nItem; + if (pGuid == nullptr) { + SPDLOG_ERROR(TEXT("Input pGuid params error")); + return -ERR_INPUT_PARAMS; + } - if ((ret = GetAllNICInfo(&nic, &nItem)) != ERR_SUCCESS) { - return ret; + ulOutBufLen = sizeof(IP_ADAPTER_INFO); + pAdapterInfo = static_cast(HeapAlloc(GetProcessHeap(), 0, sizeof(IP_ADAPTER_INFO))); + + if (pAdapterInfo == nullptr) { + SPDLOG_ERROR(TEXT("Error allocating memory needed to call GetAdaptersinfo")); + return -ERR_MALLOC_MEMORY; + } + + if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) { + HeapFree(GetProcessHeap(), 0, pAdapterInfo); + pAdapterInfo = static_cast(HeapAlloc(GetProcessHeap(), 0, ulOutBufLen)); + if (pAdapterInfo == nullptr) { + SPDLOG_ERROR(TEXT("Error allocating memory needed to call GetAdaptersinfo\n")); + return -ERR_MALLOC_MEMORY; } } - for (const auto &v : g_NetAdapterInfo) { - if (StrCmp(pInterfaceName, v.NetCardName) == 0) { - WCHAR strGuid[MAX_PATH]; + if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen)) == NO_ERROR) { + PIP_ADAPTER_INFO pAdapter = pAdapterInfo; + while (pAdapter) { + int ret; + TCHAR NetCardName[MAX_NETCARD_NAME] = {}; + GetInterfaceNameByGUID(pAdapter->AdapterName, NetCardName); - if ((ret = TCharToWideChar(v.NetCardUUID, strGuid, MAX_PATH)) != ERR_SUCCESS) { - return ret; + if (StrCmp(pInterfaceName, NetCardName) == 0) { + WCHAR strGuid[MAX_PATH]; + + if ((ret = TCharToWideChar(pAdapter->AdapterName, strGuid, MAX_PATH)) != ERR_SUCCESS) { + HeapFree(GetProcessHeap(), 0, pAdapterInfo); + return ret; + } + + if (CLSIDFromString(strGuid, pGuid) != NOERROR) { + HeapFree(GetProcessHeap(), 0, pAdapterInfo); + return -ERR_MEMORY_STR; + } + HeapFree(GetProcessHeap(), 0, pAdapterInfo); + return ERR_SUCCESS; } - if (CLSIDFromString(strGuid, pGuid) != NOERROR) { - return -ERR_MEMORY_STR; - } - - return ERR_SUCCESS; + pAdapter = pAdapter->Next; } + } else { + SPDLOG_ERROR(TEXT("GetAdaptersInfo failed with error: {0}\n"), dwRetVal); + HeapFree(GetProcessHeap(), 0, pAdapterInfo); + return -ERR_SYS_CALL; + } + + if (pAdapterInfo) { + HeapFree(GetProcessHeap(), 0, pAdapterInfo); } return -ERR_ITEM_UNEXISTS; @@ -289,8 +535,8 @@ int WaitNetAdapterConnected(const TCHAR *pInterfaceName, int timeOutOfMs) { while (S_OK == pEnumConns->Next(1, &pIConn, nullptr)) { GUID adpterGuid; - pIConn->GetAdapterId(&adpterGuid); + pIConn->GetAdapterId(&adpterGuid); pIConn->GetNetwork(&pINet); if (pINet) { @@ -307,10 +553,19 @@ int WaitNetAdapterConnected(const TCHAR *pInterfaceName, int timeOutOfMs) { SysFreeString(sName); if (StrNCmp(pInterfaceName, ifName, lstrlen(pInterfaceName)) == 0) { - if (GetInterfaceGUIDByName(pInterfaceName, &guid) != ERR_SUCCESS) { + + int ret = GetInterfaceGUIDByName(pInterfaceName, &guid); + if (ret != ERR_SUCCESS) { + SPDLOG_ERROR(TEXT("Get Interface {0} GUID error: {1}"), pInterfaceName, ret); continue; } + /*SPDLOG_DEBUG(TEXT("Match Interface {0} --> {1}, Guid {2:x} --> {3:x}"), + ifName, + pInterfaceName, + adpterGuid.Data1, + guid.Data1);*/ + if (memcmp(&adpterGuid, &guid, sizeof(GUID)) == 0) { SPDLOG_DEBUG(TEXT("Interface {0}({1}) network connected now..."), ifName, pInterfaceName); return ERR_SUCCESS; @@ -468,7 +723,7 @@ int IsInternetConnectAdapter(int ifIndex, bool *pRet) { continue; } - if (StrCmp(ipStr, TEXT("0.0.0.0")) == 0 && StrCmp(maskStr, TEXT("0.0.0.0"))) { + if (StrCmp(ipStr, TEXT("0.0.0.0")) == 0 && StrCmp(maskStr, TEXT("0.0.0.0")) == 0) { *pRet = true; break; } @@ -595,7 +850,7 @@ int GetNetConnectionNetworkCategory(const TCHAR *pInterfaceName, bool *pIsPrivat return -ERR_ITEM_UNEXISTS; } -int SetNetConnectionSharing(const TCHAR *pInterfaceName, bool isEnable, bool isSetPrivate) { +int SetNetIntelnetConnectionSharing(int ifIndex, bool isEnable, bool isSetPrivate) { VARIANT v; INetConnection *pNC = nullptr; INetSharingConfiguration *pNSC = nullptr; @@ -604,10 +859,11 @@ int SetNetConnectionSharing(const TCHAR *pInterfaceName, bool isEnable, bool isS INetSharingEveryConnectionCollection *pNSECC = nullptr; INetSharingManager *pNSM; HRESULT hr; + GUID ifGuid; + int ret; - if (pInterfaceName == nullptr || lstrlen(pInterfaceName) == 0) { - SPDLOG_ERROR(TEXT("Input pInterfaceName params error: {0}"), pInterfaceName); - return -ERR_INPUT_PARAMS; + if ((ret = GetInterfaceGUIDByIfIndex(ifIndex, &ifGuid)) != ERR_SUCCESS) { + return ret; } hr = ::CoCreateInstance(CLSID_NetSharingManager, @@ -648,17 +904,11 @@ int SetNetConnectionSharing(const TCHAR *pInterfaceName, bool isEnable, bool isS if (V_VT(&v) == VT_UNKNOWN) { V_UNKNOWN(&v)->QueryInterface(IID_INetConnection, reinterpret_cast(&pNC)); if (pNC) { - TCHAR ifName[MAX_PATH]; NETCON_PROPERTIES *pNP; pNC->GetProperties(&pNP); - // ִַת - if (WideCharToTChar(pNP->pszwName, ifName, MAX_PATH) != ERR_SUCCESS) { - continue; - } - // ҵӦд - if (StrCmp(pInterfaceName, ifName) != 0) { + if (memcmp(&ifGuid, &pNP->guidId, sizeof(GUID)) != 0) { continue; } @@ -675,15 +925,32 @@ int SetNetConnectionSharing(const TCHAR *pInterfaceName, bool isEnable, bool isS if (pNSC) { if (isEnable) { - pNSC->DisableSharing(); + hr = pNSC->DisableSharing(); + + if (hr != S_OK) { + SPDLOG_ERROR(TEXT("INetSharingManager DisableSharing failed: {0}."), hr); + pNSC->Release(); + return -ERR_CALL_COMMOBJECT; + } Sleep(500); - pNSC->EnableSharing(isSetPrivate ? ICSSHARINGTYPE_PRIVATE : ICSSHARINGTYPE_PUBLIC); + hr = pNSC->EnableSharing(isSetPrivate ? ICSSHARINGTYPE_PRIVATE : ICSSHARINGTYPE_PUBLIC); + + if (hr != S_OK) { + SPDLOG_ERROR(TEXT("INetSharingManager EnableSharing failed: {0}."), hr); + pNSC->Release(); + return -ERR_CALL_COMMOBJECT; + } } else { - pNSC->DisableSharing(); + hr = pNSC->DisableSharing(); + + if (hr != S_OK) { + SPDLOG_ERROR(TEXT("INetSharingManager DisableSharing failed: {0}."), hr); + pNSC->Release(); + return -ERR_CALL_COMMOBJECT; + } } pNSC->Release(); - return ERR_SUCCESS; } } @@ -693,7 +960,7 @@ int SetNetConnectionSharing(const TCHAR *pInterfaceName, bool isEnable, bool isS return ERR_ITEM_UNEXISTS; } -int GetNetConnectionSharing(const TCHAR *pInterfaceName, bool *pIsEnable) { +int GetNetIntelnetConnectionSharing(int ifIndex, bool *pIsEnable) { VARIANT v; INetConnection *pNC = nullptr; INetSharingConfiguration *pNSC = nullptr; @@ -702,17 +969,19 @@ int GetNetConnectionSharing(const TCHAR *pInterfaceName, bool *pIsEnable) { INetSharingEveryConnectionCollection *pNSECC = nullptr; INetSharingManager *pNSM; HRESULT hr; - - if (pInterfaceName == nullptr || lstrlen(pInterfaceName) == 0) { - SPDLOG_ERROR(TEXT("Input pInterfaceName params error: {0}"), pInterfaceName); - return -ERR_INPUT_PARAMS; - } + GUID ifGuid; + int ret; if (pIsEnable == nullptr) { SPDLOG_ERROR(TEXT("Input pIsEnable params error")); return -ERR_INPUT_PARAMS; } + // ȡGUID + if ((ret = GetInterfaceGUIDByIfIndex(ifIndex, &ifGuid)) != ERR_SUCCESS) { + return ret; + } + hr = ::CoCreateInstance(CLSID_NetSharingManager, nullptr, CLSCTX_ALL, @@ -751,19 +1020,17 @@ int GetNetConnectionSharing(const TCHAR *pInterfaceName, bool *pIsEnable) { if (V_VT(&v) == VT_UNKNOWN) { V_UNKNOWN(&v)->QueryInterface(IID_INetConnection, reinterpret_cast(&pNC)); if (pNC) { - TCHAR ifName[MAX_PATH]; NETCON_PROPERTIES *pNP; pNC->GetProperties(&pNP); - // ִַת - if (WideCharToTChar(pNP->pszwName, ifName, MAX_PATH) != ERR_SUCCESS) { + // ҵӦд + if (memcmp(&ifGuid, &pNP->guidId, sizeof(GUID)) != 0) { continue; } - // ҵӦд - if (StrCmp(pInterfaceName, ifName) != 0) { - continue; - } + //if (StrCmp(pInterfaceName, ifName) != 0) { + // continue; + //} hr = pNSM->get_INetSharingConfigurationForINetConnection(pNC, &pNSC); @@ -773,10 +1040,16 @@ int GetNetConnectionSharing(const TCHAR *pInterfaceName, bool *pIsEnable) { if (pNSC) { VARIANT_BOOL bRet = false; - pNSC->get_SharingEnabled(&bRet); - *pIsEnable = bRet; + hr = pNSC->get_SharingEnabled(&bRet); pNSC->Release(); + if (hr != S_OK) { + SPDLOG_ERROR(TEXT("INetSharingManager DisableSharing failed: {0}."), hr); + return -ERR_CALL_COMMOBJECT; + } + + *pIsEnable = bRet; + return ERR_SUCCESS; } } @@ -786,69 +1059,185 @@ int GetNetConnectionSharing(const TCHAR *pInterfaceName, bool *pIsEnable) { return ERR_ITEM_UNEXISTS; } -/** - * @brief ϵͳ·ɱ - * @param[in] ifIndex Index - * @param[in] pIP Ŀ IP ַ - * @param[in] pMask Ŀ - * @param[in] pGateway · - * @return ִн 0: ɹ С0 ʧ @see USER_ERRNO - * - -ERR_INPUT_PARAMS - * - -ERR_UN_SUPPORT IPַתַֽʧ - * - -ERR_NET_ADD_ROUTE ·ɱʧ - * - ERR_SUCCESS ɹ - */ -int AddRouteTable(int ifIndex, const char *pIP, const char *pMask, const char *pGateway) { - MIB_IPFORWARDROW IpForwardTable; +int AddRouteTable(const char *pIP, const char *pMask, const char *pGateway) { + PMIB_IPFORWARDTABLE pIpForwardTable = nullptr; + PMIB_IPFORWARDROW pRow = nullptr; + DWORD dwSize = 0; + DWORD dwStatus; + DWORD dwDestIp; + int ret; + IP_INFO ipInfo; - if (pIP == nullptr || lstrlen(pIP) < 8) { + if (pIP == nullptr || lstrlen(pIP) < MIN_IP_LEN) { SPDLOG_ERROR(TEXT("Input pIP params error: {0}"), pIP); return -ERR_INPUT_PARAMS; } - if (pMask == nullptr || lstrlen(pMask) < 8) { + if (pMask == nullptr || lstrlen(pMask) < MIN_IP_LEN) { SPDLOG_ERROR(TEXT("Input pMask params error: {0}"), pMask); return -ERR_INPUT_PARAMS; } - if (pGateway == nullptr || lstrlen(pGateway) < 8) { + if (pGateway == nullptr || lstrlen(pGateway) < MIN_IP_LEN) { SPDLOG_ERROR(TEXT("Input pGateway params error: {0}"), pGateway); return -ERR_INPUT_PARAMS; } - ZeroMemory(&IpForwardTable, sizeof(MIB_IPFORWARDROW)); + if ((ret = GetIpV4InfoFromNetmask(pIP, pMask, &ipInfo)) != ERR_SUCCESS) { + return ret; + } - if (inet_pton(AF_INET, pIP, &IpForwardTable.dwForwardDest) <= 0) { + if (inet_pton(AF_INET, ipInfo.network, &dwDestIp) <= 0) { SPDLOG_ERROR(TEXT("Convert {0} to network ipaddress error."), pIP); return -ERR_UN_SUPPORT; } - if (inet_pton(AF_INET, pMask, &IpForwardTable.dwForwardMask) <= 0) { + // Find out how big our buffer needs to be. + dwStatus = GetIpForwardTable(pIpForwardTable, &dwSize, FALSE); + if (dwStatus == ERROR_INSUFFICIENT_BUFFER) { + // Allocate the memory for the table + pIpForwardTable = static_cast(malloc(dwSize)); + if (!pIpForwardTable) { + SPDLOG_ERROR(TEXT("Malloc failed. Out of memory.")); + return -ERR_MALLOC_MEMORY; + } + // Now get the table. + dwStatus = GetIpForwardTable(pIpForwardTable, &dwSize, FALSE); + } + + if (dwStatus != ERROR_SUCCESS) { + SPDLOG_ERROR(TEXT("getIpForwardTable failed.")); + if (pIpForwardTable) { + free(pIpForwardTable); + } + return -ERR_SYS_CALL; + } + + for (DWORD i = 0; i < pIpForwardTable->dwNumEntries; i++) { + if (pIpForwardTable->table[i].dwForwardDest == 0) { + if (!pRow) { + pRow = static_cast(malloc(sizeof(MIB_IPFORWARDROW))); + if (!pRow) { + SPDLOG_ERROR(TEXT("Malloc failed. Out of memory.")); + free(pIpForwardTable); + free(pRow); + return -ERR_MALLOC_MEMORY; + } + // Copy the row + memcpy(pRow, &(pIpForwardTable->table[i]), sizeof(MIB_IPFORWARDROW)); + } + } else if (pIpForwardTable->table[i].dwForwardDest == dwDestIp) { + // ɾܴڵľɵ·Ϣ + dwStatus = DeleteIpForwardEntry(&(pIpForwardTable->table[i])); + + if (dwStatus != ERROR_SUCCESS) { + SPDLOG_ERROR(TEXT("Could not delete old gateway")); + return -ERR_NET_REMOVE_ROUTE; + } + } + } + + free(pIpForwardTable); + + pRow->dwForwardDest = dwDestIp; + + if (inet_pton(AF_INET, ipInfo.netmask, &pRow->dwForwardMask) <= 0) { SPDLOG_ERROR(TEXT("Convert {0} to network ipaddress error."), pMask); return -ERR_UN_SUPPORT; } - if (inet_pton(AF_INET, pGateway, &IpForwardTable.dwForwardNextHop) <= 0) { + if (inet_pton(AF_INET, pGateway, &pRow->dwForwardNextHop) <= 0) { SPDLOG_ERROR(TEXT("Convert {0} to network ipaddress error."), pGateway); + free(pRow); return -ERR_UN_SUPPORT; } - IpForwardTable.dwForwardIfIndex = ifIndex; - IpForwardTable.dwForwardType = MIB_IPROUTE_TYPE_DIRECT; - IpForwardTable.dwForwardProto = MIB_IPPROTO_LOCAL; - IpForwardTable.dwForwardPolicy = 0; - IpForwardTable.dwForwardAge = 0; - IpForwardTable.dwForwardNextHopAS = 0; - IpForwardTable.dwForwardMetric1 = 0xFFFFFFFF; - IpForwardTable.dwForwardMetric2 = 0xFFFFFFFF; - IpForwardTable.dwForwardMetric3 = 0xFFFFFFFF; - IpForwardTable.dwForwardMetric4 = 0xFFFFFFFF; - IpForwardTable.dwForwardMetric5 = 0xFFFFFFFF; + if ((ret = GetInterfaceIfIndexByIpAddr(pGateway, &pRow->dwForwardIfIndex)) != ERR_SUCCESS) { + free(pRow); + return ret; + } - if (CreateIpForwardEntry(&IpForwardTable) != NO_ERROR) { + if ((dwStatus = CreateIpForwardEntry(pRow)) != NO_ERROR) { + SPDLOG_ERROR(TEXT("Add Route {1} netmask {2} gateway {3} error: {0}."), dwStatus, pIP, pMask, pGateway); + free(pRow); return -ERR_NET_ADD_ROUTE; } + free(pRow); + + return ERR_SUCCESS; +} + +int SetNATRule(const TCHAR *pInterfaceName, const TCHAR *pCidrIpaddr) { + int ret; + TCHAR cmdBuf[1024]; + DWORD retCode; + + if (pInterfaceName == nullptr || lstrlen(pInterfaceName) == 0) { + SPDLOG_ERROR("Input pInterfaceName params error: {0}", pInterfaceName); + return -ERR_INPUT_PARAMS; + } + + if (pCidrIpaddr == nullptr || lstrlen(pCidrIpaddr) == 0) { + SPDLOG_ERROR("Input pCidrIpaddr params error: {0}", pCidrIpaddr); + return -ERR_INPUT_PARAMS; + } + + if (FAILED(StringCbPrintf( + cmdBuf, + 1024, + TEXT("PowerShell -NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass Invoke-Command " + "-ScriptBlock { Get-NetNat -Name %s_nat -ErrorAction Ignore | Remove-NetNat -Confirm:$false; " + "New-NetNat -Name %s_nat -InternalIPInterfaceAddressPrefix %s }"), + pInterfaceName, + pInterfaceName, + pCidrIpaddr))) { + SPDLOG_ERROR("Format String Error"); + return -ERR_MEMORY_STR; + } + + if ((ret = RunCommand(cmdBuf, nullptr, 0, &retCode)) != ERR_SUCCESS) { + SPDLOG_ERROR("Run command [{0}] error: {1}", cmdBuf, ret); + return -ERR_CALL_SHELL; + } + + SPDLOG_DEBUG("Run Command({1}): {0}", cmdBuf, retCode); + + if (retCode != 0) { + SPDLOG_ERROR("PowerShell return error({1}): {0}", cmdBuf, retCode); + return -ERR_PROCESS_RETURN; + } + + return ERR_SUCCESS; +} + +int RemoveNATRule(const TCHAR *pInterfaceName) { + int ret; + TCHAR cmdBuf[1024]; + DWORD retCode; + + if (pInterfaceName == nullptr || lstrlen(pInterfaceName) == 0) { + SPDLOG_ERROR("Input pInterfaceName params error: {0}", pInterfaceName); + return -ERR_INPUT_PARAMS; + } + + if (FAILED(StringCbPrintf( + cmdBuf, + 1024, + TEXT("PowerShell -NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass Invoke-Command " + "-ScriptBlock { Get-NetNat -Name %s_nat -ErrorAction Ignore | Remove-NetNat -Confirm:$false}"), + pInterfaceName))) { + SPDLOG_ERROR("Format String Error"); + return -ERR_MEMORY_STR; + } + + if ((ret = RunCommand(cmdBuf, nullptr, 0, &retCode)) != ERR_SUCCESS) { + SPDLOG_ERROR("Run command [{0}] error: {1}", cmdBuf, ret); + return -ERR_CALL_SHELL; + } + + SPDLOG_DEBUG("Run Command({1}): {0}", cmdBuf, retCode); + return ERR_SUCCESS; } @@ -966,74 +1355,6 @@ int GetInterfaceIndexByName(const TCHAR *pInterfaceName, int *pIndex) { return ERR_SUCCESS; } -int SetNATRule(const TCHAR *pInterfaceName, const TCHAR *pCidrIpaddr) { - int ret; - TCHAR cmdBuf[MAX_PATH]; - DWORD retCode; - - if (pInterfaceName == nullptr || lstrlen(pInterfaceName) == 0) { - SPDLOG_ERROR("Input pInterfaceName params error: {0}", pInterfaceName); - return -ERR_INPUT_PARAMS; - } - - if (pCidrIpaddr == nullptr || lstrlen(pCidrIpaddr) == 0) { - SPDLOG_ERROR("Input pCidrIpaddr params error: {0}", pCidrIpaddr); - return -ERR_INPUT_PARAMS; - } - - if (FAILED( - StringCbPrintf(cmdBuf, - MAX_PATH, - "PowerShell -Command \"& {New-NetNat -Name %s_nat -InternalIPInterfaceAddressPrefix %s}\"", - pInterfaceName, - pCidrIpaddr))) { - SPDLOG_ERROR("Format String Error"); - return -ERR_MEMORY_STR; - } - - if ((ret = RunCommand(cmdBuf, nullptr, 0, &retCode)) != ERR_SUCCESS) { - SPDLOG_ERROR("Run command [{0}] error: {1}", cmdBuf, ret); - return -ERR_CALL_SHELL; - } - - SPDLOG_DEBUG("Run Set IP Command({1}): {0}", cmdBuf, retCode); - - if (retCode != 0) { - SPDLOG_ERROR("PowerShell return error({1}): {0}", cmdBuf, retCode); - return -ERR_PROCESS_RETURN; - } - - return ERR_SUCCESS; -} - -int RemoveNATRule(const TCHAR *pInterfaceName) { - int ret; - TCHAR cmdBuf[MAX_PATH]; - DWORD retCode; - - if (pInterfaceName == nullptr || lstrlen(pInterfaceName) == 0) { - SPDLOG_ERROR("Input pInterfaceName params error: {0}", pInterfaceName); - return -ERR_INPUT_PARAMS; - } - - if (FAILED(StringCbPrintf(cmdBuf, - MAX_PATH, - "PowerShell -Command \"& {Remove-NetNat -Name %s_nat -Confirm:$false}\"", - pInterfaceName))) { - SPDLOG_ERROR("Format String Error"); - return -ERR_MEMORY_STR; - } - - if ((ret = RunCommand(cmdBuf, nullptr, 0, &retCode)) != ERR_SUCCESS) { - SPDLOG_ERROR("Run command [{0}] error: {1}", cmdBuf, ret); - return -ERR_CALL_SHELL; - } - - SPDLOG_DEBUG("Run Set IP Command({1}): {0}", cmdBuf, retCode); - - return ERR_SUCCESS; -} - int RemoveInterfaceIpAddress(const TCHAR *pInterfaceName) { int ret; TCHAR cmdBuf[MAX_PATH]; diff --git a/NetTunnelSDK/network.h b/NetTunnelSDK/network.h index 798dd25..7fb5505 100644 --- a/NetTunnelSDK/network.h +++ b/NetTunnelSDK/network.h @@ -40,12 +40,26 @@ TUNNEL_API int __cdecl GetAllNICInfo(PNIC_CONTENT *pInfo, int *pItemCounts); /** * @brief 获取当前 Internet 网卡名 - * @param ifName 网卡名称 - * @return 函数执行结果 0: 成功, 小于0 失败 @see USER_ERRNO + * @param[out] pIfIndex 网卡索引 + * @return 函数执行结果 0: 成功, 小于0 失败 @see USER_ERRNO + * - -ERR_INPUT_PARAMS 输入参数错误 * - -ERR_ITEM_UNEXISTS 未找到具有 Internet 连接的网卡 * - ERR_SUCCESS 成功 */ -TUNNEL_API int __cdecl GetInternetIfName(TCHAR ifName[MAX_NETCARD_NAME]); +TUNNEL_API int __cdecl GetInternetIfIndex(int *pIfIndex); + +/** + * @brief 根据网卡 IP地址 获取网卡索引 + * @param[in] pIpAddr 网卡IP地址 + * @param[out] pIfIndex 网卡索引编号 + * @return 函数执行结果 0: 成功, 小于0 失败 @see USER_ERRNO + * - -ERR_INPUT_PARAMS 输入参数错误 + * - -ERR_MALLOC_MEMORY 分配内存失败 + * - -ERR_ITEM_UNEXISTS 找不到合适的网卡 + * - -ERR_UN_SUPPORT 系统不支持该操作 + * - ERR_SUCCESS 成功 + */ +TUNNEL_API int __cdecl GetInterfaceIfIndexByIpAddr(const TCHAR *pIpAddr, ULONG *pIfIndex); /** * @brief 根据网卡 GUDI 获取网卡名称 @@ -61,6 +75,32 @@ TUNNEL_API int __cdecl GetInternetIfName(TCHAR ifName[MAX_NETCARD_NAME]); */ TUNNEL_API int __cdecl GetInterfaceNameByGUID(const TCHAR *pGUID, TCHAR ifName[MAX_NETCARD_NAME]); +/** + * @brief 根据网卡名获取网卡索引 + * @param[in] pInterfaceName 网卡名称 + * @param[out] pIfIndex 网卡 Index + * @return 函数执行结果 0: 成功, 小于0 失败 @see USER_ERRNO + * - -ERR_INPUT_PARAMS 输入参数错误 + * - -ERR_ITEM_UNEXISTS 网卡不存在 + * - -ERR_SYS_CALL 获取操作系统网卡适配器失败 + * - -ERR_MALLOC_MEMORY 分配内存失败 + * - ERR_SUCCESS 成功 + */ +TUNNEL_API int __cdecl GetInterfaceIfIndexByName(const TCHAR *pInterfaceName, int *pIfIndex); + +/** + * @brief 根据网卡名获取网卡 GUID + * @param[in] ifIndex 网卡索引 + * @param[out] pGuid 网卡 GUID + * @return 函数执行结果 0: 成功, 小于0 失败 @see USER_ERRNO + * - -ERR_INPUT_PARAMS 输入参数错误 + * - -ERR_ITEM_UNEXISTS 网卡不存在 + * - -ERR_MEMORY_STR 字符串转 GUID 结构体失败 + * - -ERR_MALLOC_MEMORY 分配内存失败 + * - ERR_SUCCESS 成功 + */ +TUNNEL_API int __cdecl GetInterfaceGUIDByIfIndex(const int ifIndex, GUID *pGuid); + /** * @brief 根据网卡名获取网卡 GUID * @param[in] pInterfaceName 网卡名称 @@ -107,7 +147,7 @@ TUNNEL_API int __cdecl GetNetConnectionNetworkCategory(const TCHAR *pInterfaceNa /** * @brief 启动/停止 Windows 网络共享服务 - * @param[in] pInterfaceName pInterfaceName 网卡名称 + * @param[in] ifIndex 网卡索引 * @param[in] isEnable 启动/停止 Windows 网络共享服务 * - TRUE 启动服务 * - FALSE 停止服务 @@ -122,11 +162,11 @@ TUNNEL_API int __cdecl GetNetConnectionNetworkCategory(const TCHAR *pInterfaceNa * - -ERR_NET_UNCONNECT 网络未连接 * - ERR_SUCCESS 成功 */ -NETWORK_API int __cdecl SetNetConnectionSharing(const TCHAR *pInterfaceName, bool isEnable, bool isSetPrivate); +NETWORK_API int __cdecl SetNetIntelnetConnectionSharing(int ifIndex, bool isEnable, bool isSetPrivate); /** * @brief 获取当前网络共享服务状态 - * @param[in] pInterfaceName pInterfaceName 网卡名称 + * @param[in] ifIndex 网卡名称索引 * @param[out] pIsEnable 当前网络共享服务状态 * - TRUE 启动 * - FALSE 停止 @@ -136,9 +176,10 @@ NETWORK_API int __cdecl SetNetConnectionSharing(const TCHAR *pInterfaceName, boo * - -ERR_SYS_CALL 调用 COM 接口失败 * - -ERR_ITEM_UNEXISTS GUID 不存在 * - -ERR_NET_UNCONNECT 网络未连接 + * - -ERR_CALL_COMMOBJECT 获取网络共享状态失败 * - ERR_SUCCESS 成功 */ -NETWORK_API int __cdecl GetNetConnectionSharing(const TCHAR *pInterfaceName, bool *pIsEnable); +NETWORK_API int __cdecl GetNetIntelnetConnectionSharing(int ifIndex, bool *pIsEnable); /** * @brief 设置网卡为 Private/Public 模式 * @param[in] pInterfaceName pInterfaceName 网卡名称 @@ -155,8 +196,7 @@ NETWORK_API int __cdecl GetNetConnectionSharing(const TCHAR *pInterfaceName, boo NETWORK_API int __cdecl SetNetConnectionNetworkCategory(const TCHAR *pInterfaceName, const bool isPrivate); /** - * @brief 添加系统路由表项 - * @param[in] ifIndex 网卡 Index + * @brief 添加系统路由表项 * @param[in] pIP 目的 IP 地址 * @param[in] pMask 目的子网掩码 * @param[in] pGateway 路由网关 @@ -164,10 +204,38 @@ NETWORK_API int __cdecl SetNetConnectionNetworkCategory(const TCHAR *pInterfaceN * - -ERR_INPUT_PARAMS 输入参数错误 * - -ERR_UN_SUPPORT IP地址转网络字节序网络地址失败 * - -ERR_NET_ADD_ROUTE 添加路由表项失败 + * - -ERR_NET_REMOVE_ROUTE 删除路由表项失败 * - ERR_SUCCESS 成功 */ -NETWORK_API int __cdecl AddRouteTable(int ifIndex, const char *pIP, const char *pMask, const char *pGateway); +NETWORK_API int __cdecl AddRouteTable(const char *pIP, const char *pMask, const char *pGateway); +/** + * @brief 开启 Windows WireGuard NAT 转发功能 + * @param[in] pInterfaceName 网卡名称 + * @param[in] pCidrIpaddr CIDR 网络接口地址 + * @return 函数执行结果 0: 成功, 小于0 失败 @see USER_ERRNO + * - -ERR_INPUT_PARAMS 输入参数错误 + * - -ERR_MEMORY_STR 字符串处理 + * - -ERR_CALL_SHELL 调用系统命令行失败 + * - -ERR_PROCESS_RETURN 系统调用执行结束返回失败 + * - ERR_SUCCESS 成功 + */ +TUNNEL_API int __cdecl SetNATRule(const TCHAR *pInterfaceName, const TCHAR *pCidrIpaddr); + +/** + * @brief 关闭 Windows WireGuard NAT 转发功能 + * @param pInterfaceName 网卡名称 + * @return 函数执行结果 0: 成功, 小于0 失败 @see USER_ERRNO + * - -ERR_INPUT_PARAMS 输入参数错误 + * - -ERR_MEMORY_STR 字符串处理 + * - -ERR_CALL_SHELL 调用系统命令行失败 + * - -ERR_PROCESS_RETURN 系统调用执行结束返回失败 + * - ERR_SUCCESS 成功 + */ +TUNNEL_API int __cdecl RemoveNATRule(const TCHAR *pInterfaceName); + + +TUNNEL_API int __cdecl CreatePorxyService(); #if 0 /** * @brief 获取Windows Hyper-V 虚拟机状态, 必须开启后才能开启NAT转发功能 @@ -192,19 +260,6 @@ TUNNEL_API int __cdecl GetWindowsHyperVStatus(int *pEnabled); */ TUNNEL_API int __cdecl EnableWindowsHyperV(bool enabled); -/** - * @brief 开启 Windows WireGuard NAT 转发功能 - * @param[in] pInterfaceName 网卡名称 - * @param[in] pCidrIpaddr CIDR 网络接口地址 - * @return 函数执行结果 0: 成功, 小于0 失败 @see USER_ERRNO - * - -ERR_INPUT_PARAMS 输入参数错误 - * - -ERR_MEMORY_STR 字符串处理 - * - -ERR_CALL_SHELL 调用系统命令行失败 - * - -ERR_PROCESS_RETURN 系统调用执行结束返回失败 - * - ERR_SUCCESS 成功 - */ -TUNNEL_API int __cdecl SetNATRule(const TCHAR *pInterfaceName, const TCHAR *pCidrIpaddr); - /** * @brief 设置网卡为 Private/Public 模式 * @param[in] pInterfaceName 网卡名称 diff --git a/NetTunnelSDK/protocol.cpp b/NetTunnelSDK/protocol.cpp index 4506673..c9585a8 100644 --- a/NetTunnelSDK/protocol.cpp +++ b/NetTunnelSDK/protocol.cpp @@ -25,6 +25,18 @@ int InitControlServer(const TCHAR *pUserSvrUrl) { g_tunnelHttpCtx = new httplib::Client(pUserSvrUrl); + if (g_tunnelHttpCtx) { + g_tunnelHttpCtx->set_connection_timeout(0, 1000000); // 1 second + g_tunnelHttpCtx->set_read_timeout(5, 0); // 5 seconds + g_tunnelHttpCtx->set_write_timeout(5, 0); // 5 seconds + g_tunnelHttpCtx->set_post_connect_cb([](socket_t sock) { + SPDLOG_DEBUG(TEXT("Service Connected: {0}"), sock); + + // TODO Send SCG Message + // send(sock, ..... GetGlobalCfgInfo()->curConnVmId + }); + } + SPDLOG_DEBUG(TEXT("Connect to Tunnel Control Service: {0}"), pUserSvrUrl); return ERR_SUCCESS; diff --git a/NetTunnelSDK/resource/iconsTray.ico b/NetTunnelSDK/resource/iconsTray.ico new file mode 100644 index 0000000..ce87a98 Binary files /dev/null and b/NetTunnelSDK/resource/iconsTray.ico differ diff --git a/NetTunnelSDK/tunnel.cpp b/NetTunnelSDK/tunnel.cpp index 3428533..4dda544 100644 --- a/NetTunnelSDK/tunnel.cpp +++ b/NetTunnelSDK/tunnel.cpp @@ -6,12 +6,17 @@ #include #include #include +#include #include "usrerr.h" #include "globalcfg.h" #include "misc.h" +#include "user.h" #include +#include + +#pragma comment(lib, "Dbghelp.lib") #define CONFIG_FILE_NAME TEXT("tunnelsdk.ini") @@ -21,70 +26,6 @@ PSDK_CONFIG GetGlobalCfgInfo() { return &g_globalConfig; } -int TunnelSDKInitEnv(const TCHAR *pWorkDir, const TCHAR *pSvrUrl, bool isWorkServer) { - size_t length; - const BOOL logEnable = g_globalConfig.enableLog; - const spdlog::level::level_enum lv = g_globalConfig.logLevel; - - memset(&g_globalConfig, 0, sizeof(SDK_CONFIG)); - - g_globalConfig.isWorkServer = isWorkServer; - - // 创建配置文件存储目录 - if (FAILED(SHGetFolderPath(NULL, CSIDL_APPDATA | CSIDL_FLAG_NO_ALIAS, NULL, 0, g_globalConfig.configDirectory))) { - SPDLOG_ERROR(TEXT("Get Windows system directory error.")); - return -ERR_SYS_CALL; - } - - StringCbCat(g_globalConfig.configDirectory, MAX_PATH, "\\NetTunnel"); - SPDLOG_DEBUG(TEXT("Configure directory: {0}."), g_globalConfig.configDirectory); - - // 如果配置目录不存在则自动创建 - if (!PathFileExists(g_globalConfig.configDirectory)) { - if (!CreateDirectory(g_globalConfig.configDirectory, nullptr)) { - SPDLOG_ERROR(TEXT("Create configure directory '{0}' error."), g_globalConfig.configDirectory); - return -ERR_CREATE_FILE; - } - } - - StringCbCopy(g_globalConfig.platformServerUrl, MAX_IP_LEN, pSvrUrl); - - g_globalConfig.logLevel = lv; - g_globalConfig.enableLog = logEnable; - - if (!logEnable) { - spdlog::set_level(spdlog::level::off); - } - - if (FAILED(SHGetFolderPath(NULL, CSIDL_WINDOWS | CSIDL_FLAG_NO_ALIAS, NULL, 0, g_globalConfig.systemDirectory))) { - SPDLOG_ERROR(TEXT("Get Windows system directory error.")); - return -ERR_SYS_CALL; - } - - if (pWorkDir == nullptr) { - // 获取当前文件默认路径 - GetCurrentDirectory(MAX_PATH, g_globalConfig.workDirectory); - } else { - if (StringCbLengthA(pWorkDir, MAX_PATH, &length) == S_OK && length == 0) { - GetCurrentDirectory(MAX_PATH, g_globalConfig.workDirectory); - } else { - StringCbCopy(g_globalConfig.workDirectory, MAX_PATH, pWorkDir); - } - } - - StringCbPrintf(g_globalConfig.cfgPath, MAX_PATH, TEXT("%s\\%s"), g_globalConfig.workDirectory, CONFIG_FILE_NAME); - - if (FindWireguardExe(nullptr, 0) != ERR_SUCCESS) { - SPDLOG_ERROR(TEXT("WireGuard not found, Please install WireGuard first or set the WireGuard Path.")); - return -ERR_ITEM_EXISTS; - } - - return ERR_SUCCESS; -} - -void TunnelSDKUnInit() { -} - static spdlog::level::level_enum logLevelToSpdlogLevel(LOG_LEVEL level) { switch (level) { case LOG_TRACE: @@ -106,13 +47,17 @@ static spdlog::level::level_enum logLevelToSpdlogLevel(LOG_LEVEL level) { return spdlog::level::level_enum::info; } -void InitTunnelSDKLog(const TCHAR *pLogFile, LOG_LEVEL level) { +static void InitTunnelSDKLog(const TCHAR *pLogFile, LOG_LEVEL level) { TCHAR buf[MAX_PATH] = {0}; - if (pLogFile && strlen(pLogFile) > 0) { + if (pLogFile && strlen(pLogFile) > 0 && !PathIsRelative(pLogFile)) { + TCHAR tmpPath[MAX_PATH]; + StringCbCopy(tmpPath, MAX_PATH, pLogFile); + PathRemoveFileSpec(tmpPath); + MakeSureDirectoryPathExists(tmpPath); StringCbCopy(buf, MAX_PATH, pLogFile); } else { - StringCbCopy(buf, MAX_PATH, TEXT("tunnelsdk.log")); + StringCbPrintf(buf, MAX_PATH, TEXT("%s\\tunnelsdklog.log"), g_globalConfig.workDirectory); } g_globalConfig.enableLog = TRUE; @@ -144,6 +89,83 @@ void InitTunnelSDKLog(const TCHAR *pLogFile, LOG_LEVEL level) { SPDLOG_INFO(TEXT("Log({1}): {0}"), buf, static_cast(level)); } +int TunnelSDKInitEnv(const TCHAR *pWorkDir, + const TCHAR *pSvrUrl, + const TCHAR *pLogFile, + LOG_LEVEL level, + bool isWorkServer) { + size_t length; + + memset(&g_globalConfig, 0, sizeof(SDK_CONFIG)); + + g_globalConfig.isWorkServer = isWorkServer; + g_globalConfig.usedSCGProxy = false; + + if (pWorkDir == nullptr) { + // 获取当前文件默认路径 + GetModuleFileName(nullptr, g_globalConfig.workDirectory, MAX_PATH); + PathRemoveFileSpec(g_globalConfig.workDirectory); + } else { + if (StringCbLength(pWorkDir, MAX_PATH, &length) == S_OK && length == 0 || PathIsRelative(pWorkDir)) { + // 获取当前文件默认路径 + GetModuleFileName(nullptr, g_globalConfig.workDirectory, MAX_PATH); + PathRemoveFileSpec(g_globalConfig.workDirectory); + } else { + MakeSureDirectoryPathExists(pWorkDir); + StringCbCopy(g_globalConfig.workDirectory, MAX_PATH, pWorkDir); + } + } + + // 初始化日志 + InitTunnelSDKLog(pLogFile, level); + + // 创建配置文件存储目录 + if (FAILED(SHGetFolderPath(NULL, CSIDL_APPDATA | CSIDL_FLAG_NO_ALIAS, NULL, 0, g_globalConfig.configDirectory))) { + SPDLOG_ERROR(TEXT("Get Windows system directory error.")); + return -ERR_SYS_CALL; + } + + StringCbCat(g_globalConfig.configDirectory, MAX_PATH, "\\NetTunnel"); + SPDLOG_DEBUG(TEXT("Configure directory: {0}."), g_globalConfig.configDirectory); + + // 如果配置目录不存在则自动创建 + if (!PathFileExists(g_globalConfig.configDirectory)) { + if (!CreateDirectory(g_globalConfig.configDirectory, nullptr)) { + SPDLOG_ERROR(TEXT("Create configure directory '{0}' error."), g_globalConfig.configDirectory); + return -ERR_CREATE_FILE; + } + } + + StringCbCopy(g_globalConfig.platformServerUrl, MAX_IP_LEN, pSvrUrl); + + if (FAILED(SHGetFolderPath(NULL, CSIDL_WINDOWS | CSIDL_FLAG_NO_ALIAS, NULL, 0, g_globalConfig.systemDirectory))) { + SPDLOG_ERROR(TEXT("Get Windows system directory error.")); + return -ERR_SYS_CALL; + } + + StringCbPrintf(g_globalConfig.cfgPath, MAX_PATH, TEXT("%s\\%s"), g_globalConfig.workDirectory, CONFIG_FILE_NAME); + + if (FindWireguardExe(nullptr, 0) != ERR_SUCCESS) { + SPDLOG_ERROR(TEXT("WireGuard not found, Please install WireGuard first or set the WireGuard Path.")); + return -ERR_ITEM_EXISTS; + } + + return ERR_SUCCESS; +} + +void TunnelSDKUnInit() { + RemoteWireGuardControl(false); + LocalWireGuardControl(false, false); +} + +void EnableSCGProxy(bool isEnable) { + g_globalConfig.usedSCGProxy = isEnable; +} + +bool GetSCGProxyStatus() { + return g_globalConfig.usedSCGProxy; +} + void TunnelLogEnable(bool enLog) { if (enLog) { spdlog::set_level(g_globalConfig.logLevel); @@ -154,7 +176,7 @@ void TunnelLogEnable(bool enLog) { int SetProtocolEncryptType(const PROTO_CRYPTO_TYPE type, const TCHAR *pProKey) { if (type > CRYPTO_BASE64 && type < CRYPTO_MAX) { - if (pProKey == nullptr || strlen(pProKey) < 8) { + if (pProKey == nullptr || strlen(pProKey) < MIN_IP_LEN) { return -ERR_INPUT_PARAMS; } } diff --git a/NetTunnelSDK/tunnel.h b/NetTunnelSDK/tunnel.h index ab0a5c0..026927d 100644 --- a/NetTunnelSDK/tunnel.h +++ b/NetTunnelSDK/tunnel.h @@ -23,6 +23,11 @@ constexpr auto WG_KEY_MAX = (64); */ #define MAX_IP_LEN (48) +/** + * @brief IP 字符串最小长度 + */ +#define MIN_IP_LEN (7) + /** * @brief 网卡名称字符串最大长度(支持IPv6) */ @@ -79,6 +84,15 @@ typedef enum { CHK_MAX } CHECK_FUNCTION; +/** + * @brief 网络共享模式 + * + */ +typedef enum { + ICS_SHARE_MODE = 0, ///< Internet Share Mode(ICS) 模式 + NAT_SHARE_MODE = 1 ///< Net Address Translation(NAT) 模式 +} NET_SHARE_MODE; + typedef struct { CHECK_FUNCTION chk; bool result; @@ -118,18 +132,38 @@ extern "C" { // we need to export the C interface #endif +/** + * @brief 获取当前网络共享模式 + * @return 当前网络共享模式 @see NET_SHARE_MODE + */ +TUNNEL_API NET_SHARE_MODE __cdecl GetCurrentNetShareMode(); + +/** + * @brief 设置获取当前网络共享模式 + * @param shareMode 网络共享模式 @see NET_SHARE_MODE + */ +TUNNEL_API void __cdecl SetCurrentNetShareMode(NET_SHARE_MODE shareMode); + /** * @brief 初始化 SDK 运行环境 * @param[in] pWorkDir 程序工作路径,如果不设置系统自动获取 * @param[in] pSvrUrl 管理平台 URL 地址 example: http://localhost:2313, https://localhost:2313 + * @param[in] pLogFile 日志文件名称/完整路径 + * @param[in] level 日志最低有效等级 * @param[in] isWorkServer SDK 工作模式 * - TRUE 服务端 * - FALSE 客户端 * @return 函数执行结果 0: 成功, 小于0 失败 @see USER_ERRNO * - -ERR_ITEM_EXISTS 未找到 WireGuard 程序 + * - -ERR_SYS_CALL 获取配置本地配置文件存储目录失败 + * - -ERR_CREATE_FILE 创建用户配置文件目录失败 * - ERR_SUCCESS 成功 */ -TUNNEL_API int __cdecl TunnelSDKInitEnv(const TCHAR *pWorkDir, const TCHAR *pSvrUrl, bool isWorkServer); +TUNNEL_API int __cdecl TunnelSDKInitEnv(const TCHAR *pWorkDir, + const TCHAR *pSvrUrl, + const TCHAR *pLogFile, + LOG_LEVEL level, + bool isWorkServer); /** * @brief 设置传输协议加密方式,默认 CRYPTO_NONE @@ -141,13 +175,6 @@ TUNNEL_API int __cdecl TunnelSDKInitEnv(const TCHAR *pWorkDir, const TCHAR *pSvr */ TUNNEL_API int __cdecl SetProtocolEncryptType(const PROTO_CRYPTO_TYPE type, const TCHAR *pProKey); -/** - * @brief 初始化 SDK 日志 - * @param[in] pLogFile 日志文件名称/完整路径 - * @param[in] level 日志最低有效等级 - */ -TUNNEL_API void __cdecl InitTunnelSDKLog(const TCHAR *pLogFile, LOG_LEVEL level); - /** * @brief 打开/关闭 SDK 日志开关 * @param enLog 日志开关 @@ -287,6 +314,18 @@ TUNNEL_API int __cdecl IsWireGuardServerRunning(const TCHAR *pIfName, bool *pIsR */ TUNNEL_API void __cdecl TunnelSDKUnInit(); +/** + * @brief SCG 代理服务开关 + * @param isEnable TRUE: 启动 SCG 代理, FALSE: 禁用 SCG 代理 + */ +TUNNEL_API void __cdecl EnableSCGProxy(bool isEnable); + +/** + * @brief 获取当前 SCG 代理服务状态 + * @return TRUE: SCG 代理启动, FALSE: SCG 代理禁用 + */ +TUNNEL_API bool __cdecl GetSCGProxyStatus(); + /** * @brief 计算文件 Hash * @param[in] type Hash 类型 @see HASH_TYPE diff --git a/NetTunnelSDK/user.h b/NetTunnelSDK/user.h index 4b18bef..0ac5ece 100644 --- a/NetTunnelSDK/user.h +++ b/NetTunnelSDK/user.h @@ -128,6 +128,7 @@ USERMANAGER_API int __cdecl RemoteWireGuardControl(bool isStart); * @return 0: 成功, 小于0 失败 @see USER_ERRNO * - -ERR_INPUT_PARAMS 输入参数错误 * - -ERR_NET_CATEGORY_MODE 网卡工作模式错误 + * - -ERR_UN_SUPPORT 不支持的网络共享类型 * - ERR_SUCCESS 成功 */ USERMANAGER_API int __cdecl LocalWireGuardControl(bool isStart, bool setPrivateMode); diff --git a/NetTunnelSDK/usrerr.h b/NetTunnelSDK/usrerr.h index c8f97bf..72afd3f 100644 --- a/NetTunnelSDK/usrerr.h +++ b/NetTunnelSDK/usrerr.h @@ -34,19 +34,29 @@ enum USER_ERRNO { ERR_CREATE_THREAD, ///< 创建线程失败 ERR_CREATE_TIMER, ///< 创建定时器失败 ERR_DELETE_TIMER, ///< 销毁定时器失败 + ERR_SOCKET_CREATE, ///< 创建 SOCKET 失败 + ERR_SOCKET_BIND, ///< 绑定 SOCKET 端口失败 + ERR_SOCKET_CONNECT, ///< 连接 TCP SOCKET 服务器失败 + ERR_SOCKET_LISTEN, ///< TCP SOCKET 服务监听失败 ERR_SOCKET_BIND_PORT, ///< 绑定端口失败 + ERR_SOCKET_SET_OPT, ///< 设置 SOCKET 参数失败 + ERR_SOCKET_GET_OPT, ///< 读取 SOCKET 参数失败 ERR_BCRYPT_OPEN = 100, ///< 创建加密算法失败 ERR_BCRYPT_GETPROPERTY, ///< 获取加密算法属性失败 ERR_BCRYPT_CREATEHASH, ///< 创建 Hash 算法失败 ERR_BCRYPT_HASHDATA, ///< 计算 Hash 数据失败 ERR_BCRYPT_FINISHHASH, ///< 计算 Hash 结果失败 - ERR_NET_UNCONNECT = 100, ///< 网络未连接 + ERR_NET_UNCONNECT = 200, ///< 网络未连接 ERR_NET_CATEGORY_MODE, ///< 网络工作模式 - ERR_GET_IPFOWARDTBL = 200, ///< 获取系统 IP 转发表失败 - ERR_CREATE_COMMOBJECT = 300, ///< 创建 COM 对象失败 - ERR_JSON_CREATE = 400, ///< 创建 JSON 对象失败 + ERR_NET_INTELNEL_ICS, ///< 共享 Intelnet 网络 ICS 共享失败 + ERR_NET_WIREGUARD_ICS, ///< 共享 WireGuard 网络 ICS 共享失败 + ERR_GET_IPFOWARDTBL = 300, ///< 获取系统 IP 转发表失败 + ERR_CREATE_COMMOBJECT = 400, ///< 创建 COM 对象失败 + ERR_CALL_COMMOBJECT, ///< 调用 COM 对象失败 + ERR_JSON_CREATE = 500, ///< 创建 JSON 对象失败 ERR_JSON_DECODE, ///< 从 JSON 反序列化对象失败 - ERR_HTTP_SERVER_RSP = 500, ///< HTTP 服务端返回错误 + ERR_HTTP_SERVER_RSP = 600, ///< HTTP 服务端返回错误 ERR_HTTP_POST_DATA, ///< 发送 POST 请求失败 ERR_NET_ADD_ROUTE, ///< 添加路由失败 + ERR_NET_REMOVE_ROUTE, ///< 删除路由失败 }; \ No newline at end of file diff --git a/NetTunnelSDK/uthash/utarray.h b/NetTunnelSDK/uthash/utarray.h new file mode 100644 index 0000000..2919a07 --- /dev/null +++ b/NetTunnelSDK/uthash/utarray.h @@ -0,0 +1,285 @@ +/* +Copyright (c) 2008-2021, Troy D. Hanson http://troydhanson.github.com/uthash/ +All rights reserved. + +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. + +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. +*/ + +/* a dynamic array implementation using macros + */ +#ifndef UTARRAY_H +#define UTARRAY_H + +#define UTARRAY_VERSION 2.3.0 + +#include /* size_t */ +#include /* memset, etc */ +#include /* exit */ + +#ifdef __GNUC__ +#define UTARRAY_UNUSED __attribute__((__unused__)) +#else +#define UTARRAY_UNUSED +#endif + +#ifdef oom +#error "The name of macro 'oom' has been changed to 'utarray_oom'. Please update your code." +#define utarray_oom() oom() +#endif + +#ifndef utarray_oom +#define utarray_oom() exit(-1) +#endif + +typedef void(ctor_f)(void *dst, const void *src); +typedef void(dtor_f)(void *elt); +typedef void(init_f)(void *elt); +typedef struct { + size_t sz; + init_f *init; + ctor_f *copy; + dtor_f *dtor; +} UT_icd; + +typedef struct { + unsigned i, n; /* i: index of next available slot, n: num slots */ + UT_icd icd; /* initializer, copy and destructor functions */ + char *d; /* n slots of size icd->sz*/ +} UT_array; + +#define utarray_init(a, _icd) \ + do { \ + memset(a, 0, sizeof(UT_array)); \ + (a)->icd = *(_icd); \ + } while (0) + +#define utarray_done(a) \ + do { \ + if ((a)->n) { \ + if ((a)->icd.dtor) { \ + unsigned _ut_i; \ + for (_ut_i = 0; _ut_i < (a)->i; _ut_i++) { \ + (a)->icd.dtor(utarray_eltptr(a, _ut_i)); \ + } \ + } \ + free((a)->d); \ + } \ + (a)->n = 0; \ + } while (0) + +#define utarray_new(a, _icd) \ + do { \ + (a) = (UT_array *)malloc(sizeof(UT_array)); \ + if ((a) == NULL) { \ + utarray_oom(); \ + } \ + utarray_init(a, _icd); \ + } while (0) + +#define utarray_free(a) \ + do { \ + utarray_done(a); \ + free(a); \ + } while (0) + +#define utarray_reserve(a, by) \ + do { \ + if (((a)->i + (by)) > (a)->n) { \ + char *utarray_tmp; \ + while (((a)->i + (by)) > (a)->n) { \ + (a)->n = ((a)->n ? (2 * (a)->n) : 8); \ + } \ + utarray_tmp = (char *)realloc((a)->d, (a)->n * (a)->icd.sz); \ + if (utarray_tmp == NULL) { \ + utarray_oom(); \ + } \ + (a)->d = utarray_tmp; \ + } \ + } while (0) + +#define utarray_push_back(a, p) \ + do { \ + utarray_reserve(a, 1); \ + if ((a)->icd.copy) { \ + (a)->icd.copy(_utarray_eltptr(a, (a)->i++), p); \ + } else { \ + memcpy(_utarray_eltptr(a, (a)->i++), p, (a)->icd.sz); \ + }; \ + } while (0) + +#define utarray_pop_back(a) \ + do { \ + if ((a)->icd.dtor) { \ + (a)->icd.dtor(_utarray_eltptr(a, --((a)->i))); \ + } else { \ + (a)->i--; \ + } \ + } while (0) + +#define utarray_extend_back(a) \ + do { \ + utarray_reserve(a, 1); \ + if ((a)->icd.init) { \ + (a)->icd.init(_utarray_eltptr(a, (a)->i)); \ + } else { \ + memset(_utarray_eltptr(a, (a)->i), 0, (a)->icd.sz); \ + } \ + (a)->i++; \ + } while (0) + +#define utarray_len(a) ((a)->i) + +#define utarray_eltptr(a, j) (((j) < (a)->i) ? _utarray_eltptr(a, j) : NULL) +#define _utarray_eltptr(a, j) ((void *)((a)->d + ((a)->icd.sz * (j)))) + +#define utarray_insert(a, p, j) \ + do { \ + if ((j) > (a)->i) \ + utarray_resize(a, j); \ + utarray_reserve(a, 1); \ + if ((j) < (a)->i) { \ + memmove(_utarray_eltptr(a, (j) + 1), _utarray_eltptr(a, j), ((a)->i - (j)) * ((a)->icd.sz)); \ + } \ + if ((a)->icd.copy) { \ + (a)->icd.copy(_utarray_eltptr(a, j), p); \ + } else { \ + memcpy(_utarray_eltptr(a, j), p, (a)->icd.sz); \ + }; \ + (a)->i++; \ + } while (0) + +#define utarray_inserta(a, w, j) \ + do { \ + if (utarray_len(w) == 0) \ + break; \ + if ((j) > (a)->i) \ + utarray_resize(a, j); \ + utarray_reserve(a, utarray_len(w)); \ + if ((j) < (a)->i) { \ + memmove(_utarray_eltptr(a, (j) + utarray_len(w)), _utarray_eltptr(a, j), ((a)->i - (j)) * ((a)->icd.sz)); \ + } \ + if ((a)->icd.copy) { \ + unsigned _ut_i; \ + for (_ut_i = 0; _ut_i < (w)->i; _ut_i++) { \ + (a)->icd.copy(_utarray_eltptr(a, (j) + _ut_i), _utarray_eltptr(w, _ut_i)); \ + } \ + } else { \ + memcpy(_utarray_eltptr(a, j), _utarray_eltptr(w, 0), utarray_len(w) * ((a)->icd.sz)); \ + } \ + (a)->i += utarray_len(w); \ + } while (0) + +#define utarray_resize(dst, num) \ + do { \ + unsigned _ut_i; \ + if ((dst)->i > (unsigned)(num)) { \ + if ((dst)->icd.dtor) { \ + for (_ut_i = (num); _ut_i < (dst)->i; ++_ut_i) { \ + (dst)->icd.dtor(_utarray_eltptr(dst, _ut_i)); \ + } \ + } \ + } else if ((dst)->i < (unsigned)(num)) { \ + utarray_reserve(dst, (num) - (dst)->i); \ + if ((dst)->icd.init) { \ + for (_ut_i = (dst)->i; _ut_i < (unsigned)(num); ++_ut_i) { \ + (dst)->icd.init(_utarray_eltptr(dst, _ut_i)); \ + } \ + } else { \ + memset(_utarray_eltptr(dst, (dst)->i), 0, (dst)->icd.sz *((num) - (dst)->i)); \ + } \ + } \ + (dst)->i = (num); \ + } while (0) + +#define utarray_concat(dst, src) \ + do { \ + utarray_inserta(dst, src, utarray_len(dst)); \ + } while (0) + +#define utarray_erase(a, pos, len) \ + do { \ + if ((a)->icd.dtor) { \ + unsigned _ut_i; \ + for (_ut_i = 0; _ut_i < (len); _ut_i++) { \ + (a)->icd.dtor(utarray_eltptr(a, (pos) + _ut_i)); \ + } \ + } \ + if ((a)->i > ((pos) + (len))) { \ + memmove(_utarray_eltptr(a, pos), \ + _utarray_eltptr(a, (pos) + (len)), \ + ((a)->i - ((pos) + (len))) * (a)->icd.sz); \ + } \ + (a)->i -= (len); \ + } while (0) + +#define utarray_renew(a, u) \ + do { \ + if (a) \ + utarray_clear(a); \ + else \ + utarray_new(a, u); \ + } while (0) + +#define utarray_clear(a) \ + do { \ + if ((a)->i > 0) { \ + if ((a)->icd.dtor) { \ + unsigned _ut_i; \ + for (_ut_i = 0; _ut_i < (a)->i; _ut_i++) { \ + (a)->icd.dtor(_utarray_eltptr(a, _ut_i)); \ + } \ + } \ + (a)->i = 0; \ + } \ + } while (0) + +#define utarray_sort(a, cmp) \ + do { \ + qsort((a)->d, (a)->i, (a)->icd.sz, cmp); \ + } while (0) + +#define utarray_find(a, v, cmp) bsearch((v), (a)->d, (a)->i, (a)->icd.sz, cmp) + +#define utarray_front(a) (((a)->i) ? (_utarray_eltptr(a, 0)) : NULL) +#define utarray_next(a, e) \ + (((e) == NULL) ? utarray_front(a) \ + : (((a)->i != utarray_eltidx(a, e) + 1) ? _utarray_eltptr(a, utarray_eltidx(a, e) + 1) : NULL)) +#define utarray_prev(a, e) \ + (((e) == NULL) ? utarray_back(a) \ + : ((utarray_eltidx(a, e) != 0) ? _utarray_eltptr(a, utarray_eltidx(a, e) - 1) : NULL)) +#define utarray_back(a) (((a)->i) ? (_utarray_eltptr(a, (a)->i - 1)) : NULL) +#define utarray_eltidx(a, e) (((char *)(e) - (a)->d) / (a)->icd.sz) + +/* last we pre-define a few icd for common utarrays of ints and strings */ +static void utarray_str_cpy(void *dst, const void *src) { + char *const *srcc = (char *const *)src; + char **dstc = (char **)dst; + *dstc = (*srcc == NULL) ? NULL : strdup(*srcc); +} +static void utarray_str_dtor(void *elt) { + char **eltc = (char **)elt; + if (*eltc != NULL) { + free(*eltc); + } +} +static const UT_icd ut_str_icd UTARRAY_UNUSED = {sizeof(char *), NULL, utarray_str_cpy, utarray_str_dtor}; +static const UT_icd ut_int_icd UTARRAY_UNUSED = {sizeof(int), NULL, NULL, NULL}; +static const UT_icd ut_ptr_icd UTARRAY_UNUSED = {sizeof(void *), NULL, NULL, NULL}; + +#endif /* UTARRAY_H */ diff --git a/NetTunnelSDK/uthash/uthash.h b/NetTunnelSDK/uthash/uthash.h new file mode 100644 index 0000000..a93311d --- /dev/null +++ b/NetTunnelSDK/uthash/uthash.h @@ -0,0 +1,1136 @@ +/* +Copyright (c) 2003-2021, Troy D. Hanson http://troydhanson.github.com/uthash/ +All rights reserved. + +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. + +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. +*/ + +#ifndef UTHASH_H +#define UTHASH_H + +#define UTHASH_VERSION 2.3.0 + +#include /* memcmp, memset, strlen */ +#include /* ptrdiff_t */ +#include /* exit */ + +#if defined(HASH_DEFINE_OWN_STDINT) && HASH_DEFINE_OWN_STDINT +/* This codepath is provided for backward compatibility, but I plan to remove it. */ +#warning "HASH_DEFINE_OWN_STDINT is deprecated; please use HASH_NO_STDINT instead" +typedef unsigned int uint32_t; +typedef unsigned char uint8_t; +#elif defined(HASH_NO_STDINT) && HASH_NO_STDINT +#else +#include /* uint8_t, uint32_t */ +#endif + +/* These macros use decltype or the earlier __typeof GNU extension. + As decltype is only available in newer compilers (VS2010 or gcc 4.3+ + when compiling c++ source) this code uses whatever method is needed + or, for VS2008 where neither is available, uses casting workarounds. */ +#if !defined(DECLTYPE) && !defined(NO_DECLTYPE) +#if defined(_MSC_VER) /* MS compiler */ +#if _MSC_VER >= 1600 && defined(__cplusplus) /* VS2010 or newer in C++ mode */ +#define DECLTYPE(x) (decltype(x)) +#else /* VS2008 or older (or VS2010 in C mode) */ +#define NO_DECLTYPE +#endif +#elif defined(__BORLANDC__) || defined(__ICCARM__) || defined(__LCC__) || defined(__WATCOMC__) +#define NO_DECLTYPE +#else /* GNU, Sun and other compilers */ +#define DECLTYPE(x) (__typeof(x)) +#endif +#endif + +#ifdef NO_DECLTYPE +#define DECLTYPE(x) +#define DECLTYPE_ASSIGN(dst, src) \ + do { \ + char **_da_dst = (char **)(&(dst)); \ + *_da_dst = (char *)(src); \ + } while (0) +#else +#define DECLTYPE_ASSIGN(dst, src) \ + do { \ + (dst) = DECLTYPE(dst)(src); \ + } while (0) +#endif + +#ifndef uthash_malloc +#define uthash_malloc(sz) malloc(sz) /* malloc fcn */ +#endif +#ifndef uthash_free +#define uthash_free(ptr, sz) free(ptr) /* free fcn */ +#endif +#ifndef uthash_bzero +#define uthash_bzero(a, n) memset(a, '\0', n) +#endif +#ifndef uthash_strlen +#define uthash_strlen(s) strlen(s) +#endif + +#ifndef HASH_FUNCTION +#define HASH_FUNCTION(keyptr, keylen, hashv) HASH_JEN(keyptr, keylen, hashv) +#endif + +#ifndef HASH_KEYCMP +#define HASH_KEYCMP(a, b, n) memcmp(a, b, n) +#endif + +#ifndef uthash_noexpand_fyi +#define uthash_noexpand_fyi(tbl) /* can be defined to log noexpand */ +#endif +#ifndef uthash_expand_fyi +#define uthash_expand_fyi(tbl) /* can be defined to log expands */ +#endif + +#ifndef HASH_NONFATAL_OOM +#define HASH_NONFATAL_OOM 0 +#endif + +#if HASH_NONFATAL_OOM +/* malloc failures can be recovered from */ + +#ifndef uthash_nonfatal_oom +#define uthash_nonfatal_oom(obj) \ + do { \ + } while (0) /* non-fatal OOM error */ +#endif + +#define HASH_RECORD_OOM(oomed) \ + do { \ + (oomed) = 1; \ + } while (0) +#define IF_HASH_NONFATAL_OOM(x) x + +#else +/* malloc failures result in lost memory, hash tables are unusable */ + +#ifndef uthash_fatal +#define uthash_fatal(msg) exit(-1) /* fatal OOM error */ +#endif + +#define HASH_RECORD_OOM(oomed) uthash_fatal("out of memory") +#define IF_HASH_NONFATAL_OOM(x) + +#endif + +/* initial number of buckets */ +#define HASH_INITIAL_NUM_BUCKETS 32U /* initial number of buckets */ +#define HASH_INITIAL_NUM_BUCKETS_LOG2 5U /* lg2 of initial number of buckets */ +#define HASH_BKT_CAPACITY_THRESH 10U /* expand when bucket count reaches */ + +/* calculate the element whose hash handle address is hhp */ +#define ELMT_FROM_HH(tbl, hhp) ((void *)(((char *)(hhp)) - ((tbl)->hho))) +/* calculate the hash handle from element address elp */ +#define HH_FROM_ELMT(tbl, elp) ((UT_hash_handle *)(void *)(((char *)(elp)) + ((tbl)->hho))) + +#define HASH_ROLLBACK_BKT(hh, head, itemptrhh) \ + do { \ + struct UT_hash_handle *_hd_hh_item = (itemptrhh); \ + unsigned _hd_bkt; \ + HASH_TO_BKT(_hd_hh_item->hashv, (head)->hh.tbl->num_buckets, _hd_bkt); \ + (head)->hh.tbl->buckets[_hd_bkt].count++; \ + _hd_hh_item->hh_next = NULL; \ + _hd_hh_item->hh_prev = NULL; \ + } while (0) + +#define HASH_VALUE(keyptr, keylen, hashv) \ + do { \ + HASH_FUNCTION(keyptr, keylen, hashv); \ + } while (0) + +#define HASH_FIND_BYHASHVALUE(hh, head, keyptr, keylen, hashval, out) \ + do { \ + (out) = NULL; \ + if (head) { \ + unsigned _hf_bkt; \ + HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _hf_bkt); \ + if (HASH_BLOOM_TEST((head)->hh.tbl, hashval) != 0) { \ + HASH_FIND_IN_BKT((head)->hh.tbl, hh, (head)->hh.tbl->buckets[_hf_bkt], keyptr, keylen, hashval, out); \ + } \ + } \ + } while (0) + +#define HASH_FIND(hh, head, keyptr, keylen, out) \ + do { \ + (out) = NULL; \ + if (head) { \ + unsigned _hf_hashv; \ + HASH_VALUE(keyptr, keylen, _hf_hashv); \ + HASH_FIND_BYHASHVALUE(hh, head, keyptr, keylen, _hf_hashv, out); \ + } \ + } while (0) + +#ifdef HASH_BLOOM +#define HASH_BLOOM_BITLEN (1UL << HASH_BLOOM) +#define HASH_BLOOM_BYTELEN (HASH_BLOOM_BITLEN / 8UL) + (((HASH_BLOOM_BITLEN % 8UL) != 0UL) ? 1UL : 0UL) +#define HASH_BLOOM_MAKE(tbl, oomed) \ + do { \ + (tbl)->bloom_nbits = HASH_BLOOM; \ + (tbl)->bloom_bv = (uint8_t *)uthash_malloc(HASH_BLOOM_BYTELEN); \ + if (!(tbl)->bloom_bv) { \ + HASH_RECORD_OOM(oomed); \ + } else { \ + uthash_bzero((tbl)->bloom_bv, HASH_BLOOM_BYTELEN); \ + (tbl)->bloom_sig = HASH_BLOOM_SIGNATURE; \ + } \ + } while (0) + +#define HASH_BLOOM_FREE(tbl) \ + do { \ + uthash_free((tbl)->bloom_bv, HASH_BLOOM_BYTELEN); \ + } while (0) + +#define HASH_BLOOM_BITSET(bv, idx) (bv[(idx) / 8U] |= (1U << ((idx) % 8U))) +#define HASH_BLOOM_BITTEST(bv, idx) (bv[(idx) / 8U] & (1U << ((idx) % 8U))) + +#define HASH_BLOOM_ADD(tbl, hashv) \ + HASH_BLOOM_BITSET((tbl)->bloom_bv, ((hashv) & (uint32_t)((1UL << (tbl)->bloom_nbits) - 1U))) + +#define HASH_BLOOM_TEST(tbl, hashv) \ + HASH_BLOOM_BITTEST((tbl)->bloom_bv, ((hashv) & (uint32_t)((1UL << (tbl)->bloom_nbits) - 1U))) + +#else +#define HASH_BLOOM_MAKE(tbl, oomed) +#define HASH_BLOOM_FREE(tbl) +#define HASH_BLOOM_ADD(tbl, hashv) +#define HASH_BLOOM_TEST(tbl, hashv) (1) +#define HASH_BLOOM_BYTELEN 0U +#endif + +#define HASH_MAKE_TABLE(hh, head, oomed) \ + do { \ + (head)->hh.tbl = (UT_hash_table *)uthash_malloc(sizeof(UT_hash_table)); \ + if (!(head)->hh.tbl) { \ + HASH_RECORD_OOM(oomed); \ + } else { \ + uthash_bzero((head)->hh.tbl, sizeof(UT_hash_table)); \ + (head)->hh.tbl->tail = &((head)->hh); \ + (head)->hh.tbl->num_buckets = HASH_INITIAL_NUM_BUCKETS; \ + (head)->hh.tbl->log2_num_buckets = HASH_INITIAL_NUM_BUCKETS_LOG2; \ + (head)->hh.tbl->hho = (char *)(&(head)->hh) - (char *)(head); \ + (head)->hh.tbl->buckets = (UT_hash_bucket *)uthash_malloc(HASH_INITIAL_NUM_BUCKETS * \ + sizeof(struct UT_hash_bucket)); \ + (head)->hh.tbl->signature = HASH_SIGNATURE; \ + if (!(head)->hh.tbl->buckets) { \ + HASH_RECORD_OOM(oomed); \ + uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ + } else { \ + uthash_bzero((head)->hh.tbl->buckets, HASH_INITIAL_NUM_BUCKETS * sizeof(struct UT_hash_bucket)); \ + HASH_BLOOM_MAKE((head)->hh.tbl, oomed); \ + IF_HASH_NONFATAL_OOM(if (oomed) { \ + uthash_free((head)->hh.tbl->buckets, HASH_INITIAL_NUM_BUCKETS * sizeof(struct UT_hash_bucket)); \ + uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ + }) \ + } \ + } \ + } while (0) + +#define HASH_REPLACE_BYHASHVALUE_INORDER(hh, head, fieldname, keylen_in, hashval, add, replaced, cmpfcn) \ + do { \ + (replaced) = NULL; \ + HASH_FIND_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, replaced); \ + if (replaced) { \ + HASH_DELETE(hh, head, replaced); \ + } \ + HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, &((add)->fieldname), keylen_in, hashval, add, cmpfcn); \ + } while (0) + +#define HASH_REPLACE_BYHASHVALUE(hh, head, fieldname, keylen_in, hashval, add, replaced) \ + do { \ + (replaced) = NULL; \ + HASH_FIND_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, replaced); \ + if (replaced) { \ + HASH_DELETE(hh, head, replaced); \ + } \ + HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, add); \ + } while (0) + +#define HASH_REPLACE(hh, head, fieldname, keylen_in, add, replaced) \ + do { \ + unsigned _hr_hashv; \ + HASH_VALUE(&((add)->fieldname), keylen_in, _hr_hashv); \ + HASH_REPLACE_BYHASHVALUE(hh, head, fieldname, keylen_in, _hr_hashv, add, replaced); \ + } while (0) + +#define HASH_REPLACE_INORDER(hh, head, fieldname, keylen_in, add, replaced, cmpfcn) \ + do { \ + unsigned _hr_hashv; \ + HASH_VALUE(&((add)->fieldname), keylen_in, _hr_hashv); \ + HASH_REPLACE_BYHASHVALUE_INORDER(hh, head, fieldname, keylen_in, _hr_hashv, add, replaced, cmpfcn); \ + } while (0) + +#define HASH_APPEND_LIST(hh, head, add) \ + do { \ + (add)->hh.next = NULL; \ + (add)->hh.prev = ELMT_FROM_HH((head)->hh.tbl, (head)->hh.tbl->tail); \ + (head)->hh.tbl->tail->next = (add); \ + (head)->hh.tbl->tail = &((add)->hh); \ + } while (0) + +#define HASH_AKBI_INNER_LOOP(hh, head, add, cmpfcn) \ + do { \ + do { \ + if (cmpfcn(DECLTYPE(head)(_hs_iter), add) > 0) { \ + break; \ + } \ + } while ((_hs_iter = HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->next)); \ + } while (0) + +#ifdef NO_DECLTYPE +#undef HASH_AKBI_INNER_LOOP +#define HASH_AKBI_INNER_LOOP(hh, head, add, cmpfcn) \ + do { \ + char *_hs_saved_head = (char *)(head); \ + do { \ + DECLTYPE_ASSIGN(head, _hs_iter); \ + if (cmpfcn(head, add) > 0) { \ + DECLTYPE_ASSIGN(head, _hs_saved_head); \ + break; \ + } \ + DECLTYPE_ASSIGN(head, _hs_saved_head); \ + } while ((_hs_iter = HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->next)); \ + } while (0) +#endif + +#if HASH_NONFATAL_OOM + +#define HASH_ADD_TO_TABLE(hh, head, keyptr, keylen_in, hashval, add, oomed) \ + do { \ + if (!(oomed)) { \ + unsigned _ha_bkt; \ + (head)->hh.tbl->num_items++; \ + HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _ha_bkt); \ + HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt], hh, &(add)->hh, oomed); \ + if (oomed) { \ + HASH_ROLLBACK_BKT(hh, head, &(add)->hh); \ + HASH_DELETE_HH(hh, head, &(add)->hh); \ + (add)->hh.tbl = NULL; \ + uthash_nonfatal_oom(add); \ + } else { \ + HASH_BLOOM_ADD((head)->hh.tbl, hashval); \ + HASH_EMIT_KEY(hh, head, keyptr, keylen_in); \ + } \ + } else { \ + (add)->hh.tbl = NULL; \ + uthash_nonfatal_oom(add); \ + } \ + } while (0) + +#else + +#define HASH_ADD_TO_TABLE(hh, head, keyptr, keylen_in, hashval, add, oomed) \ + do { \ + unsigned _ha_bkt; \ + (head)->hh.tbl->num_items++; \ + HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _ha_bkt); \ + HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt], hh, &(add)->hh, oomed); \ + HASH_BLOOM_ADD((head)->hh.tbl, hashval); \ + HASH_EMIT_KEY(hh, head, keyptr, keylen_in); \ + } while (0) + +#endif + +#define HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, keyptr, keylen_in, hashval, add, cmpfcn) \ + do { \ + IF_HASH_NONFATAL_OOM(int _ha_oomed = 0;) \ + (add)->hh.hashv = (hashval); \ + (add)->hh.key = (char *)(keyptr); \ + (add)->hh.keylen = (unsigned)(keylen_in); \ + if (!(head)) { \ + (add)->hh.next = NULL; \ + (add)->hh.prev = NULL; \ + HASH_MAKE_TABLE(hh, add, _ha_oomed); \ + IF_HASH_NONFATAL_OOM(if (!_ha_oomed) { ) \ + (head) = (add); \ + IF_HASH_NONFATAL_OOM( \ + }) \ + } else { \ + void *_hs_iter = (head); \ + (add)->hh.tbl = (head)->hh.tbl; \ + HASH_AKBI_INNER_LOOP(hh, head, add, cmpfcn); \ + if (_hs_iter) { \ + (add)->hh.next = _hs_iter; \ + if (((add)->hh.prev = HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->prev)) { \ + HH_FROM_ELMT((head)->hh.tbl, (add)->hh.prev)->next = (add); \ + } else { \ + (head) = (add); \ + } \ + HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->prev = (add); \ + } else { \ + HASH_APPEND_LIST(hh, head, add); \ + } \ + } \ + HASH_ADD_TO_TABLE(hh, head, keyptr, keylen_in, hashval, add, _ha_oomed); \ + HASH_FSCK(hh, head, "HASH_ADD_KEYPTR_BYHASHVALUE_INORDER"); \ + } while (0) + +#define HASH_ADD_KEYPTR_INORDER(hh, head, keyptr, keylen_in, add, cmpfcn) \ + do { \ + unsigned _hs_hashv; \ + HASH_VALUE(keyptr, keylen_in, _hs_hashv); \ + HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, keyptr, keylen_in, _hs_hashv, add, cmpfcn); \ + } while (0) + +#define HASH_ADD_BYHASHVALUE_INORDER(hh, head, fieldname, keylen_in, hashval, add, cmpfcn) \ + HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, &((add)->fieldname), keylen_in, hashval, add, cmpfcn) + +#define HASH_ADD_INORDER(hh, head, fieldname, keylen_in, add, cmpfcn) \ + HASH_ADD_KEYPTR_INORDER(hh, head, &((add)->fieldname), keylen_in, add, cmpfcn) + +#define HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, keyptr, keylen_in, hashval, add) \ + do { \ + IF_HASH_NONFATAL_OOM(int _ha_oomed = 0;) \ + (add)->hh.hashv = (hashval); \ + (add)->hh.key = (const void *)(keyptr); \ + (add)->hh.keylen = (unsigned)(keylen_in); \ + if (!(head)) { \ + (add)->hh.next = NULL; \ + (add)->hh.prev = NULL; \ + HASH_MAKE_TABLE(hh, add, _ha_oomed); \ + IF_HASH_NONFATAL_OOM(if (!_ha_oomed) { ) \ + (head) = (add); \ + IF_HASH_NONFATAL_OOM( \ + }) \ + } else { \ + (add)->hh.tbl = (head)->hh.tbl; \ + HASH_APPEND_LIST(hh, head, add); \ + } \ + HASH_ADD_TO_TABLE(hh, head, keyptr, keylen_in, hashval, add, _ha_oomed); \ + HASH_FSCK(hh, head, "HASH_ADD_KEYPTR_BYHASHVALUE"); \ + } while (0) + +#define HASH_ADD_KEYPTR(hh, head, keyptr, keylen_in, add) \ + do { \ + unsigned _ha_hashv; \ + HASH_VALUE(keyptr, keylen_in, _ha_hashv); \ + HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, keyptr, keylen_in, _ha_hashv, add); \ + } while (0) + +#define HASH_ADD_BYHASHVALUE(hh, head, fieldname, keylen_in, hashval, add) \ + HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, add) + +#define HASH_ADD(hh, head, fieldname, keylen_in, add) HASH_ADD_KEYPTR(hh, head, &((add)->fieldname), keylen_in, add) + +#define HASH_TO_BKT(hashv, num_bkts, bkt) \ + do { \ + bkt = ((hashv) & ((num_bkts)-1U)); \ + } while (0) + +/* delete "delptr" from the hash table. + * "the usual" patch-up process for the app-order doubly-linked-list. + * The use of _hd_hh_del below deserves special explanation. + * These used to be expressed using (delptr) but that led to a bug + * if someone used the same symbol for the head and deletee, like + * HASH_DELETE(hh,users,users); + * We want that to work, but by changing the head (users) below + * we were forfeiting our ability to further refer to the deletee (users) + * in the patch-up process. Solution: use scratch space to + * copy the deletee pointer, then the latter references are via that + * scratch pointer rather than through the repointed (users) symbol. + */ +#define HASH_DELETE(hh, head, delptr) HASH_DELETE_HH(hh, head, &(delptr)->hh) + +#define HASH_DELETE_HH(hh, head, delptrhh) \ + do { \ + struct UT_hash_handle *_hd_hh_del = (delptrhh); \ + if ((_hd_hh_del->prev == NULL) && (_hd_hh_del->next == NULL)) { \ + HASH_BLOOM_FREE((head)->hh.tbl); \ + uthash_free((head)->hh.tbl->buckets, (head)->hh.tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ + uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ + (head) = NULL; \ + } else { \ + unsigned _hd_bkt; \ + if (_hd_hh_del == (head)->hh.tbl->tail) { \ + (head)->hh.tbl->tail = HH_FROM_ELMT((head)->hh.tbl, _hd_hh_del->prev); \ + } \ + if (_hd_hh_del->prev != NULL) { \ + HH_FROM_ELMT((head)->hh.tbl, _hd_hh_del->prev)->next = _hd_hh_del->next; \ + } else { \ + DECLTYPE_ASSIGN(head, _hd_hh_del->next); \ + } \ + if (_hd_hh_del->next != NULL) { \ + HH_FROM_ELMT((head)->hh.tbl, _hd_hh_del->next)->prev = _hd_hh_del->prev; \ + } \ + HASH_TO_BKT(_hd_hh_del->hashv, (head)->hh.tbl->num_buckets, _hd_bkt); \ + HASH_DEL_IN_BKT((head)->hh.tbl->buckets[_hd_bkt], _hd_hh_del); \ + (head)->hh.tbl->num_items--; \ + } \ + HASH_FSCK(hh, head, "HASH_DELETE_HH"); \ + } while (0) + +/* convenience forms of HASH_FIND/HASH_ADD/HASH_DEL */ +#define HASH_FIND_STR(head, findstr, out) \ + do { \ + unsigned _uthash_hfstr_keylen = (unsigned)uthash_strlen(findstr); \ + HASH_FIND(hh, head, findstr, _uthash_hfstr_keylen, out); \ + } while (0) +#define HASH_ADD_STR(head, strfield, add) \ + do { \ + unsigned _uthash_hastr_keylen = (unsigned)uthash_strlen((add)->strfield); \ + HASH_ADD(hh, head, strfield[0], _uthash_hastr_keylen, add); \ + } while (0) +#define HASH_REPLACE_STR(head, strfield, add, replaced) \ + do { \ + unsigned _uthash_hrstr_keylen = (unsigned)uthash_strlen((add)->strfield); \ + HASH_REPLACE(hh, head, strfield[0], _uthash_hrstr_keylen, add, replaced); \ + } while (0) +#define HASH_FIND_INT(head, findint, out) HASH_FIND(hh, head, findint, sizeof(int), out) +#define HASH_ADD_INT(head, intfield, add) HASH_ADD(hh, head, intfield, sizeof(int), add) +#define HASH_REPLACE_INT(head, intfield, add, replaced) HASH_REPLACE(hh, head, intfield, sizeof(int), add, replaced) +#define HASH_FIND_PTR(head, findptr, out) HASH_FIND(hh, head, findptr, sizeof(void *), out) +#define HASH_ADD_PTR(head, ptrfield, add) HASH_ADD(hh, head, ptrfield, sizeof(void *), add) +#define HASH_REPLACE_PTR(head, ptrfield, add, replaced) HASH_REPLACE(hh, head, ptrfield, sizeof(void *), add, replaced) +#define HASH_DEL(head, delptr) HASH_DELETE(hh, head, delptr) + +/* HASH_FSCK checks hash integrity on every add/delete when HASH_DEBUG is defined. + * This is for uthash developer only; it compiles away if HASH_DEBUG isn't defined. + */ +#ifdef HASH_DEBUG +#include /* fprintf, stderr */ +#define HASH_OOPS(...) \ + do { \ + fprintf(stderr, __VA_ARGS__); \ + exit(-1); \ + } while (0) +#define HASH_FSCK(hh, head, where) \ + do { \ + struct UT_hash_handle *_thh; \ + if (head) { \ + unsigned _bkt_i; \ + unsigned _count = 0; \ + char *_prev; \ + for (_bkt_i = 0; _bkt_i < (head)->hh.tbl->num_buckets; ++_bkt_i) { \ + unsigned _bkt_count = 0; \ + _thh = (head)->hh.tbl->buckets[_bkt_i].hh_head; \ + _prev = NULL; \ + while (_thh) { \ + if (_prev != (char *)(_thh->hh_prev)) { \ + HASH_OOPS("%s: invalid hh_prev %p, actual %p\n", \ + (where), \ + (void *)_thh->hh_prev, \ + (void *)_prev); \ + } \ + _bkt_count++; \ + _prev = (char *)(_thh); \ + _thh = _thh->hh_next; \ + } \ + _count += _bkt_count; \ + if ((head)->hh.tbl->buckets[_bkt_i].count != _bkt_count) { \ + HASH_OOPS("%s: invalid bucket count %u, actual %u\n", \ + (where), \ + (head)->hh.tbl->buckets[_bkt_i].count, \ + _bkt_count); \ + } \ + } \ + if (_count != (head)->hh.tbl->num_items) { \ + HASH_OOPS("%s: invalid hh item count %u, actual %u\n", (where), (head)->hh.tbl->num_items, _count); \ + } \ + _count = 0; \ + _prev = NULL; \ + _thh = &(head)->hh; \ + while (_thh) { \ + _count++; \ + if (_prev != (char *)_thh->prev) { \ + HASH_OOPS("%s: invalid prev %p, actual %p\n", (where), (void *)_thh->prev, (void *)_prev); \ + } \ + _prev = (char *)ELMT_FROM_HH((head)->hh.tbl, _thh); \ + _thh = (_thh->next ? HH_FROM_ELMT((head)->hh.tbl, _thh->next) : NULL); \ + } \ + if (_count != (head)->hh.tbl->num_items) { \ + HASH_OOPS("%s: invalid app item count %u, actual %u\n", (where), (head)->hh.tbl->num_items, _count); \ + } \ + } \ + } while (0) +#else +#define HASH_FSCK(hh, head, where) +#endif + +/* When compiled with -DHASH_EMIT_KEYS, length-prefixed keys are emitted to + * the descriptor to which this macro is defined for tuning the hash function. + * The app can #include to get the prototype for write(2). */ +#ifdef HASH_EMIT_KEYS +#define HASH_EMIT_KEY(hh, head, keyptr, fieldlen) \ + do { \ + unsigned _klen = fieldlen; \ + write(HASH_EMIT_KEYS, &_klen, sizeof(_klen)); \ + write(HASH_EMIT_KEYS, keyptr, (unsigned long)fieldlen); \ + } while (0) +#else +#define HASH_EMIT_KEY(hh, head, keyptr, fieldlen) +#endif + +/* The Bernstein hash function, used in Perl prior to v5.6. Note (x<<5+x)=x*33. */ +#define HASH_BER(key, keylen, hashv) \ + do { \ + unsigned _hb_keylen = (unsigned)keylen; \ + const unsigned char *_hb_key = (const unsigned char *)(key); \ + (hashv) = 0; \ + while (_hb_keylen-- != 0U) { \ + (hashv) = (((hashv) << 5) + (hashv)) + *_hb_key++; \ + } \ + } while (0) + +/* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at + * http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx */ +#define HASH_SAX(key, keylen, hashv) \ + do { \ + unsigned _sx_i; \ + const unsigned char *_hs_key = (const unsigned char *)(key); \ + hashv = 0; \ + for (_sx_i = 0; _sx_i < keylen; _sx_i++) { \ + hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i]; \ + } \ + } while (0) +/* FNV-1a variation */ +#define HASH_FNV(key, keylen, hashv) \ + do { \ + unsigned _fn_i; \ + const unsigned char *_hf_key = (const unsigned char *)(key); \ + (hashv) = 2166136261U; \ + for (_fn_i = 0; _fn_i < keylen; _fn_i++) { \ + hashv = hashv ^ _hf_key[_fn_i]; \ + hashv = hashv * 16777619U; \ + } \ + } while (0) + +#define HASH_OAT(key, keylen, hashv) \ + do { \ + unsigned _ho_i; \ + const unsigned char *_ho_key = (const unsigned char *)(key); \ + hashv = 0; \ + for (_ho_i = 0; _ho_i < keylen; _ho_i++) { \ + hashv += _ho_key[_ho_i]; \ + hashv += (hashv << 10); \ + hashv ^= (hashv >> 6); \ + } \ + hashv += (hashv << 3); \ + hashv ^= (hashv >> 11); \ + hashv += (hashv << 15); \ + } while (0) + +#define HASH_JEN_MIX(a, b, c) \ + do { \ + a -= b; \ + a -= c; \ + a ^= (c >> 13); \ + b -= c; \ + b -= a; \ + b ^= (a << 8); \ + c -= a; \ + c -= b; \ + c ^= (b >> 13); \ + a -= b; \ + a -= c; \ + a ^= (c >> 12); \ + b -= c; \ + b -= a; \ + b ^= (a << 16); \ + c -= a; \ + c -= b; \ + c ^= (b >> 5); \ + a -= b; \ + a -= c; \ + a ^= (c >> 3); \ + b -= c; \ + b -= a; \ + b ^= (a << 10); \ + c -= a; \ + c -= b; \ + c ^= (b >> 15); \ + } while (0) + +#define HASH_JEN(key, keylen, hashv) \ + do { \ + unsigned _hj_i, _hj_j, _hj_k; \ + unsigned const char *_hj_key = (unsigned const char *)(key); \ + hashv = 0xfeedbeefu; \ + _hj_i = _hj_j = 0x9e3779b9u; \ + _hj_k = (unsigned)(keylen); \ + while (_hj_k >= 12U) { \ + _hj_i += (_hj_key[0] + ((unsigned)_hj_key[1] << 8) + ((unsigned)_hj_key[2] << 16) + \ + ((unsigned)_hj_key[3] << 24)); \ + _hj_j += (_hj_key[4] + ((unsigned)_hj_key[5] << 8) + ((unsigned)_hj_key[6] << 16) + \ + ((unsigned)_hj_key[7] << 24)); \ + hashv += (_hj_key[8] + ((unsigned)_hj_key[9] << 8) + ((unsigned)_hj_key[10] << 16) + \ + ((unsigned)_hj_key[11] << 24)); \ + \ + HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ + \ + _hj_key += 12; \ + _hj_k -= 12U; \ + } \ + hashv += (unsigned)(keylen); \ + switch (_hj_k) { \ + case 11: \ + hashv += ((unsigned)_hj_key[10] << 24); /* FALLTHROUGH */ \ + case 10: \ + hashv += ((unsigned)_hj_key[9] << 16); /* FALLTHROUGH */ \ + case 9: \ + hashv += ((unsigned)_hj_key[8] << 8); /* FALLTHROUGH */ \ + case 8: \ + _hj_j += ((unsigned)_hj_key[7] << 24); /* FALLTHROUGH */ \ + case 7: \ + _hj_j += ((unsigned)_hj_key[6] << 16); /* FALLTHROUGH */ \ + case 6: \ + _hj_j += ((unsigned)_hj_key[5] << 8); /* FALLTHROUGH */ \ + case 5: \ + _hj_j += _hj_key[4]; /* FALLTHROUGH */ \ + case 4: \ + _hj_i += ((unsigned)_hj_key[3] << 24); /* FALLTHROUGH */ \ + case 3: \ + _hj_i += ((unsigned)_hj_key[2] << 16); /* FALLTHROUGH */ \ + case 2: \ + _hj_i += ((unsigned)_hj_key[1] << 8); /* FALLTHROUGH */ \ + case 1: \ + _hj_i += _hj_key[0]; /* FALLTHROUGH */ \ + default:; \ + } \ + HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ + } while (0) + +/* The Paul Hsieh hash function */ +#undef get16bits +#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) || defined(_MSC_VER) || defined(__BORLANDC__) || \ + defined(__TURBOC__) +#define get16bits(d) (*((const uint16_t *)(d))) +#endif + +#if !defined(get16bits) +#define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8) + (uint32_t)(((const uint8_t *)(d))[0])) +#endif +#define HASH_SFH(key, keylen, hashv) \ + do { \ + unsigned const char *_sfh_key = (unsigned const char *)(key); \ + uint32_t _sfh_tmp, _sfh_len = (uint32_t)keylen; \ + \ + unsigned _sfh_rem = _sfh_len & 3U; \ + _sfh_len >>= 2; \ + hashv = 0xcafebabeu; \ + \ + /* Main loop */ \ + for (; _sfh_len > 0U; _sfh_len--) { \ + hashv += get16bits(_sfh_key); \ + _sfh_tmp = ((uint32_t)(get16bits(_sfh_key + 2)) << 11) ^ hashv; \ + hashv = (hashv << 16) ^ _sfh_tmp; \ + _sfh_key += 2U * sizeof(uint16_t); \ + hashv += hashv >> 11; \ + } \ + \ + /* Handle end cases */ \ + switch (_sfh_rem) { \ + case 3: \ + hashv += get16bits(_sfh_key); \ + hashv ^= hashv << 16; \ + hashv ^= (uint32_t)(_sfh_key[sizeof(uint16_t)]) << 18; \ + hashv += hashv >> 11; \ + break; \ + case 2: \ + hashv += get16bits(_sfh_key); \ + hashv ^= hashv << 11; \ + hashv += hashv >> 17; \ + break; \ + case 1: \ + hashv += *_sfh_key; \ + hashv ^= hashv << 10; \ + hashv += hashv >> 1; \ + break; \ + default:; \ + } \ + \ + /* Force "avalanching" of final 127 bits */ \ + hashv ^= hashv << 3; \ + hashv += hashv >> 5; \ + hashv ^= hashv << 4; \ + hashv += hashv >> 17; \ + hashv ^= hashv << 25; \ + hashv += hashv >> 6; \ + } while (0) + +/* iterate over items in a known bucket to find desired item */ +#define HASH_FIND_IN_BKT(tbl, hh, head, keyptr, keylen_in, hashval, out) \ + do { \ + if ((head).hh_head != NULL) { \ + DECLTYPE_ASSIGN(out, ELMT_FROM_HH(tbl, (head).hh_head)); \ + } else { \ + (out) = NULL; \ + } \ + while ((out) != NULL) { \ + if ((out)->hh.hashv == (hashval) && (out)->hh.keylen == (keylen_in)) { \ + if (HASH_KEYCMP((out)->hh.key, keyptr, keylen_in) == 0) { \ + break; \ + } \ + } \ + if ((out)->hh.hh_next != NULL) { \ + DECLTYPE_ASSIGN(out, ELMT_FROM_HH(tbl, (out)->hh.hh_next)); \ + } else { \ + (out) = NULL; \ + } \ + } \ + } while (0) + +/* add an item to a bucket */ +#define HASH_ADD_TO_BKT(head, hh, addhh, oomed) \ + do { \ + UT_hash_bucket *_ha_head = &(head); \ + _ha_head->count++; \ + (addhh)->hh_next = _ha_head->hh_head; \ + (addhh)->hh_prev = NULL; \ + if (_ha_head->hh_head != NULL) { \ + _ha_head->hh_head->hh_prev = (addhh); \ + } \ + _ha_head->hh_head = (addhh); \ + if ((_ha_head->count >= ((_ha_head->expand_mult + 1U) * HASH_BKT_CAPACITY_THRESH)) && \ + !(addhh)->tbl->noexpand) { \ + HASH_EXPAND_BUCKETS(addhh, (addhh)->tbl, oomed); \ + IF_HASH_NONFATAL_OOM(if (oomed) { HASH_DEL_IN_BKT(head, addhh); }) \ + } \ + } while (0) + +/* remove an item from a given bucket */ +#define HASH_DEL_IN_BKT(head, delhh) \ + do { \ + UT_hash_bucket *_hd_head = &(head); \ + _hd_head->count--; \ + if (_hd_head->hh_head == (delhh)) { \ + _hd_head->hh_head = (delhh)->hh_next; \ + } \ + if ((delhh)->hh_prev) { \ + (delhh)->hh_prev->hh_next = (delhh)->hh_next; \ + } \ + if ((delhh)->hh_next) { \ + (delhh)->hh_next->hh_prev = (delhh)->hh_prev; \ + } \ + } while (0) + +/* Bucket expansion has the effect of doubling the number of buckets + * and redistributing the items into the new buckets. Ideally the + * items will distribute more or less evenly into the new buckets + * (the extent to which this is true is a measure of the quality of + * the hash function as it applies to the key domain). + * + * With the items distributed into more buckets, the chain length + * (item count) in each bucket is reduced. Thus by expanding buckets + * the hash keeps a bound on the chain length. This bounded chain + * length is the essence of how a hash provides constant time lookup. + * + * The calculation of tbl->ideal_chain_maxlen below deserves some + * explanation. First, keep in mind that we're calculating the ideal + * maximum chain length based on the *new* (doubled) bucket count. + * In fractions this is just n/b (n=number of items,b=new num buckets). + * Since the ideal chain length is an integer, we want to calculate + * ceil(n/b). We don't depend on floating point arithmetic in this + * hash, so to calculate ceil(n/b) with integers we could write + * + * ceil(n/b) = (n/b) + ((n%b)?1:0) + * + * and in fact a previous version of this hash did just that. + * But now we have improved things a bit by recognizing that b is + * always a power of two. We keep its base 2 log handy (call it lb), + * so now we can write this with a bit shift and logical AND: + * + * ceil(n/b) = (n>>lb) + ( (n & (b-1)) ? 1:0) + * + */ +#define HASH_EXPAND_BUCKETS(hh, tbl, oomed) \ + do { \ + unsigned _he_bkt; \ + unsigned _he_bkt_i; \ + struct UT_hash_handle *_he_thh, *_he_hh_nxt; \ + UT_hash_bucket *_he_new_buckets, *_he_newbkt; \ + _he_new_buckets = (UT_hash_bucket *)uthash_malloc(sizeof(struct UT_hash_bucket) * (tbl)->num_buckets * 2U); \ + if (!_he_new_buckets) { \ + HASH_RECORD_OOM(oomed); \ + } else { \ + uthash_bzero(_he_new_buckets, sizeof(struct UT_hash_bucket) * (tbl)->num_buckets * 2U); \ + (tbl)->ideal_chain_maxlen = ((tbl)->num_items >> ((tbl)->log2_num_buckets + 1U)) + \ + ((((tbl)->num_items & (((tbl)->num_buckets * 2U) - 1U)) != 0U) ? 1U : 0U); \ + (tbl)->nonideal_items = 0; \ + for (_he_bkt_i = 0; _he_bkt_i < (tbl)->num_buckets; _he_bkt_i++) { \ + _he_thh = (tbl)->buckets[_he_bkt_i].hh_head; \ + while (_he_thh != NULL) { \ + _he_hh_nxt = _he_thh->hh_next; \ + HASH_TO_BKT(_he_thh->hashv, (tbl)->num_buckets * 2U, _he_bkt); \ + _he_newbkt = &(_he_new_buckets[_he_bkt]); \ + if (++(_he_newbkt->count) > (tbl)->ideal_chain_maxlen) { \ + (tbl)->nonideal_items++; \ + if (_he_newbkt->count > _he_newbkt->expand_mult * (tbl)->ideal_chain_maxlen) { \ + _he_newbkt->expand_mult++; \ + } \ + } \ + _he_thh->hh_prev = NULL; \ + _he_thh->hh_next = _he_newbkt->hh_head; \ + if (_he_newbkt->hh_head != NULL) { \ + _he_newbkt->hh_head->hh_prev = _he_thh; \ + } \ + _he_newbkt->hh_head = _he_thh; \ + _he_thh = _he_hh_nxt; \ + } \ + } \ + uthash_free((tbl)->buckets, (tbl)->num_buckets * sizeof(struct UT_hash_bucket)); \ + (tbl)->num_buckets *= 2U; \ + (tbl)->log2_num_buckets++; \ + (tbl)->buckets = _he_new_buckets; \ + (tbl)->ineff_expands = ((tbl)->nonideal_items > ((tbl)->num_items >> 1)) ? ((tbl)->ineff_expands + 1U) \ + : 0U; \ + if ((tbl)->ineff_expands > 1U) { \ + (tbl)->noexpand = 1; \ + uthash_noexpand_fyi(tbl); \ + } \ + uthash_expand_fyi(tbl); \ + } \ + } while (0) + +/* This is an adaptation of Simon Tatham's O(n log(n)) mergesort */ +/* Note that HASH_SORT assumes the hash handle name to be hh. + * HASH_SRT was added to allow the hash handle name to be passed in. */ +#define HASH_SORT(head, cmpfcn) HASH_SRT(hh, head, cmpfcn) +#define HASH_SRT(hh, head, cmpfcn) \ + do { \ + unsigned _hs_i; \ + unsigned _hs_looping, _hs_nmerges, _hs_insize, _hs_psize, _hs_qsize; \ + struct UT_hash_handle *_hs_p, *_hs_q, *_hs_e, *_hs_list, *_hs_tail; \ + if (head != NULL) { \ + _hs_insize = 1; \ + _hs_looping = 1; \ + _hs_list = &((head)->hh); \ + while (_hs_looping != 0U) { \ + _hs_p = _hs_list; \ + _hs_list = NULL; \ + _hs_tail = NULL; \ + _hs_nmerges = 0; \ + while (_hs_p != NULL) { \ + _hs_nmerges++; \ + _hs_q = _hs_p; \ + _hs_psize = 0; \ + for (_hs_i = 0; _hs_i < _hs_insize; ++_hs_i) { \ + _hs_psize++; \ + _hs_q = ((_hs_q->next != NULL) ? HH_FROM_ELMT((head)->hh.tbl, _hs_q->next) : NULL); \ + if (_hs_q == NULL) { \ + break; \ + } \ + } \ + _hs_qsize = _hs_insize; \ + while ((_hs_psize != 0U) || ((_hs_qsize != 0U) && (_hs_q != NULL))) { \ + if (_hs_psize == 0U) { \ + _hs_e = _hs_q; \ + _hs_q = ((_hs_q->next != NULL) ? HH_FROM_ELMT((head)->hh.tbl, _hs_q->next) : NULL); \ + _hs_qsize--; \ + } else if ((_hs_qsize == 0U) || (_hs_q == NULL)) { \ + _hs_e = _hs_p; \ + if (_hs_p != NULL) { \ + _hs_p = ((_hs_p->next != NULL) ? HH_FROM_ELMT((head)->hh.tbl, _hs_p->next) : NULL); \ + } \ + _hs_psize--; \ + } else if ((cmpfcn(DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl, _hs_p)), \ + DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl, _hs_q)))) <= 0) { \ + _hs_e = _hs_p; \ + if (_hs_p != NULL) { \ + _hs_p = ((_hs_p->next != NULL) ? HH_FROM_ELMT((head)->hh.tbl, _hs_p->next) : NULL); \ + } \ + _hs_psize--; \ + } else { \ + _hs_e = _hs_q; \ + _hs_q = ((_hs_q->next != NULL) ? HH_FROM_ELMT((head)->hh.tbl, _hs_q->next) : NULL); \ + _hs_qsize--; \ + } \ + if (_hs_tail != NULL) { \ + _hs_tail->next = ((_hs_e != NULL) ? ELMT_FROM_HH((head)->hh.tbl, _hs_e) : NULL); \ + } else { \ + _hs_list = _hs_e; \ + } \ + if (_hs_e != NULL) { \ + _hs_e->prev = ((_hs_tail != NULL) ? ELMT_FROM_HH((head)->hh.tbl, _hs_tail) : NULL); \ + } \ + _hs_tail = _hs_e; \ + } \ + _hs_p = _hs_q; \ + } \ + if (_hs_tail != NULL) { \ + _hs_tail->next = NULL; \ + } \ + if (_hs_nmerges <= 1U) { \ + _hs_looping = 0; \ + (head)->hh.tbl->tail = _hs_tail; \ + DECLTYPE_ASSIGN(head, ELMT_FROM_HH((head)->hh.tbl, _hs_list)); \ + } \ + _hs_insize *= 2U; \ + } \ + HASH_FSCK(hh, head, "HASH_SRT"); \ + } \ + } while (0) + +/* This function selects items from one hash into another hash. + * The end result is that the selected items have dual presence + * in both hashes. There is no copy of the items made; rather + * they are added into the new hash through a secondary hash + * hash handle that must be present in the structure. */ +#define HASH_SELECT(hh_dst, dst, hh_src, src, cond) \ + do { \ + unsigned _src_bkt, _dst_bkt; \ + void *_last_elt = NULL, *_elt; \ + UT_hash_handle *_src_hh, *_dst_hh, *_last_elt_hh = NULL; \ + ptrdiff_t _dst_hho = ((char *)(&(dst)->hh_dst) - (char *)(dst)); \ + if ((src) != NULL) { \ + for (_src_bkt = 0; _src_bkt < (src)->hh_src.tbl->num_buckets; _src_bkt++) { \ + for (_src_hh = (src)->hh_src.tbl->buckets[_src_bkt].hh_head; _src_hh != NULL; \ + _src_hh = _src_hh->hh_next) { \ + _elt = ELMT_FROM_HH((src)->hh_src.tbl, _src_hh); \ + if (cond(_elt)) { \ + IF_HASH_NONFATAL_OOM(int _hs_oomed = 0;) \ + _dst_hh = (UT_hash_handle *)(void *)(((char *)_elt) + _dst_hho); \ + _dst_hh->key = _src_hh->key; \ + _dst_hh->keylen = _src_hh->keylen; \ + _dst_hh->hashv = _src_hh->hashv; \ + _dst_hh->prev = _last_elt; \ + _dst_hh->next = NULL; \ + if (_last_elt_hh != NULL) { \ + _last_elt_hh->next = _elt; \ + } \ + if ((dst) == NULL) { \ + DECLTYPE_ASSIGN(dst, _elt); \ + HASH_MAKE_TABLE(hh_dst, dst, _hs_oomed); \ + IF_HASH_NONFATAL_OOM(if (_hs_oomed) { \ + uthash_nonfatal_oom(_elt); \ + (dst) = NULL; \ + continue; \ + }) \ + } else { \ + _dst_hh->tbl = (dst)->hh_dst.tbl; \ + } \ + HASH_TO_BKT(_dst_hh->hashv, _dst_hh->tbl->num_buckets, _dst_bkt); \ + HASH_ADD_TO_BKT(_dst_hh->tbl->buckets[_dst_bkt], hh_dst, _dst_hh, _hs_oomed); \ + (dst)->hh_dst.tbl->num_items++; \ + IF_HASH_NONFATAL_OOM(if (_hs_oomed) { \ + HASH_ROLLBACK_BKT(hh_dst, dst, _dst_hh); \ + HASH_DELETE_HH(hh_dst, dst, _dst_hh); \ + _dst_hh->tbl = NULL; \ + uthash_nonfatal_oom(_elt); \ + continue; \ + }) \ + HASH_BLOOM_ADD(_dst_hh->tbl, _dst_hh->hashv); \ + _last_elt = _elt; \ + _last_elt_hh = _dst_hh; \ + } \ + } \ + } \ + } \ + HASH_FSCK(hh_dst, dst, "HASH_SELECT"); \ + } while (0) + +#define HASH_CLEAR(hh, head) \ + do { \ + if ((head) != NULL) { \ + HASH_BLOOM_FREE((head)->hh.tbl); \ + uthash_free((head)->hh.tbl->buckets, (head)->hh.tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ + uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ + (head) = NULL; \ + } \ + } while (0) + +#define HASH_OVERHEAD(hh, head) \ + (((head) != NULL) ? ((size_t)(((head)->hh.tbl->num_items * sizeof(UT_hash_handle)) + \ + ((head)->hh.tbl->num_buckets * sizeof(UT_hash_bucket)) + sizeof(UT_hash_table) + \ + (HASH_BLOOM_BYTELEN))) \ + : 0U) + +#ifdef NO_DECLTYPE +#define HASH_ITER(hh, head, el, tmp) \ + for (((el) = (head)), ((*(char **)(&(tmp))) = (char *)((head != NULL) ? (head)->hh.next : NULL)); (el) != NULL; \ + ((el) = (tmp)), ((*(char **)(&(tmp))) = (char *)((tmp != NULL) ? (tmp)->hh.next : NULL))) +#else +#define HASH_ITER(hh, head, el, tmp) \ + for (((el) = (head)), ((tmp) = DECLTYPE(el)((head != NULL) ? (head)->hh.next : NULL)); (el) != NULL; \ + ((el) = (tmp)), ((tmp) = DECLTYPE(el)((tmp != NULL) ? (tmp)->hh.next : NULL))) +#endif + +/* obtain a count of items in the hash */ +#define HASH_COUNT(head) HASH_CNT(hh, head) +#define HASH_CNT(hh, head) ((head != NULL) ? ((head)->hh.tbl->num_items) : 0U) + +typedef struct UT_hash_bucket { + struct UT_hash_handle *hh_head; + unsigned count; + + /* expand_mult is normally set to 0. In this situation, the max chain length + * threshold is enforced at its default value, HASH_BKT_CAPACITY_THRESH. (If + * the bucket's chain exceeds this length, bucket expansion is triggered). + * However, setting expand_mult to a non-zero value delays bucket expansion + * (that would be triggered by additions to this particular bucket) + * until its chain length reaches a *multiple* of HASH_BKT_CAPACITY_THRESH. + * (The multiplier is simply expand_mult+1). The whole idea of this + * multiplier is to reduce bucket expansions, since they are expensive, in + * situations where we know that a particular bucket tends to be overused. + * It is better to let its chain length grow to a longer yet-still-bounded + * value, than to do an O(n) bucket expansion too often. + */ + unsigned expand_mult; + +} UT_hash_bucket; + +/* random signature used only to find hash tables in external analysis */ +#define HASH_SIGNATURE 0xa0111fe1u +#define HASH_BLOOM_SIGNATURE 0xb12220f2u + +typedef struct UT_hash_table { + UT_hash_bucket *buckets; + unsigned num_buckets, log2_num_buckets; + unsigned num_items; + struct UT_hash_handle *tail; /* tail hh in app order, for fast append */ + ptrdiff_t hho; /* hash handle offset (byte pos of hash handle in element */ + + /* in an ideal situation (all buckets used equally), no bucket would have + * more than ceil(#items/#buckets) items. that's the ideal chain length. */ + unsigned ideal_chain_maxlen; + + /* nonideal_items is the number of items in the hash whose chain position + * exceeds the ideal chain maxlen. these items pay the penalty for an uneven + * hash distribution; reaching them in a chain traversal takes >ideal steps */ + unsigned nonideal_items; + + /* ineffective expands occur when a bucket doubling was performed, but + * afterward, more than half the items in the hash had nonideal chain + * positions. If this happens on two consecutive expansions we inhibit any + * further expansion, as it's not helping; this happens when the hash + * function isn't a good fit for the key domain. When expansion is inhibited + * the hash will still work, albeit no longer in constant time. */ + unsigned ineff_expands, noexpand; + + uint32_t signature; /* used only to find hash tables in external analysis */ +#ifdef HASH_BLOOM + uint32_t bloom_sig; /* used only to test_case bloom exists in external analysis */ + uint8_t *bloom_bv; + uint8_t bloom_nbits; +#endif + +} UT_hash_table; + +typedef struct UT_hash_handle { + struct UT_hash_table *tbl; + void *prev; /* prev element in app order */ + void *next; /* next element in app order */ + struct UT_hash_handle *hh_prev; /* previous hh in bucket order */ + struct UT_hash_handle *hh_next; /* next hh in bucket order */ + const void *key; /* ptr to enclosing struct's key */ + unsigned keylen; /* enclosing struct's key len */ + unsigned hashv; /* result of hash-fcn(key) */ +} UT_hash_handle; + +#endif /* UTHASH_H */ diff --git a/NetTunnelSDK/uthash/utlist.h b/NetTunnelSDK/uthash/utlist.h new file mode 100644 index 0000000..ba81aa0 --- /dev/null +++ b/NetTunnelSDK/uthash/utlist.h @@ -0,0 +1,1131 @@ +/* +Copyright (c) 2007-2021, Troy D. Hanson http://troydhanson.github.com/uthash/ +All rights reserved. + +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. + +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. +*/ + +#ifndef UTLIST_H +#define UTLIST_H + +#define UTLIST_VERSION 2.3.0 + +#include + +/* + * This file contains macros to manipulate singly and doubly-linked lists. + * + * 1. LL_ macros: singly-linked lists. + * 2. DL_ macros: doubly-linked lists. + * 3. CDL_ macros: circular doubly-linked lists. + * + * To use singly-linked lists, your structure must have a "next" pointer. + * To use doubly-linked lists, your structure must "prev" and "next" pointers. + * Either way, the pointer to the head of the list must be initialized to NULL. + * + * ----------------.EXAMPLE ------------------------- + * struct item { + * int id; + * struct item *prev, *next; + * } + * + * struct item *list = NULL: + * + * int main() { + * struct item *item; + * ... allocate and populate item ... + * DL_APPEND(list, item); + * } + * -------------------------------------------------- + * + * For doubly-linked lists, the append and delete macros are O(1) + * For singly-linked lists, append and delete are O(n) but prepend is O(1) + * The sort macro is O(n log(n)) for all types of single/double/circular lists. + */ + +/* These macros use decltype or the earlier __typeof GNU extension. + As decltype is only available in newer compilers (VS2010 or gcc 4.3+ + when compiling c++ source) this code uses whatever method is needed + or, for VS2008 where neither is available, uses casting workarounds. */ +#if !defined(LDECLTYPE) && !defined(NO_DECLTYPE) +#if defined(_MSC_VER) /* MS compiler */ +#if _MSC_VER >= 1600 && defined(__cplusplus) /* VS2010 or newer in C++ mode */ +#define LDECLTYPE(x) decltype(x) +#else /* VS2008 or older (or VS2010 in C mode) */ +#define NO_DECLTYPE +#endif +#elif defined(__BORLANDC__) || defined(__ICCARM__) || defined(__LCC__) || defined(__WATCOMC__) +#define NO_DECLTYPE +#else /* GNU, Sun and other compilers */ +#define LDECLTYPE(x) __typeof(x) +#endif +#endif + +/* for VS2008 we use some workarounds to get around the lack of decltype, + * namely, we always reassign our tmp variable to the list head if we need + * to dereference its prev/next pointers, and save/restore the real head.*/ +#ifdef NO_DECLTYPE +#define IF_NO_DECLTYPE(x) x +#define LDECLTYPE(x) char * +#define UTLIST_SV(elt, list) \ + _tmp = (char *)(list); \ + { \ + char **_alias = (char **)&(list); \ + *_alias = (elt); \ + } +#define UTLIST_NEXT(elt, list, next) ((char *)((list)->next)) +#define UTLIST_NEXTASGN(elt, list, to, next) \ + { \ + char **_alias = (char **)&((list)->next); \ + *_alias = (char *)(to); \ + } +/* #define UTLIST_PREV(elt,list,prev) ((char*)((list)->prev)) */ +#define UTLIST_PREVASGN(elt, list, to, prev) \ + { \ + char **_alias = (char **)&((list)->prev); \ + *_alias = (char *)(to); \ + } +#define UTLIST_RS(list) \ + { \ + char **_alias = (char **)&(list); \ + *_alias = _tmp; \ + } +#define UTLIST_CASTASGN(a, b) \ + { \ + char **_alias = (char **)&(a); \ + *_alias = (char *)(b); \ + } +#else +#define IF_NO_DECLTYPE(x) +#define UTLIST_SV(elt, list) +#define UTLIST_NEXT(elt, list, next) ((elt)->next) +#define UTLIST_NEXTASGN(elt, list, to, next) ((elt)->next) = (to) +/* #define UTLIST_PREV(elt,list,prev) ((elt)->prev) */ +#define UTLIST_PREVASGN(elt, list, to, prev) ((elt)->prev) = (to) +#define UTLIST_RS(list) +#define UTLIST_CASTASGN(a, b) (a) = (b) +#endif + +/****************************************************************************** + * The sort macro is an adaptation of Simon Tatham's O(n log(n)) mergesort * + * Unwieldy variable names used here to avoid shadowing passed-in variables. * + *****************************************************************************/ +#define LL_SORT(list, cmp) LL_SORT2(list, cmp, next) + +#define LL_SORT2(list, cmp, next) \ + do { \ + LDECLTYPE(list) _ls_p; \ + LDECLTYPE(list) _ls_q; \ + LDECLTYPE(list) _ls_e; \ + LDECLTYPE(list) _ls_tail; \ + IF_NO_DECLTYPE(LDECLTYPE(list) _tmp;) \ + int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ + if (list) { \ + _ls_insize = 1; \ + _ls_looping = 1; \ + while (_ls_looping) { \ + UTLIST_CASTASGN(_ls_p, list); \ + (list) = NULL; \ + _ls_tail = NULL; \ + _ls_nmerges = 0; \ + while (_ls_p) { \ + _ls_nmerges++; \ + _ls_q = _ls_p; \ + _ls_psize = 0; \ + for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) { \ + _ls_psize++; \ + UTLIST_SV(_ls_q, list); \ + _ls_q = UTLIST_NEXT(_ls_q, list, next); \ + UTLIST_RS(list); \ + if (!_ls_q) \ + break; \ + } \ + _ls_qsize = _ls_insize; \ + while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) { \ + if (_ls_psize == 0) { \ + _ls_e = _ls_q; \ + UTLIST_SV(_ls_q, list); \ + _ls_q = UTLIST_NEXT(_ls_q, list, next); \ + UTLIST_RS(list); \ + _ls_qsize--; \ + } else if (_ls_qsize == 0 || !_ls_q) { \ + _ls_e = _ls_p; \ + UTLIST_SV(_ls_p, list); \ + _ls_p = UTLIST_NEXT(_ls_p, list, next); \ + UTLIST_RS(list); \ + _ls_psize--; \ + } else if (cmp(_ls_p, _ls_q) <= 0) { \ + _ls_e = _ls_p; \ + UTLIST_SV(_ls_p, list); \ + _ls_p = UTLIST_NEXT(_ls_p, list, next); \ + UTLIST_RS(list); \ + _ls_psize--; \ + } else { \ + _ls_e = _ls_q; \ + UTLIST_SV(_ls_q, list); \ + _ls_q = UTLIST_NEXT(_ls_q, list, next); \ + UTLIST_RS(list); \ + _ls_qsize--; \ + } \ + if (_ls_tail) { \ + UTLIST_SV(_ls_tail, list); \ + UTLIST_NEXTASGN(_ls_tail, list, _ls_e, next); \ + UTLIST_RS(list); \ + } else { \ + UTLIST_CASTASGN(list, _ls_e); \ + } \ + _ls_tail = _ls_e; \ + } \ + _ls_p = _ls_q; \ + } \ + if (_ls_tail) { \ + UTLIST_SV(_ls_tail, list); \ + UTLIST_NEXTASGN(_ls_tail, list, NULL, next); \ + UTLIST_RS(list); \ + } \ + if (_ls_nmerges <= 1) { \ + _ls_looping = 0; \ + } \ + _ls_insize *= 2; \ + } \ + } \ + } while (0) + +#define DL_SORT(list, cmp) DL_SORT2(list, cmp, prev, next) + +#define DL_SORT2(list, cmp, prev, next) \ + do { \ + LDECLTYPE(list) _ls_p; \ + LDECLTYPE(list) _ls_q; \ + LDECLTYPE(list) _ls_e; \ + LDECLTYPE(list) _ls_tail; \ + IF_NO_DECLTYPE(LDECLTYPE(list) _tmp;) \ + int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ + if (list) { \ + _ls_insize = 1; \ + _ls_looping = 1; \ + while (_ls_looping) { \ + UTLIST_CASTASGN(_ls_p, list); \ + (list) = NULL; \ + _ls_tail = NULL; \ + _ls_nmerges = 0; \ + while (_ls_p) { \ + _ls_nmerges++; \ + _ls_q = _ls_p; \ + _ls_psize = 0; \ + for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) { \ + _ls_psize++; \ + UTLIST_SV(_ls_q, list); \ + _ls_q = UTLIST_NEXT(_ls_q, list, next); \ + UTLIST_RS(list); \ + if (!_ls_q) \ + break; \ + } \ + _ls_qsize = _ls_insize; \ + while ((_ls_psize > 0) || ((_ls_qsize > 0) && _ls_q)) { \ + if (_ls_psize == 0) { \ + _ls_e = _ls_q; \ + UTLIST_SV(_ls_q, list); \ + _ls_q = UTLIST_NEXT(_ls_q, list, next); \ + UTLIST_RS(list); \ + _ls_qsize--; \ + } else if ((_ls_qsize == 0) || (!_ls_q)) { \ + _ls_e = _ls_p; \ + UTLIST_SV(_ls_p, list); \ + _ls_p = UTLIST_NEXT(_ls_p, list, next); \ + UTLIST_RS(list); \ + _ls_psize--; \ + } else if (cmp(_ls_p, _ls_q) <= 0) { \ + _ls_e = _ls_p; \ + UTLIST_SV(_ls_p, list); \ + _ls_p = UTLIST_NEXT(_ls_p, list, next); \ + UTLIST_RS(list); \ + _ls_psize--; \ + } else { \ + _ls_e = _ls_q; \ + UTLIST_SV(_ls_q, list); \ + _ls_q = UTLIST_NEXT(_ls_q, list, next); \ + UTLIST_RS(list); \ + _ls_qsize--; \ + } \ + if (_ls_tail) { \ + UTLIST_SV(_ls_tail, list); \ + UTLIST_NEXTASGN(_ls_tail, list, _ls_e, next); \ + UTLIST_RS(list); \ + } else { \ + UTLIST_CASTASGN(list, _ls_e); \ + } \ + UTLIST_SV(_ls_e, list); \ + UTLIST_PREVASGN(_ls_e, list, _ls_tail, prev); \ + UTLIST_RS(list); \ + _ls_tail = _ls_e; \ + } \ + _ls_p = _ls_q; \ + } \ + UTLIST_CASTASGN((list)->prev, _ls_tail); \ + UTLIST_SV(_ls_tail, list); \ + UTLIST_NEXTASGN(_ls_tail, list, NULL, next); \ + UTLIST_RS(list); \ + if (_ls_nmerges <= 1) { \ + _ls_looping = 0; \ + } \ + _ls_insize *= 2; \ + } \ + } \ + } while (0) + +#define CDL_SORT(list, cmp) CDL_SORT2(list, cmp, prev, next) + +#define CDL_SORT2(list, cmp, prev, next) \ + do { \ + LDECLTYPE(list) _ls_p; \ + LDECLTYPE(list) _ls_q; \ + LDECLTYPE(list) _ls_e; \ + LDECLTYPE(list) _ls_tail; \ + LDECLTYPE(list) _ls_oldhead; \ + LDECLTYPE(list) _tmp; \ + int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ + if (list) { \ + _ls_insize = 1; \ + _ls_looping = 1; \ + while (_ls_looping) { \ + UTLIST_CASTASGN(_ls_p, list); \ + UTLIST_CASTASGN(_ls_oldhead, list); \ + (list) = NULL; \ + _ls_tail = NULL; \ + _ls_nmerges = 0; \ + while (_ls_p) { \ + _ls_nmerges++; \ + _ls_q = _ls_p; \ + _ls_psize = 0; \ + for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) { \ + _ls_psize++; \ + UTLIST_SV(_ls_q, list); \ + if (UTLIST_NEXT(_ls_q, list, next) == _ls_oldhead) { \ + _ls_q = NULL; \ + } else { \ + _ls_q = UTLIST_NEXT(_ls_q, list, next); \ + } \ + UTLIST_RS(list); \ + if (!_ls_q) \ + break; \ + } \ + _ls_qsize = _ls_insize; \ + while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) { \ + if (_ls_psize == 0) { \ + _ls_e = _ls_q; \ + UTLIST_SV(_ls_q, list); \ + _ls_q = UTLIST_NEXT(_ls_q, list, next); \ + UTLIST_RS(list); \ + _ls_qsize--; \ + if (_ls_q == _ls_oldhead) { \ + _ls_q = NULL; \ + } \ + } else if (_ls_qsize == 0 || !_ls_q) { \ + _ls_e = _ls_p; \ + UTLIST_SV(_ls_p, list); \ + _ls_p = UTLIST_NEXT(_ls_p, list, next); \ + UTLIST_RS(list); \ + _ls_psize--; \ + if (_ls_p == _ls_oldhead) { \ + _ls_p = NULL; \ + } \ + } else if (cmp(_ls_p, _ls_q) <= 0) { \ + _ls_e = _ls_p; \ + UTLIST_SV(_ls_p, list); \ + _ls_p = UTLIST_NEXT(_ls_p, list, next); \ + UTLIST_RS(list); \ + _ls_psize--; \ + if (_ls_p == _ls_oldhead) { \ + _ls_p = NULL; \ + } \ + } else { \ + _ls_e = _ls_q; \ + UTLIST_SV(_ls_q, list); \ + _ls_q = UTLIST_NEXT(_ls_q, list, next); \ + UTLIST_RS(list); \ + _ls_qsize--; \ + if (_ls_q == _ls_oldhead) { \ + _ls_q = NULL; \ + } \ + } \ + if (_ls_tail) { \ + UTLIST_SV(_ls_tail, list); \ + UTLIST_NEXTASGN(_ls_tail, list, _ls_e, next); \ + UTLIST_RS(list); \ + } else { \ + UTLIST_CASTASGN(list, _ls_e); \ + } \ + UTLIST_SV(_ls_e, list); \ + UTLIST_PREVASGN(_ls_e, list, _ls_tail, prev); \ + UTLIST_RS(list); \ + _ls_tail = _ls_e; \ + } \ + _ls_p = _ls_q; \ + } \ + UTLIST_CASTASGN((list)->prev, _ls_tail); \ + UTLIST_CASTASGN(_tmp, list); \ + UTLIST_SV(_ls_tail, list); \ + UTLIST_NEXTASGN(_ls_tail, list, _tmp, next); \ + UTLIST_RS(list); \ + if (_ls_nmerges <= 1) { \ + _ls_looping = 0; \ + } \ + _ls_insize *= 2; \ + } \ + } \ + } while (0) + +/****************************************************************************** + * singly linked list macros (non-circular) * + *****************************************************************************/ +#define LL_PREPEND(head, add) LL_PREPEND2(head, add, next) + +#define LL_PREPEND2(head, add, next) \ + do { \ + (add)->next = (head); \ + (head) = (add); \ + } while (0) + +#define LL_CONCAT(head1, head2) LL_CONCAT2(head1, head2, next) + +#define LL_CONCAT2(head1, head2, next) \ + do { \ + LDECLTYPE(head1) _tmp; \ + if (head1) { \ + _tmp = (head1); \ + while (_tmp->next) { \ + _tmp = _tmp->next; \ + } \ + _tmp->next = (head2); \ + } else { \ + (head1) = (head2); \ + } \ + } while (0) + +#define LL_APPEND(head, add) LL_APPEND2(head, add, next) + +#define LL_APPEND2(head, add, next) \ + do { \ + LDECLTYPE(head) _tmp; \ + (add)->next = NULL; \ + if (head) { \ + _tmp = (head); \ + while (_tmp->next) { \ + _tmp = _tmp->next; \ + } \ + _tmp->next = (add); \ + } else { \ + (head) = (add); \ + } \ + } while (0) + +#define LL_INSERT_INORDER(head, add, cmp) LL_INSERT_INORDER2(head, add, cmp, next) + +#define LL_INSERT_INORDER2(head, add, cmp, next) \ + do { \ + LDECLTYPE(head) _tmp; \ + if (head) { \ + LL_LOWER_BOUND2(head, _tmp, add, cmp, next); \ + LL_APPEND_ELEM2(head, _tmp, add, next); \ + } else { \ + (head) = (add); \ + (head)->next = NULL; \ + } \ + } while (0) + +#define LL_LOWER_BOUND(head, elt, like, cmp) LL_LOWER_BOUND2(head, elt, like, cmp, next) + +#define LL_LOWER_BOUND2(head, elt, like, cmp, next) \ + do { \ + if ((head) == NULL || (cmp(head, like)) >= 0) { \ + (elt) = NULL; \ + } else { \ + for ((elt) = (head); (elt)->next != NULL; (elt) = (elt)->next) { \ + if (cmp((elt)->next, like) >= 0) { \ + break; \ + } \ + } \ + } \ + } while (0) + +#define LL_DELETE(head, del) LL_DELETE2(head, del, next) + +#define LL_DELETE2(head, del, next) \ + do { \ + LDECLTYPE(head) _tmp; \ + if ((head) == (del)) { \ + (head) = (head)->next; \ + } else { \ + _tmp = (head); \ + while (_tmp->next && (_tmp->next != (del))) { \ + _tmp = _tmp->next; \ + } \ + if (_tmp->next) { \ + _tmp->next = (del)->next; \ + } \ + } \ + } while (0) + +#define LL_COUNT(head, el, counter) LL_COUNT2(head, el, counter, next) + +#define LL_COUNT2(head, el, counter, next) \ + do { \ + (counter) = 0; \ + LL_FOREACH2(head, el, next) { \ + ++(counter); \ + } \ + } while (0) + +#define LL_FOREACH(head, el) LL_FOREACH2(head, el, next) + +#define LL_FOREACH2(head, el, next) for ((el) = (head); el; (el) = (el)->next) + +#define LL_FOREACH_SAFE(head, el, tmp) LL_FOREACH_SAFE2(head, el, tmp, next) + +#define LL_FOREACH_SAFE2(head, el, tmp, next) for ((el) = (head); (el) && ((tmp) = (el)->next, 1); (el) = (tmp)) + +#define LL_SEARCH_SCALAR(head, out, field, val) LL_SEARCH_SCALAR2(head, out, field, val, next) + +#define LL_SEARCH_SCALAR2(head, out, field, val, next) \ + do { \ + LL_FOREACH2(head, out, next) { \ + if ((out)->field == (val)) \ + break; \ + } \ + } while (0) + +#define LL_SEARCH(head, out, elt, cmp) LL_SEARCH2(head, out, elt, cmp, next) + +#define LL_SEARCH2(head, out, elt, cmp, next) \ + do { \ + LL_FOREACH2(head, out, next) { \ + if ((cmp(out, elt)) == 0) \ + break; \ + } \ + } while (0) + +#define LL_REPLACE_ELEM2(head, el, add, next) \ + do { \ + LDECLTYPE(head) _tmp; \ + assert((head) != NULL); \ + assert((el) != NULL); \ + assert((add) != NULL); \ + (add)->next = (el)->next; \ + if ((head) == (el)) { \ + (head) = (add); \ + } else { \ + _tmp = (head); \ + while (_tmp->next && (_tmp->next != (el))) { \ + _tmp = _tmp->next; \ + } \ + if (_tmp->next) { \ + _tmp->next = (add); \ + } \ + } \ + } while (0) + +#define LL_REPLACE_ELEM(head, el, add) LL_REPLACE_ELEM2(head, el, add, next) + +#define LL_PREPEND_ELEM2(head, el, add, next) \ + do { \ + if (el) { \ + LDECLTYPE(head) _tmp; \ + assert((head) != NULL); \ + assert((add) != NULL); \ + (add)->next = (el); \ + if ((head) == (el)) { \ + (head) = (add); \ + } else { \ + _tmp = (head); \ + while (_tmp->next && (_tmp->next != (el))) { \ + _tmp = _tmp->next; \ + } \ + if (_tmp->next) { \ + _tmp->next = (add); \ + } \ + } \ + } else { \ + LL_APPEND2(head, add, next); \ + } \ + } while (0) + +#define LL_PREPEND_ELEM(head, el, add) LL_PREPEND_ELEM2(head, el, add, next) + +#define LL_APPEND_ELEM2(head, el, add, next) \ + do { \ + if (el) { \ + assert((head) != NULL); \ + assert((add) != NULL); \ + (add)->next = (el)->next; \ + (el)->next = (add); \ + } else { \ + LL_PREPEND2(head, add, next); \ + } \ + } while (0) + +#define LL_APPEND_ELEM(head, el, add) LL_APPEND_ELEM2(head, el, add, next) + +#ifdef NO_DECLTYPE +/* Here are VS2008 / NO_DECLTYPE replacements for a few functions */ + +#undef LL_CONCAT2 +#define LL_CONCAT2(head1, head2, next) \ + do { \ + char *_tmp; \ + if (head1) { \ + _tmp = (char *)(head1); \ + while ((head1)->next) { \ + (head1) = (head1)->next; \ + } \ + (head1)->next = (head2); \ + UTLIST_RS(head1); \ + } else { \ + (head1) = (head2); \ + } \ + } while (0) + +#undef LL_APPEND2 +#define LL_APPEND2(head, add, next) \ + do { \ + if (head) { \ + (add)->next = head; /* use add->next as a temp variable */ \ + while ((add)->next->next) { \ + (add)->next = (add)->next->next; \ + } \ + (add)->next->next = (add); \ + } else { \ + (head) = (add); \ + } \ + (add)->next = NULL; \ + } while (0) + +#undef LL_INSERT_INORDER2 +#define LL_INSERT_INORDER2(head, add, cmp, next) \ + do { \ + if ((head) == NULL || (cmp(head, add)) >= 0) { \ + (add)->next = (head); \ + (head) = (add); \ + } else { \ + char *_tmp = (char *)(head); \ + while ((head)->next != NULL && (cmp((head)->next, add)) < 0) { \ + (head) = (head)->next; \ + } \ + (add)->next = (head)->next; \ + (head)->next = (add); \ + UTLIST_RS(head); \ + } \ + } while (0) + +#undef LL_DELETE2 +#define LL_DELETE2(head, del, next) \ + do { \ + if ((head) == (del)) { \ + (head) = (head)->next; \ + } else { \ + char *_tmp = (char *)(head); \ + while ((head)->next && ((head)->next != (del))) { \ + (head) = (head)->next; \ + } \ + if ((head)->next) { \ + (head)->next = ((del)->next); \ + } \ + UTLIST_RS(head); \ + } \ + } while (0) + +#undef LL_REPLACE_ELEM2 +#define LL_REPLACE_ELEM2(head, el, add, next) \ + do { \ + assert((head) != NULL); \ + assert((el) != NULL); \ + assert((add) != NULL); \ + if ((head) == (el)) { \ + (head) = (add); \ + } else { \ + (add)->next = head; \ + while ((add)->next->next && ((add)->next->next != (el))) { \ + (add)->next = (add)->next->next; \ + } \ + if ((add)->next->next) { \ + (add)->next->next = (add); \ + } \ + } \ + (add)->next = (el)->next; \ + } while (0) + +#undef LL_PREPEND_ELEM2 +#define LL_PREPEND_ELEM2(head, el, add, next) \ + do { \ + if (el) { \ + assert((head) != NULL); \ + assert((add) != NULL); \ + if ((head) == (el)) { \ + (head) = (add); \ + } else { \ + (add)->next = (head); \ + while ((add)->next->next && ((add)->next->next != (el))) { \ + (add)->next = (add)->next->next; \ + } \ + if ((add)->next->next) { \ + (add)->next->next = (add); \ + } \ + } \ + (add)->next = (el); \ + } else { \ + LL_APPEND2(head, add, next); \ + } \ + } while (0) + +#endif /* NO_DECLTYPE */ + +/****************************************************************************** + * doubly linked list macros (non-circular) * + *****************************************************************************/ +#define DL_PREPEND(head, add) DL_PREPEND2(head, add, prev, next) + +#define DL_PREPEND2(head, add, prev, next) \ + do { \ + (add)->next = (head); \ + if (head) { \ + (add)->prev = (head)->prev; \ + (head)->prev = (add); \ + } else { \ + (add)->prev = (add); \ + } \ + (head) = (add); \ + } while (0) + +#define DL_APPEND(head, add) DL_APPEND2(head, add, prev, next) + +#define DL_APPEND2(head, add, prev, next) \ + do { \ + if (head) { \ + (add)->prev = (head)->prev; \ + (head)->prev->next = (add); \ + (head)->prev = (add); \ + (add)->next = NULL; \ + } else { \ + (head) = (add); \ + (head)->prev = (head); \ + (head)->next = NULL; \ + } \ + } while (0) + +#define DL_INSERT_INORDER(head, add, cmp) DL_INSERT_INORDER2(head, add, cmp, prev, next) + +#define DL_INSERT_INORDER2(head, add, cmp, prev, next) \ + do { \ + LDECLTYPE(head) _tmp; \ + if (head) { \ + DL_LOWER_BOUND2(head, _tmp, add, cmp, next); \ + DL_APPEND_ELEM2(head, _tmp, add, prev, next); \ + } else { \ + (head) = (add); \ + (head)->prev = (head); \ + (head)->next = NULL; \ + } \ + } while (0) + +#define DL_LOWER_BOUND(head, elt, like, cmp) DL_LOWER_BOUND2(head, elt, like, cmp, next) + +#define DL_LOWER_BOUND2(head, elt, like, cmp, next) \ + do { \ + if ((head) == NULL || (cmp(head, like)) >= 0) { \ + (elt) = NULL; \ + } else { \ + for ((elt) = (head); (elt)->next != NULL; (elt) = (elt)->next) { \ + if ((cmp((elt)->next, like)) >= 0) { \ + break; \ + } \ + } \ + } \ + } while (0) + +#define DL_CONCAT(head1, head2) DL_CONCAT2(head1, head2, prev, next) + +#define DL_CONCAT2(head1, head2, prev, next) \ + do { \ + LDECLTYPE(head1) _tmp; \ + if (head2) { \ + if (head1) { \ + UTLIST_CASTASGN(_tmp, (head2)->prev); \ + (head2)->prev = (head1)->prev; \ + (head1)->prev->next = (head2); \ + UTLIST_CASTASGN((head1)->prev, _tmp); \ + } else { \ + (head1) = (head2); \ + } \ + } \ + } while (0) + +#define DL_DELETE(head, del) DL_DELETE2(head, del, prev, next) + +#define DL_DELETE2(head, del, prev, next) \ + do { \ + assert((head) != NULL); \ + assert((del)->prev != NULL); \ + if ((del)->prev == (del)) { \ + (head) = NULL; \ + } else if ((del) == (head)) { \ + (del)->next->prev = (del)->prev; \ + (head) = (del)->next; \ + } else { \ + (del)->prev->next = (del)->next; \ + if ((del)->next) { \ + (del)->next->prev = (del)->prev; \ + } else { \ + (head)->prev = (del)->prev; \ + } \ + } \ + } while (0) + +#define DL_COUNT(head, el, counter) DL_COUNT2(head, el, counter, next) + +#define DL_COUNT2(head, el, counter, next) \ + do { \ + (counter) = 0; \ + DL_FOREACH2(head, el, next) { \ + ++(counter); \ + } \ + } while (0) + +#define DL_FOREACH(head, el) DL_FOREACH2(head, el, next) + +#define DL_FOREACH2(head, el, next) for ((el) = (head); el; (el) = (el)->next) + +/* this version is safe for deleting the elements during iteration */ +#define DL_FOREACH_SAFE(head, el, tmp) DL_FOREACH_SAFE2(head, el, tmp, next) + +#define DL_FOREACH_SAFE2(head, el, tmp, next) for ((el) = (head); (el) && ((tmp) = (el)->next, 1); (el) = (tmp)) + +/* these are identical to their singly-linked list counterparts */ +#define DL_SEARCH_SCALAR LL_SEARCH_SCALAR +#define DL_SEARCH LL_SEARCH +#define DL_SEARCH_SCALAR2 LL_SEARCH_SCALAR2 +#define DL_SEARCH2 LL_SEARCH2 + +#define DL_REPLACE_ELEM2(head, el, add, prev, next) \ + do { \ + assert((head) != NULL); \ + assert((el) != NULL); \ + assert((add) != NULL); \ + if ((head) == (el)) { \ + (head) = (add); \ + (add)->next = (el)->next; \ + if ((el)->next == NULL) { \ + (add)->prev = (add); \ + } else { \ + (add)->prev = (el)->prev; \ + (add)->next->prev = (add); \ + } \ + } else { \ + (add)->next = (el)->next; \ + (add)->prev = (el)->prev; \ + (add)->prev->next = (add); \ + if ((el)->next == NULL) { \ + (head)->prev = (add); \ + } else { \ + (add)->next->prev = (add); \ + } \ + } \ + } while (0) + +#define DL_REPLACE_ELEM(head, el, add) DL_REPLACE_ELEM2(head, el, add, prev, next) + +#define DL_PREPEND_ELEM2(head, el, add, prev, next) \ + do { \ + if (el) { \ + assert((head) != NULL); \ + assert((add) != NULL); \ + (add)->next = (el); \ + (add)->prev = (el)->prev; \ + (el)->prev = (add); \ + if ((head) == (el)) { \ + (head) = (add); \ + } else { \ + (add)->prev->next = (add); \ + } \ + } else { \ + DL_APPEND2(head, add, prev, next); \ + } \ + } while (0) + +#define DL_PREPEND_ELEM(head, el, add) DL_PREPEND_ELEM2(head, el, add, prev, next) + +#define DL_APPEND_ELEM2(head, el, add, prev, next) \ + do { \ + if (el) { \ + assert((head) != NULL); \ + assert((add) != NULL); \ + (add)->next = (el)->next; \ + (add)->prev = (el); \ + (el)->next = (add); \ + if ((add)->next) { \ + (add)->next->prev = (add); \ + } else { \ + (head)->prev = (add); \ + } \ + } else { \ + DL_PREPEND2(head, add, prev, next); \ + } \ + } while (0) + +#define DL_APPEND_ELEM(head, el, add) DL_APPEND_ELEM2(head, el, add, prev, next) + +#ifdef NO_DECLTYPE +/* Here are VS2008 / NO_DECLTYPE replacements for a few functions */ + +#undef DL_INSERT_INORDER2 +#define DL_INSERT_INORDER2(head, add, cmp, prev, next) \ + do { \ + if ((head) == NULL) { \ + (add)->prev = (add); \ + (add)->next = NULL; \ + (head) = (add); \ + } else if ((cmp(head, add)) >= 0) { \ + (add)->prev = (head)->prev; \ + (add)->next = (head); \ + (head)->prev = (add); \ + (head) = (add); \ + } else { \ + char *_tmp = (char *)(head); \ + while ((head)->next && (cmp((head)->next, add)) < 0) { \ + (head) = (head)->next; \ + } \ + (add)->prev = (head); \ + (add)->next = (head)->next; \ + (head)->next = (add); \ + UTLIST_RS(head); \ + if ((add)->next) { \ + (add)->next->prev = (add); \ + } else { \ + (head)->prev = (add); \ + } \ + } \ + } while (0) +#endif /* NO_DECLTYPE */ + +/****************************************************************************** + * circular doubly linked list macros * + *****************************************************************************/ +#define CDL_APPEND(head, add) CDL_APPEND2(head, add, prev, next) + +#define CDL_APPEND2(head, add, prev, next) \ + do { \ + if (head) { \ + (add)->prev = (head)->prev; \ + (add)->next = (head); \ + (head)->prev = (add); \ + (add)->prev->next = (add); \ + } else { \ + (add)->prev = (add); \ + (add)->next = (add); \ + (head) = (add); \ + } \ + } while (0) + +#define CDL_PREPEND(head, add) CDL_PREPEND2(head, add, prev, next) + +#define CDL_PREPEND2(head, add, prev, next) \ + do { \ + if (head) { \ + (add)->prev = (head)->prev; \ + (add)->next = (head); \ + (head)->prev = (add); \ + (add)->prev->next = (add); \ + } else { \ + (add)->prev = (add); \ + (add)->next = (add); \ + } \ + (head) = (add); \ + } while (0) + +#define CDL_INSERT_INORDER(head, add, cmp) CDL_INSERT_INORDER2(head, add, cmp, prev, next) + +#define CDL_INSERT_INORDER2(head, add, cmp, prev, next) \ + do { \ + LDECLTYPE(head) _tmp; \ + if (head) { \ + CDL_LOWER_BOUND2(head, _tmp, add, cmp, next); \ + CDL_APPEND_ELEM2(head, _tmp, add, prev, next); \ + } else { \ + (head) = (add); \ + (head)->next = (head); \ + (head)->prev = (head); \ + } \ + } while (0) + +#define CDL_LOWER_BOUND(head, elt, like, cmp) CDL_LOWER_BOUND2(head, elt, like, cmp, next) + +#define CDL_LOWER_BOUND2(head, elt, like, cmp, next) \ + do { \ + if ((head) == NULL || (cmp(head, like)) >= 0) { \ + (elt) = NULL; \ + } else { \ + for ((elt) = (head); (elt)->next != (head); (elt) = (elt)->next) { \ + if ((cmp((elt)->next, like)) >= 0) { \ + break; \ + } \ + } \ + } \ + } while (0) + +#define CDL_DELETE(head, del) CDL_DELETE2(head, del, prev, next) + +#define CDL_DELETE2(head, del, prev, next) \ + do { \ + if (((head) == (del)) && ((head)->next == (head))) { \ + (head) = NULL; \ + } else { \ + (del)->next->prev = (del)->prev; \ + (del)->prev->next = (del)->next; \ + if ((del) == (head)) \ + (head) = (del)->next; \ + } \ + } while (0) + +#define CDL_COUNT(head, el, counter) CDL_COUNT2(head, el, counter, next) + +#define CDL_COUNT2(head, el, counter, next) \ + do { \ + (counter) = 0; \ + CDL_FOREACH2(head, el, next) { \ + ++(counter); \ + } \ + } while (0) + +#define CDL_FOREACH(head, el) CDL_FOREACH2(head, el, next) + +#define CDL_FOREACH2(head, el, next) for ((el) = (head); el; (el) = (((el)->next == (head)) ? NULL : (el)->next)) + +#define CDL_FOREACH_SAFE(head, el, tmp1, tmp2) CDL_FOREACH_SAFE2(head, el, tmp1, tmp2, prev, next) + +#define CDL_FOREACH_SAFE2(head, el, tmp1, tmp2, prev, next) \ + for ((el) = (head), (tmp1) = (head) ? (head)->prev : NULL; (el) && ((tmp2) = (el)->next, 1); \ + (el) = ((el) == (tmp1) ? NULL : (tmp2))) + +#define CDL_SEARCH_SCALAR(head, out, field, val) CDL_SEARCH_SCALAR2(head, out, field, val, next) + +#define CDL_SEARCH_SCALAR2(head, out, field, val, next) \ + do { \ + CDL_FOREACH2(head, out, next) { \ + if ((out)->field == (val)) \ + break; \ + } \ + } while (0) + +#define CDL_SEARCH(head, out, elt, cmp) CDL_SEARCH2(head, out, elt, cmp, next) + +#define CDL_SEARCH2(head, out, elt, cmp, next) \ + do { \ + CDL_FOREACH2(head, out, next) { \ + if ((cmp(out, elt)) == 0) \ + break; \ + } \ + } while (0) + +#define CDL_REPLACE_ELEM2(head, el, add, prev, next) \ + do { \ + assert((head) != NULL); \ + assert((el) != NULL); \ + assert((add) != NULL); \ + if ((el)->next == (el)) { \ + (add)->next = (add); \ + (add)->prev = (add); \ + (head) = (add); \ + } else { \ + (add)->next = (el)->next; \ + (add)->prev = (el)->prev; \ + (add)->next->prev = (add); \ + (add)->prev->next = (add); \ + if ((head) == (el)) { \ + (head) = (add); \ + } \ + } \ + } while (0) + +#define CDL_REPLACE_ELEM(head, el, add) CDL_REPLACE_ELEM2(head, el, add, prev, next) + +#define CDL_PREPEND_ELEM2(head, el, add, prev, next) \ + do { \ + if (el) { \ + assert((head) != NULL); \ + assert((add) != NULL); \ + (add)->next = (el); \ + (add)->prev = (el)->prev; \ + (el)->prev = (add); \ + (add)->prev->next = (add); \ + if ((head) == (el)) { \ + (head) = (add); \ + } \ + } else { \ + CDL_APPEND2(head, add, prev, next); \ + } \ + } while (0) + +#define CDL_PREPEND_ELEM(head, el, add) CDL_PREPEND_ELEM2(head, el, add, prev, next) + +#define CDL_APPEND_ELEM2(head, el, add, prev, next) \ + do { \ + if (el) { \ + assert((head) != NULL); \ + assert((add) != NULL); \ + (add)->next = (el)->next; \ + (add)->prev = (el); \ + (el)->next = (add); \ + (add)->next->prev = (add); \ + } else { \ + CDL_PREPEND2(head, add, prev, next); \ + } \ + } while (0) + +#define CDL_APPEND_ELEM(head, el, add) CDL_APPEND_ELEM2(head, el, add, prev, next) + +#ifdef NO_DECLTYPE +/* Here are VS2008 / NO_DECLTYPE replacements for a few functions */ + +#undef CDL_INSERT_INORDER2 +#define CDL_INSERT_INORDER2(head, add, cmp, prev, next) \ + do { \ + if ((head) == NULL) { \ + (add)->prev = (add); \ + (add)->next = (add); \ + (head) = (add); \ + } else if ((cmp(head, add)) >= 0) { \ + (add)->prev = (head)->prev; \ + (add)->next = (head); \ + (add)->prev->next = (add); \ + (head)->prev = (add); \ + (head) = (add); \ + } else { \ + char *_tmp = (char *)(head); \ + while ((char *)(head)->next != _tmp && (cmp((head)->next, add)) < 0) { \ + (head) = (head)->next; \ + } \ + (add)->prev = (head); \ + (add)->next = (head)->next; \ + (add)->next->prev = (add); \ + (head)->next = (add); \ + UTLIST_RS(head); \ + } \ + } while (0) +#endif /* NO_DECLTYPE */ + +#endif /* UTLIST_H */ diff --git a/NetTunnelSDK/uthash/utringbuffer.h b/NetTunnelSDK/uthash/utringbuffer.h new file mode 100644 index 0000000..6bb6c4b --- /dev/null +++ b/NetTunnelSDK/uthash/utringbuffer.h @@ -0,0 +1,128 @@ +/* +Copyright (c) 2015-2021, Troy D. Hanson http://troydhanson.github.com/uthash/ +All rights reserved. + +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. + +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. +*/ + +/* a ring-buffer implementation using macros + */ +#ifndef UTRINGBUFFER_H +#define UTRINGBUFFER_H + +#define UTRINGBUFFER_VERSION 2.3.0 + +#include +#include +#include "utarray.h" // for "UT_icd" + +typedef struct { + unsigned i; /* index of next available slot; wraps at n */ + unsigned n; /* capacity */ + unsigned char f; /* full */ + UT_icd icd; /* initializer, copy and destructor functions */ + char *d; /* n slots of size icd->sz */ +} UT_ringbuffer; + +#define utringbuffer_init(a, _n, _icd) \ + do { \ + memset(a, 0, sizeof(UT_ringbuffer)); \ + (a)->icd = *(_icd); \ + (a)->n = (_n); \ + if ((a)->n) { \ + (a)->d = (char *)malloc((a)->n * (_icd)->sz); \ + } \ + } while (0) + +#define utringbuffer_clear(a) \ + do { \ + if ((a)->icd.dtor) { \ + if ((a)->f) { \ + unsigned _ut_i; \ + for (_ut_i = 0; _ut_i < (a)->n; ++_ut_i) { \ + (a)->icd.dtor(utringbuffer_eltptr(a, _ut_i)); \ + } \ + } else { \ + unsigned _ut_i; \ + for (_ut_i = 0; _ut_i < (a)->i; ++_ut_i) { \ + (a)->icd.dtor(utringbuffer_eltptr(a, _ut_i)); \ + } \ + } \ + } \ + (a)->i = 0; \ + (a)->f = 0; \ + } while (0) + +#define utringbuffer_done(a) \ + do { \ + utringbuffer_clear(a); \ + free((a)->d); \ + (a)->d = NULL; \ + (a)->n = 0; \ + } while (0) + +#define utringbuffer_new(a, n, _icd) \ + do { \ + a = (UT_ringbuffer *)malloc(sizeof(UT_ringbuffer)); \ + utringbuffer_init(a, n, _icd); \ + } while (0) + +#define utringbuffer_free(a) \ + do { \ + utringbuffer_done(a); \ + free(a); \ + } while (0) + +#define utringbuffer_push_back(a, p) \ + do { \ + if ((a)->icd.dtor && (a)->f) { \ + (a)->icd.dtor(_utringbuffer_internalptr(a, (a)->i)); \ + } \ + if ((a)->icd.copy) { \ + (a)->icd.copy(_utringbuffer_internalptr(a, (a)->i), p); \ + } else { \ + memcpy(_utringbuffer_internalptr(a, (a)->i), p, (a)->icd.sz); \ + }; \ + if (++(a)->i == (a)->n) { \ + (a)->i = 0; \ + (a)->f = 1; \ + } \ + } while (0) + +#define utringbuffer_len(a) ((a)->f ? (a)->n : (a)->i) +#define utringbuffer_empty(a) ((a)->i == 0 && !(a)->f) +#define utringbuffer_full(a) ((a)->f != 0) + +#define _utringbuffer_real_idx(a, j) ((a)->f ? ((j) + (a)->i) % (a)->n : (j)) +#define _utringbuffer_internalptr(a, j) ((void *)((a)->d + ((a)->icd.sz * (j)))) +#define utringbuffer_eltptr(a, j) \ + ((0 <= (j) && (j) < utringbuffer_len(a)) ? _utringbuffer_internalptr(a, _utringbuffer_real_idx(a, j)) : NULL) + +#define _utringbuffer_fake_idx(a, j) ((a)->f ? ((j) + (a)->n - (a)->i) % (a)->n : (j)) +#define _utringbuffer_internalidx(a, e) (((char *)(e) >= (a)->d) ? (((char *)(e) - (a)->d) / (a)->icd.sz) : -1) +#define utringbuffer_eltidx(a, e) _utringbuffer_fake_idx(a, _utringbuffer_internalidx(a, e)) + +#define utringbuffer_front(a) utringbuffer_eltptr(a, 0) +#define utringbuffer_next(a, e) \ + ((e) == NULL ? utringbuffer_front(a) : utringbuffer_eltptr(a, utringbuffer_eltidx(a, e) + 1)) +#define utringbuffer_prev(a, e) \ + ((e) == NULL ? utringbuffer_back(a) : utringbuffer_eltptr(a, utringbuffer_eltidx(a, e) - 1)) +#define utringbuffer_back(a) (utringbuffer_empty(a) ? NULL : utringbuffer_eltptr(a, utringbuffer_len(a) - 1)) + +#endif /* UTRINGBUFFER_H */ diff --git a/NetTunnelSDK/uthash/utstack.h b/NetTunnelSDK/uthash/utstack.h new file mode 100644 index 0000000..b911917 --- /dev/null +++ b/NetTunnelSDK/uthash/utstack.h @@ -0,0 +1,87 @@ +/* +Copyright (c) 2018-2021, Troy D. Hanson http://troydhanson.github.com/uthash/ +All rights reserved. + +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. + +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. +*/ + +#ifndef UTSTACK_H +#define UTSTACK_H + +#define UTSTACK_VERSION 2.3.0 + +/* + * This file contains macros to manipulate a singly-linked list as a stack. + * + * To use utstack, your structure must have a "next" pointer. + * + * ----------------.EXAMPLE ------------------------- + * struct item { + * int id; + * struct item *next; + * } + * + * struct item *stack = NULL: + * + * int main() { + * int count; + * struct item *tmp; + * struct item *item = malloc(sizeof *item); + * item->id = 42; + * STACK_COUNT(stack, tmp, count); assert(count == 0); + * STACK_PUSH(stack, item); + * STACK_COUNT(stack, tmp, count); assert(count == 1); + * STACK_POP(stack, item); + * free(item); + * STACK_COUNT(stack, tmp, count); assert(count == 0); + * } + * -------------------------------------------------- + */ + +#define STACK_TOP(head) (head) + +#define STACK_EMPTY(head) (!(head)) + +#define STACK_PUSH(head, add) STACK_PUSH2(head, add, next) + +#define STACK_PUSH2(head, add, next) \ + do { \ + (add)->next = (head); \ + (head) = (add); \ + } while (0) + +#define STACK_POP(head, result) STACK_POP2(head, result, next) + +#define STACK_POP2(head, result, next) \ + do { \ + (result) = (head); \ + (head) = (head)->next; \ + } while (0) + +#define STACK_COUNT(head, el, counter) STACK_COUNT2(head, el, counter, next) + +#define STACK_COUNT2(head, el, counter, next) \ + do { \ + (counter) = 0; \ + for ((el) = (head); el; (el) = (el)->next) { \ + ++(counter); \ + } \ + } while (0) + +#endif /* UTSTACK_H */ diff --git a/NetTunnelSDK/uthash/utstring.h b/NetTunnelSDK/uthash/utstring.h new file mode 100644 index 0000000..f91f856 --- /dev/null +++ b/NetTunnelSDK/uthash/utstring.h @@ -0,0 +1,351 @@ +/* +Copyright (c) 2008-2021, Troy D. Hanson http://troydhanson.github.com/uthash/ +All rights reserved. + +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. + +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. +*/ + +/* a dynamic string implementation using macros + */ +#ifndef UTSTRING_H +#define UTSTRING_H + +#define UTSTRING_VERSION 2.3.0 + +#include +#include +#include +#include + +#ifdef __GNUC__ +#define UTSTRING_UNUSED __attribute__((__unused__)) +#else +#define UTSTRING_UNUSED +#endif + +#ifdef oom +#error "The name of macro 'oom' has been changed to 'utstring_oom'. Please update your code." +#define utstring_oom() oom() +#endif + +#ifndef utstring_oom +#define utstring_oom() exit(-1) +#endif + +typedef struct { + char *d; /* pointer to allocated buffer */ + size_t n; /* allocated capacity */ + size_t i; /* index of first unused byte */ +} UT_string; + +#define utstring_reserve(s, amt) \ + do { \ + if (((s)->n - (s)->i) < (size_t)(amt)) { \ + char *utstring_tmp = (char *)realloc((s)->d, (s)->n + (amt)); \ + if (!utstring_tmp) { \ + utstring_oom(); \ + } \ + (s)->d = utstring_tmp; \ + (s)->n += (amt); \ + } \ + } while (0) + +#define utstring_init(s) \ + do { \ + (s)->n = 0; \ + (s)->i = 0; \ + (s)->d = NULL; \ + utstring_reserve(s, 100); \ + (s)->d[0] = '\0'; \ + } while (0) + +#define utstring_done(s) \ + do { \ + if ((s)->d != NULL) \ + free((s)->d); \ + (s)->n = 0; \ + } while (0) + +#define utstring_free(s) \ + do { \ + utstring_done(s); \ + free(s); \ + } while (0) + +#define utstring_new(s) \ + do { \ + (s) = (UT_string *)malloc(sizeof(UT_string)); \ + if (!(s)) { \ + utstring_oom(); \ + } \ + utstring_init(s); \ + } while (0) + +#define utstring_renew(s) \ + do { \ + if (s) { \ + utstring_clear(s); \ + } else { \ + utstring_new(s); \ + } \ + } while (0) + +#define utstring_clear(s) \ + do { \ + (s)->i = 0; \ + (s)->d[0] = '\0'; \ + } while (0) + +#define utstring_bincpy(s, b, l) \ + do { \ + utstring_reserve((s), (l) + 1); \ + if (l) \ + memcpy(&(s)->d[(s)->i], b, l); \ + (s)->i += (l); \ + (s)->d[(s)->i] = '\0'; \ + } while (0) + +#define utstring_concat(dst, src) \ + do { \ + utstring_reserve((dst), ((src)->i) + 1); \ + if ((src)->i) \ + memcpy(&(dst)->d[(dst)->i], (src)->d, (src)->i); \ + (dst)->i += (src)->i; \ + (dst)->d[(dst)->i] = '\0'; \ + } while (0) + +#define utstring_len(s) ((s)->i) + +#define utstring_body(s) ((s)->d) + +UTSTRING_UNUSED static void utstring_printf_va(UT_string *s, const char *fmt, va_list ap) { + int n; + va_list cp; + for (;;) { +#ifdef _WIN32 + cp = ap; +#else + va_copy(cp, ap); +#endif + n = vsnprintf(&s->d[s->i], s->n - s->i, fmt, cp); + va_end(cp); + + if ((n > -1) && ((size_t)n < (s->n - s->i))) { + s->i += n; + return; + } + + /* Else try again with more space. */ + if (n > -1) { + utstring_reserve(s, n + 1); /* exact */ + } else { + utstring_reserve(s, (s->n) * 2); /* 2x */ + } + } +} +#ifdef __GNUC__ +/* support printf format checking (2=the format string, 3=start of varargs) */ +static void utstring_printf(UT_string *s, const char *fmt, ...) __attribute__((format(printf, 2, 3))); +#endif +UTSTRING_UNUSED static void utstring_printf(UT_string *s, const char *fmt, ...) { + va_list ap; + va_start(ap, fmt); + utstring_printf_va(s, fmt, ap); + va_end(ap); +} + +/******************************************************************************* + * begin substring search functions * + ******************************************************************************/ +/* Build KMP table from left to right. */ +UTSTRING_UNUSED static void _utstring_BuildTable(const char *P_Needle, size_t P_NeedleLen, long *P_KMP_Table) { + long i, j; + + i = 0; + j = i - 1; + P_KMP_Table[i] = j; + while (i < (long)P_NeedleLen) { + while ((j > -1) && (P_Needle[i] != P_Needle[j])) { + j = P_KMP_Table[j]; + } + i++; + j++; + if (i < (long)P_NeedleLen) { + if (P_Needle[i] == P_Needle[j]) { + P_KMP_Table[i] = P_KMP_Table[j]; + } else { + P_KMP_Table[i] = j; + } + } else { + P_KMP_Table[i] = j; + } + } + + return; +} + +/* Build KMP table from right to left. */ +UTSTRING_UNUSED static void _utstring_BuildTableR(const char *P_Needle, size_t P_NeedleLen, long *P_KMP_Table) { + long i, j; + + i = P_NeedleLen - 1; + j = i + 1; + P_KMP_Table[i + 1] = j; + while (i >= 0) { + while ((j < (long)P_NeedleLen) && (P_Needle[i] != P_Needle[j])) { + j = P_KMP_Table[j + 1]; + } + i--; + j--; + if (i >= 0) { + if (P_Needle[i] == P_Needle[j]) { + P_KMP_Table[i + 1] = P_KMP_Table[j + 1]; + } else { + P_KMP_Table[i + 1] = j; + } + } else { + P_KMP_Table[i + 1] = j; + } + } + + return; +} + +/* Search data from left to right. ( Multiple search mode. ) */ +UTSTRING_UNUSED static long _utstring_find(const char *P_Haystack, + size_t P_HaystackLen, + const char *P_Needle, + size_t P_NeedleLen, + long *P_KMP_Table) { + long i, j; + long V_FindPosition = -1; + + /* Search from left to right. */ + i = j = 0; + while ((j < (int)P_HaystackLen) && (((P_HaystackLen - j) + i) >= P_NeedleLen)) { + while ((i > -1) && (P_Needle[i] != P_Haystack[j])) { + i = P_KMP_Table[i]; + } + i++; + j++; + if (i >= (int)P_NeedleLen) { + /* Found. */ + V_FindPosition = j - i; + break; + } + } + + return V_FindPosition; +} + +/* Search data from right to left. ( Multiple search mode. ) */ +UTSTRING_UNUSED static long _utstring_findR(const char *P_Haystack, + size_t P_HaystackLen, + const char *P_Needle, + size_t P_NeedleLen, + long *P_KMP_Table) { + long i, j; + long V_FindPosition = -1; + + /* Search from right to left. */ + j = (P_HaystackLen - 1); + i = (P_NeedleLen - 1); + while ((j >= 0) && (j >= i)) { + while ((i < (int)P_NeedleLen) && (P_Needle[i] != P_Haystack[j])) { + i = P_KMP_Table[i + 1]; + } + i--; + j--; + if (i < 0) { + /* Found. */ + V_FindPosition = j + 1; + break; + } + } + + return V_FindPosition; +} + +/* Search data from left to right. ( One time search mode. ) */ +UTSTRING_UNUSED static long utstring_find(UT_string *s, + long P_StartPosition, /* Start from 0. -1 means last position. */ + const char *P_Needle, + size_t P_NeedleLen) { + long V_StartPosition; + long V_HaystackLen; + long *V_KMP_Table; + long V_FindPosition = -1; + + if (P_StartPosition < 0) { + V_StartPosition = s->i + P_StartPosition; + } else { + V_StartPosition = P_StartPosition; + } + V_HaystackLen = s->i - V_StartPosition; + if ((V_HaystackLen >= (long)P_NeedleLen) && (P_NeedleLen > 0)) { + V_KMP_Table = (long *)malloc(sizeof(long) * (P_NeedleLen + 1)); + if (V_KMP_Table != NULL) { + _utstring_BuildTable(P_Needle, P_NeedleLen, V_KMP_Table); + + V_FindPosition = _utstring_find(s->d + V_StartPosition, V_HaystackLen, P_Needle, P_NeedleLen, V_KMP_Table); + if (V_FindPosition >= 0) { + V_FindPosition += V_StartPosition; + } + + free(V_KMP_Table); + } + } + + return V_FindPosition; +} + +/* Search data from right to left. ( One time search mode. ) */ +UTSTRING_UNUSED static long utstring_findR(UT_string *s, + long P_StartPosition, /* Start from 0. -1 means last position. */ + const char *P_Needle, + size_t P_NeedleLen) { + long V_StartPosition; + long V_HaystackLen; + long *V_KMP_Table; + long V_FindPosition = -1; + + if (P_StartPosition < 0) { + V_StartPosition = s->i + P_StartPosition; + } else { + V_StartPosition = P_StartPosition; + } + V_HaystackLen = V_StartPosition + 1; + if ((V_HaystackLen >= (long)P_NeedleLen) && (P_NeedleLen > 0)) { + V_KMP_Table = (long *)malloc(sizeof(long) * (P_NeedleLen + 1)); + if (V_KMP_Table != NULL) { + _utstring_BuildTableR(P_Needle, P_NeedleLen, V_KMP_Table); + + V_FindPosition = _utstring_findR(s->d, V_HaystackLen, P_Needle, P_NeedleLen, V_KMP_Table); + + free(V_KMP_Table); + } + } + + return V_FindPosition; +} +/******************************************************************************* + * end substring search functions * + ******************************************************************************/ + +#endif /* UTSTRING_H */ diff --git a/NetTunnelSDK/wireguard.cpp b/NetTunnelSDK/wireguard.cpp index 50c3dc7..0ff4abe 100644 --- a/NetTunnelSDK/wireguard.cpp +++ b/NetTunnelSDK/wireguard.cpp @@ -14,8 +14,18 @@ #define WG_NIC_DISCRIPT TEXT("WireGuard Tunnel") +static NET_SHARE_MODE g_CurShareMode = ICS_SHARE_MODE; + constexpr auto WINENVBUF_SIZE = (4096); +NET_SHARE_MODE GetCurrentNetShareMode() { + return g_CurShareMode; +} + +void SetCurrentNetShareMode(NET_SHARE_MODE shareMode) { + g_CurShareMode = shareMode; +} + int GetWireGuardWorkMode(bool *pIsWorkServer) { if (pIsWorkServer == nullptr) { SPDLOG_ERROR(TEXT("Input pIsWorkServer params error")); @@ -73,7 +83,10 @@ int WireGuardInstallDefaultServerService(bool bInstall) { SPDLOG_DEBUG(TEXT("Run command [{0}]"), cmdBuf); if (bInstall) { - ret = WaitNetAdapterConnected(svrName, 10 * 1000); + int retry = 10; + do { + ret = WaitNetAdapterConnected(svrName, 1000); + } while (ret != ERR_SUCCESS && retry--); } return ret; diff --git a/NetTunnelSDKTestApp/NetShare.cpp b/NetTunnelSDKTestApp/NetShare.cpp index 6a497db..e9364d6 100644 --- a/NetTunnelSDKTestApp/NetShare.cpp +++ b/NetTunnelSDKTestApp/NetShare.cpp @@ -1,10 +1,129 @@ - - - -#include +#include #include #include +static int WideCharToTChar2(const WCHAR *pWStr, TCHAR *pOutStr, int maxOutLen) { + if (sizeof(TCHAR) == sizeof(WCHAR)) { + if (wcslen(pWStr) * sizeof(WCHAR) >= maxOutLen) { + return -1; + } + memcpy(pOutStr, pWStr, wcslen(pWStr)); + } else { + int len = WideCharToMultiByte(CP_ACP, 0, pWStr, static_cast(wcslen(pWStr)), nullptr, 0, nullptr, nullptr); + + if (len >= maxOutLen) { + return -1; + } + + WideCharToMultiByte(CP_ACP, 0, pWStr, static_cast(wcslen(pWStr)), pOutStr, len, nullptr, nullptr); + pOutStr[len] = 0; + + return 0; + } +} + +HRESULT shareNet2(INetSharingManager *pNSM) { // this is done in 2 parts: + // 1: enum connections until we get one that we can convert into an INetSharingConfiguration + // 2: then, enum portmappings, and delete if we find a match. + + // PART 1: find a valid connection + INetConnection *pNC = nullptr; // fill this out for part 2 below + + INetSharingEveryConnectionCollection *pNSECC = nullptr; + HRESULT hr = pNSM->get_EnumEveryConnection(&pNSECC); + if (!pNSECC) { + printf("failed to get EveryConnectionCollection!\r\n"); + } else { + // enumerate connections + IEnumVARIANT *pEV = nullptr; + IUnknown *pUnk = nullptr; + hr = pNSECC->get__NewEnum(&pUnk); + if (pUnk) { + hr = pUnk->QueryInterface(__uuidof(IEnumVARIANT), (void **)&pEV); + pUnk->Release(); + } + if (pEV) { + VARIANT v; + VariantInit(&v); + BOOL bFoundIt = FALSE; + while (S_OK == pEV->Next(1, &v, nullptr)) { + if (V_VT(&v) == VT_UNKNOWN) { + V_UNKNOWN(&v)->QueryInterface(__uuidof(INetConnection), (void **)&pNC); + if (pNC) { + INetConnectionProps *pNCP = nullptr; + pNSM->get_NetConnectionProps(pNC, &pNCP); + if (!pNCP) { + printf("failed to get NetConnectionProps!\r\n"); + } else { + // check properties for firewalled or shared connection + DWORD dwCharacteristics = 0; + pNCP->get_Characteristics(&dwCharacteristics); + if (dwCharacteristics & (NCCF_SHARED | NCCF_FIREWALLED)) { + NETCON_MEDIATYPE MediaType = NCM_NONE; + pNCP->get_MediaType(&MediaType); + if ((MediaType != NCM_SHAREDACCESSHOST_LAN) && + (MediaType != NCM_SHAREDACCESSHOST_RAS)) { + // got a shared/firewalled connection + bFoundIt = TRUE; + } + } + + BSTR sName = {}; + TCHAR ifName[MAX_PATH]; + + pNCP->get_Name(&sName); + + WideCharToTChar2(sName, ifName, MAX_PATH); + SysFreeString(sName); + + printf("Get NC Name %s\r\n", ifName); + if(strcmp(ifName, "admin") == 0) { + bFoundIt = TRUE; + } + pNCP->Release(); + } + if (bFoundIt == FALSE) { + pNC->Release(); + pNC = nullptr; + } + } + } + VariantClear(&v); + if (bFoundIt == TRUE) { + break; + } + } + pEV->Release(); + } + pNSECC->Release(); + } + if (pNC == nullptr) { + printf("failed to find a valid connection!\r\n"); + return E_FAIL; + } + INetSharingConfiguration *pNSC = nullptr; + hr = pNSM->get_INetSharingConfigurationForINetConnection(pNC, &pNSC); + + if (!pNSC) { + printf("can't make INetSharingConfiguration object!\r\n"); + return hr; + } + + NETCON_PROPERTIES *pNP = nullptr; + pNC->GetProperties(&pNP); + + hr = pNSM->get_INetSharingConfigurationForINetConnection(pNC, &pNSC); + printf("**************find nic srcName : %s\r\n", static_cast(CW2A(pNP->pszwName))); + //hr = pNSC->DisableSharing(); + Sleep(500); + //getchar(); + hr = pNSC->EnableSharing(ICSSHARINGTYPE_PUBLIC); + + pNC->Release(); // don't need this anymore + pNSC->Release(); + return hr; +} + HRESULT shareNet(INetSharingManager *pNSM, const char *srcName, const char *dstName) { INetConnection *pNC = nullptr; INetSharingConfiguration *pNSC = nullptr; @@ -33,7 +152,7 @@ HRESULT shareNet(INetSharingManager *pNSM, const char *srcName, const char *dstN if (V_VT(&v) == VT_UNKNOWN) { V_UNKNOWN(&v)->QueryInterface(__uuidof(INetConnection), (void **)&pNC); if (pNC) { - WCHAR guid[256]; + WCHAR guid[256]; NETCON_PROPERTIES *pNP = nullptr; pNC->GetProperties(&pNP); //setlocale(LC_ALL, "chs"); @@ -49,27 +168,29 @@ HRESULT shareNet(INetSharingManager *pNSM, const char *srcName, const char *dstN if (pNP->Status != NCS_CONNECTED) { continue; } - TCHAR* tmpName = CW2A(pNP->pszwName); - // printf("###### |%s| : |%s|\r\n", tmpName, ""); + TCHAR *tmpName = CW2A(pNP->pszwName); + // printf("###### |%s| : |%s|\r\n", tmpName, ""); - hr = pNSM->get_INetSharingConfigurationForINetConnection(pNC, &pNSC); - if (!strcmp(tmpName, (char *)srcName)) { - printf("**************find nic srcName : %s\r\n", (char *)srcName); + if (i == 2) { + hr = pNSM->get_INetSharingConfigurationForINetConnection(pNC, &pNSC); + printf("**************find nic srcName : %s\r\n", static_cast(CW2A(pNP->pszwName))); //hr = pNSC->DisableSharing(); Sleep(500); //getchar(); hr = pNSC->EnableSharing(ICSSHARINGTYPE_PUBLIC); + pNSC->Release(); } - pNSC->Release(); -#if 0 - hr = pNSM->get_INetSharingConfigurationForINetConnection(pNC, &pNSC); - if (!strcmp(tmpName.c_str(), (char *)dstName)) { - printf("**************find nic dstName : %s\r\n", (char *)dstName); + +#if 1 + + if (i == 5) { + hr = pNSM->get_INetSharingConfigurationForINetConnection(pNC, &pNSC); + printf("**************find nic dstName : %s\r\n", static_cast(CW2A(pNP->pszwName))); //hr = pNSC->DisableSharing(); Sleep(500); hr = pNSC->EnableSharing(ICSSHARINGTYPE_PRIVATE); + pNSC->Release(); } - pNSC->Release(); #endif } } @@ -100,8 +221,8 @@ int NetShare() { printf(TEXT("failed to create NetSharingManager object\r\n")); } else { //shareNet(pNSM, "WLAN", "мн╠Ф═Э 4"); - shareNet(pNSM, "", ""); + shareNet2(pNSM); //StartHostednetwork(); } return 0; -} +} \ No newline at end of file diff --git a/NetTunnelSDKTestApp/NetTunnelSDKTestApp.cpp b/NetTunnelSDKTestApp/NetTunnelSDKTestApp.cpp index dbeeca5..cb5c839 100644 --- a/NetTunnelSDKTestApp/NetTunnelSDKTestApp.cpp +++ b/NetTunnelSDKTestApp/NetTunnelSDKTestApp.cpp @@ -7,14 +7,41 @@ #include "tunnel.h" #include "globalcfg.h" +#include "network.h" #include "user.h" #include "usrerr.h" const TCHAR *g_AppPath = TEXT("C:\\Users\\HuangXin\\Documents\\development\\visual_studio\\tunnel_windows\\x64\\Debug"); const TCHAR *g_SvrUserName = TEXT("tunnel_svr"); const TCHAR *g_PlatformURL = TEXT("http://xajhuang.com:9276"); + //const TCHAR *g_PlatformURL = TEXT("http://localhost:9276"); +void test_socket() { + /*WSADATA wsa_data; + WORD wsa_version = MAKEWORD(2, 2); + WSAStartup(wsa_version, &wsa_data);*/ + const SOCKET sd = socket(AF_INET, SOCK_STREAM, 0); //server descriptor + sockaddr_in server {}; + int addrSize = sizeof(sockaddr_in); + + server.sin_family = AF_INET; + server.sin_addr.s_addr = inet_addr (TEXT("127.0.0.1")); + server.sin_port = htons(0); + + if (bind(sd, reinterpret_cast(&server), sizeof(struct sockaddr)) == -1) { + printf("error....\n"); + } + + printf("Set Bind Port: %d\n", ntohs(server.sin_port)); //is still 0 + + sockaddr_in bindAddr {}; + + int ret = getsockname(sd, reinterpret_cast(&bindAddr), &addrSize); + + printf("Bind port %d ret: %d\n", ntohs(bindAddr.sin_port), WSAGetLastError()); +} + #if 0 int service_test() { TCHAR szSvcName[] = _T("WireGuard"); @@ -88,12 +115,12 @@ int service_test() { int tunnel_service() { PUSER_SERVER_CONFIG pSvrCfg; - TCHAR logPath[MAX_PATH]; + //TCHAR logPath[MAX_PATH]; - TunnelSDKInitEnv(g_AppPath, g_PlatformURL, true); + TunnelSDKInitEnv(g_AppPath, g_PlatformURL, nullptr, LOG_DEBUG, true); - StringCbPrintf(logPath, MAX_PATH, TEXT("%s\\TestApp.log"), g_AppPath); - InitTunnelSDKLog(logPath, LOG_DEBUG); + //StringCbPrintf(logPath, MAX_PATH, TEXT("%s\\TestApp.log"), g_AppPath); + //InitTunnelSDKLog(nullptr, LOG_DEBUG); // Server 端用户名建议固定为一个字符串,因为每个云电脑上有且只有一个用户名, 长度不要超过32字符 int ret = GetUserServerConfigure(g_SvrUserName, "asfdafdafdaf", &pSvrCfg); @@ -115,7 +142,10 @@ int main() { //GetInterface(); //CryptoExample(); //SetRouteTable(); - tunnel_service(); + + //CreatePorxyService(); + //tunnel_service(); + test_socket(); while (true) { Sleep(100); diff --git a/NetTunnelSDKTestApp/NetTunnelSDKTestApp.vcxproj b/NetTunnelSDKTestApp/NetTunnelSDKTestApp.vcxproj index 2123aa1..ca7d327 100644 --- a/NetTunnelSDKTestApp/NetTunnelSDKTestApp.vcxproj +++ b/NetTunnelSDKTestApp/NetTunnelSDKTestApp.vcxproj @@ -130,6 +130,7 @@ + diff --git a/NetTunnelSDKTestApp/NetTunnelSDKTestApp.vcxproj.filters b/NetTunnelSDKTestApp/NetTunnelSDKTestApp.vcxproj.filters index 91dc69e..2333458 100644 --- a/NetTunnelSDKTestApp/NetTunnelSDKTestApp.vcxproj.filters +++ b/NetTunnelSDKTestApp/NetTunnelSDKTestApp.vcxproj.filters @@ -30,6 +30,9 @@ 源文件 + + 源文件 + diff --git a/NetTunnelSDKTestApp/firewall.cpp b/NetTunnelSDKTestApp/firewall.cpp new file mode 100644 index 0000000..3b41d6e --- /dev/null +++ b/NetTunnelSDKTestApp/firewall.cpp @@ -0,0 +1,292 @@ +// Copyright (C) Microsoft. All rights reserved. + +#define WIN32_LEAN_AND_MEAN +#include +#include +#include +#include + +#pragma comment(lib, "ole32.lib") +#pragma comment(lib, "oleaut32.lib") + +// as in winsock.h +#define NAT_PROTOCOL_TCP 6 + +HRESULT DeletePortMapping(INetSharingManager *pNSM, + UCHAR ucIPProtocol, + short usExternalPort) { // this is done in 2 parts: + // 1: enum connections until we get one that we can convert into an INetSharingConfiguration + // 2: then, enum portmappings, and delete if we find a match. + + // PART 1: find a valid connection + INetConnection *pNC = nullptr; // fill this out for part 2 below + + INetSharingEveryConnectionCollection *pNSECC = nullptr; + HRESULT hr = pNSM->get_EnumEveryConnection(&pNSECC); + if (!pNSECC) { + wprintf(L"failed to get EveryConnectionCollection!\r\n"); + } else { + // enumerate connections + IEnumVARIANT *pEV = nullptr; + IUnknown *pUnk = nullptr; + hr = pNSECC->get__NewEnum(&pUnk); + if (pUnk) { + hr = pUnk->QueryInterface(__uuidof(IEnumVARIANT), (void **)&pEV); + pUnk->Release(); + } + if (pEV) { + VARIANT v; + VariantInit(&v); + BOOL bFoundIt = FALSE; + while (S_OK == pEV->Next(1, &v, nullptr)) { + if (V_VT(&v) == VT_UNKNOWN) { + V_UNKNOWN(&v)->QueryInterface(__uuidof(INetConnection), (void **)&pNC); + if (pNC) { + INetConnectionProps *pNCP = nullptr; + pNSM->get_NetConnectionProps(pNC, &pNCP); + if (!pNCP) { + wprintf(L"failed to get NetConnectionProps!\r\n"); + } else { + // check properties for firewalled or shared connection + DWORD dwCharacteristics = 0; + pNCP->get_Characteristics(&dwCharacteristics); + if (dwCharacteristics & (NCCF_SHARED | NCCF_FIREWALLED)) { + NETCON_MEDIATYPE MediaType = NCM_NONE; + pNCP->get_MediaType(&MediaType); + if ((MediaType != NCM_SHAREDACCESSHOST_LAN) &&(MediaType != NCM_SHAREDACCESSHOST_RAS)) { + // got a shared/firewalled connection + bFoundIt = TRUE; + } + } + pNCP->Release(); + } + if (bFoundIt == FALSE) { + pNC->Release(); + pNC = nullptr; + } + } + } + VariantClear(&v); + if (bFoundIt == TRUE) { + break; + } + } + pEV->Release(); + } + pNSECC->Release(); + } + if (pNC == nullptr) { + wprintf(L"failed to find a valid connection!\r\n"); + return E_FAIL; + } + INetSharingConfiguration *pNSC = nullptr; + hr = pNSM->get_INetSharingConfigurationForINetConnection(pNC, &pNSC); + pNC->Release(); // don't need this anymore + if (!pNSC) { + wprintf(L"can't make INetSharingConfiguration object!\r\n"); + return hr; + } + + // PART 2: enum port mappings, deleting match, if any + INetSharingPortMappingCollection *pNSPMC = nullptr; + hr = pNSC->get_EnumPortMappings(ICSSC_DEFAULT, &pNSPMC); + if (!pNSPMC) { + wprintf(L"can't get PortMapping collection!\r\n"); + } else { + + // this is the interface to be filled out by the code below + INetSharingPortMapping *pNSPM = nullptr; + + IEnumVARIANT *pEV = nullptr; + IUnknown *pUnk = nullptr; + hr = pNSPMC->get__NewEnum(&pUnk); + if (pUnk) { + hr = pUnk->QueryInterface(__uuidof(IEnumVARIANT), (void **)&pEV); + pUnk->Release(); + } + if (pEV) { + VARIANT v; + VariantInit(&v); + BOOL bFoundIt = FALSE; + while (S_OK == pEV->Next(1, &v, nullptr)) { + if (V_VT(&v) == VT_DISPATCH) { + V_DISPATCH(&v)->QueryInterface(__uuidof(INetSharingPortMapping), (void **)&pNSPM); + if (pNSPM) { + INetSharingPortMappingProps *pNSPMP = nullptr; + hr = pNSPM->get_Properties(&pNSPMP); + if (pNSPMP) { + UCHAR uc = 0; + pNSPMP->get_IPProtocol(&uc); + long usExternal = 0; + pNSPMP->get_ExternalPort(&usExternal); + if ((uc == ucIPProtocol) &&(usExternal == usExternalPort)) { + bFoundIt = TRUE; + } + + pNSPMP->Release(); + } + if (bFoundIt == FALSE) { // hang onto reference to pNSPM iff found (used below) + pNSPM->Release(); + pNSPM = nullptr; + } + } + } + VariantClear(&v); + if (bFoundIt == TRUE) { + break; // bail out if we've found one + } + } + pEV->Release(); + } + + if (pNSPM) { + hr = pNSPM->Delete(); // or pNSC->RemovePortMapping (pNSPM); + wprintf(L"just deleted a port mapping!\r\n"); + + pNSPM->Release(); + } + pNSPMC->Release(); + } + pNSC->Release(); + return hr; +} + +HRESULT AddAsymmetricPortMapping(INetSharingConfiguration *pNSC) { + HRESULT hr = S_OK; +#if 0 + VARIANT_BOOL vb1 = VARIANT_FALSE; + VARIANT_BOOL vb2 = VARIANT_FALSE; + pNSC->get_SharingEnabled(&vb1); + pNSC->get_InternetFirewallEnabled(&vb2); + if ((vb1 == VARIANT_FALSE) &&(vb2 == VARIANT_FALSE)) { + wprintf(L"sharing and/or firewall not enabled on this connection!\r\n"); + } else { + INetSharingPortMapping *pNSPM = nullptr; + hr = pNSC->AddPortMapping("Ben's Port Mapping", + NAT_PROTOCOL_TCP, + 555, + 444, + 0, + "192.168.0.2", + ICSTT_IPADDRESS, + &pNSPM); + if (pNSPM) { + wprintf(L"just added NAT_PROTOCOL_TCP, 555, 444!\r\n"); + + hr = pNSPM->Enable(); + wprintf(L"just enabled port mapping!\r\n"); + + pNSPM->Release(); + } else { + wprintf(L"failed to add asymmetric port mapping!\r\n"); + } + } +#endif + return hr; +} + +HRESULT DoTheWork(INetSharingManager *pNSM) { // add a port mapping to every firewalled or shared connection + + INetSharingEveryConnectionCollection *pNSECC = nullptr; + HRESULT hr = pNSM->get_EnumEveryConnection(&pNSECC); + if (!pNSECC) { + wprintf(L"failed to get EveryConnectionCollection!\r\n"); + } else { + + // enumerate connections + IEnumVARIANT *pEV = nullptr; + IUnknown *pUnk = nullptr; + hr = pNSECC->get__NewEnum(&pUnk); + if (pUnk) { + hr = pUnk->QueryInterface(__uuidof(IEnumVARIANT), (void **)&pEV); + pUnk->Release(); + } + if (pEV) { + VARIANT v; + VariantInit(&v); + while (S_OK == pEV->Next(1, &v, nullptr)) { + if (V_VT(&v) == VT_UNKNOWN) { + INetConnection *pNC = nullptr; + V_UNKNOWN(&v)->QueryInterface(__uuidof(INetConnection), (void **)&pNC); + if (pNC) { + INetConnectionProps *pNCP = nullptr; + pNSM->get_NetConnectionProps(pNC, &pNCP); + if (!pNCP) { + wprintf(L"failed to get NetConnectionProps!\r\n"); + } else { + // check properties for firewalled or shared connection + DWORD dwCharacteristics = 0; + pNCP->get_Characteristics(&dwCharacteristics); + if (dwCharacteristics & (NCCF_SHARED | NCCF_FIREWALLED)) { + NETCON_MEDIATYPE MediaType = NCM_NONE; + pNCP->get_MediaType(&MediaType); + if ((MediaType != NCM_SHAREDACCESSHOST_LAN) && + (MediaType != NCM_SHAREDACCESSHOST_RAS)) { + // got a shared/firewalled connection + INetSharingConfiguration *pNSC = nullptr; + hr = pNSM->get_INetSharingConfigurationForINetConnection(pNC, &pNSC); + if (!pNSC) { + wprintf(L"can't make INetSharingConfiguration object!\r\n"); + } else { + hr = AddAsymmetricPortMapping(pNSC); + pNSC->Release(); + } + } + } + pNCP->Release(); + } + pNC->Release(); + } + } + VariantClear(&v); + } + pEV->Release(); + } + pNSECC->Release(); + } + return hr; +} + +int main3() { + CoInitialize(nullptr); + + // init security to enum RAS connections + CoInitializeSecurity(nullptr, + -1, + nullptr, + nullptr, + RPC_C_AUTHN_LEVEL_PKT, + RPC_C_IMP_LEVEL_IMPERSONATE, + nullptr, + EOAC_NONE, + nullptr); + + INetSharingManager *pNSM = nullptr; + HRESULT hr = ::CoCreateInstance(CLSID_NetSharingManager, + nullptr, + CLSCTX_ALL, + IID_INetSharingManager, + reinterpret_cast(&pNSM)); + if (!pNSM) { + wprintf(L"failed to create NetSharingManager object\r\n"); + } else { + // in case it exists already + DeletePortMapping(pNSM, NAT_PROTOCOL_TCP, 555); + + // add a port mapping to every shared or firewalled connection. + hr = DoTheWork(pNSM); + if (SUCCEEDED(hr)) { + + // do other work here. + // when you're done, + // clean up port mapping + + hr = DeletePortMapping(pNSM, NAT_PROTOCOL_TCP, 555); + } + + pNSM->Release(); + } + + CoUninitialize(); + return (int)hr; +} \ No newline at end of file diff --git a/TestNetTunnelSDK/TestNetTunnelSDK.cpp b/TestNetTunnelSDK/TestNetTunnelSDK.cpp index 51fcfe5..cc89ec1 100644 --- a/TestNetTunnelSDK/TestNetTunnelSDK.cpp +++ b/TestNetTunnelSDK/TestNetTunnelSDK.cpp @@ -18,11 +18,13 @@ TEST_MODULE_INITIALIZE(ModuleInitialize) { "C:\\Users\\HuangXin\\Documents\\development\\visual_studio\\tunnel_windows\\NetTunnelApp\\bin\\Debug"); Logger::WriteMessage("In Module Initialize"); - Assert::AreEqual(0, TunnelSDKInitEnv(path, "http://xajhuang.com:9276", false)); - - InitTunnelSDKLog(TEXT("C:\\Users\\HuangXin\\Documents\\development\\visual_studio\\tunnel_" - "windows\\NetTunnelApp\\bin\\Debug\\utest.log"), - LOG_DEBUG); + Assert::AreEqual(0, + TunnelSDKInitEnv(path, + "http://xajhuang.com:9276", + TEXT("C:\\Users\\HuangXin\\Documents\\development\\visual_studio\\tunnel_" + "windows\\NetTunnelApp\\bin\\Debug\\utest.log"), + LOG_DEBUG, + false)); } TEST_MODULE_CLEANUP(ModuleCleanup) { @@ -137,16 +139,17 @@ public: TEST_METHOD(TestGetInternetConnectAdaptersIndex) { bool bRet; - Assert::AreEqual(RET_OK, IsInternetConnectAdapter(10, &bRet)); + Assert::AreEqual(RET_OK, IsInternetConnectAdapter(9, &bRet)); Assert::AreEqual(true, bRet); - Assert::AreEqual(RET_OK, IsInternetConnectAdapter(1, &bRet)); + Assert::AreEqual(RET_OK, IsInternetConnectAdapter(44, &bRet)); Assert::AreEqual(false, bRet); } - TEST_METHOD(TestEnableNetConnectionSharing) { - Assert::AreEqual(RET_OK, SetNetConnectionSharing(TEXT("wg_cli"), true, true)); - Assert::AreEqual(RET_OK, SetNetConnectionSharing(TEXT("wg_cli"), false, true)); + TEST_METHOD(TestGetNetConnectionSharing) { + //bool chkStatus; + //Assert::AreEqual(RET_OK, GetNetIntelnetConnectionSharing(TEXT("admin"), &chkStatus)); + //Assert::IsTrue(chkStatus); } TEST_METHOD(TestSetNetConnectionNetworkCategory) { @@ -163,29 +166,48 @@ public: Assert::AreEqual(RET_OK, GetNetConnectionNetworkCategory(TEXT("admin"), &chkStatus)); } - TEST_METHOD(TestWaitNetAdapterConnected) { - Assert::AreEqual(RET_OK, WaitNetAdapterConnected(TEXT("admin"), 10* 1000)); + TEST_METHOD(TestWaitNetAdapterConnected) { + Assert::AreEqual(RET_OK, WaitNetAdapterConnected(TEXT("admin"), 10 * 1000)); } TEST_METHOD(TestProtoGetUserConfigure) { //Assert::AreEqual(RET_OK, ProtoGetUserConfigure("admin", "asfdsafdladf083asldf+=")); } + TEST_METHOD(TestAddRouteTable) { + Assert::AreEqual(RET_OK, AddRouteTable(TEXT("1.1.1.1"), TEXT("255.255.255.0"), TEXT("10.10.10.1"))); + } + TEST_METHOD(TestGetInterfaceGUIDByName) { GUID guid; - ; + Assert::AreEqual(RET_OK, GetInterfaceGUIDByName(TEXT("admin"), &guid)); Assert::AreNotEqual(0, static_cast(guid.Data1)); //Assert::AreEqual(RET_OK, ProtoGetUserConfigure("admin", "asfdsafdladf083asldf+=")); } + TEST_METHOD(TestSetNATRule) { + Assert::AreEqual(RET_OK, SetNATRule(TEXT("admin"), TEXT("10.10.10.250/24"))); + } + + TEST_METHOD(TestRemoveNATRule) { + Assert::AreEqual(RET_OK, RemoveNATRule(TEXT("admin"))); + } + + + TEST_METHOD(TestGetInterfaceIfIndexByIpAddr) { + ULONG index = -1; + Assert::AreEqual(RET_OK, GetInterfaceIfIndexByIpAddr(TEXT("10.10.10.1"), &index)); + Assert::AreNotEqual(-1, static_cast(index)); + } + TEST_METHOD(TestClientProgress) { PUSER_CLIENT_CONFIG pCfg = nullptr; Assert::AreEqual(RET_OK, GetUserClientConfigure(TEXT("admin"), TEXT("1323245235"), &pCfg)); Assert::IsNotNull(pCfg); - Assert::AreEqual(RET_OK, RemoteCtrlSvrCfgUserTunnel(2, TEXT("172.18.2.128/26"))); + Assert::AreEqual(RET_OK, RemoteCtrlSvrCfgUserTunnel(2, TEXT("172.18.2.0/24"))); Assert::AreEqual(RET_OK, LocalWireGuardControl(true, true)); } diff --git a/tunnel_windows.sln b/tunnel_windows.sln index 102e4fd..75a6216 100644 --- a/tunnel_windows.sln +++ b/tunnel_windows.sln @@ -24,65 +24,131 @@ Project("{54435603-DBB4-11D2-8724-00A0C9A8B90C}") = "InstallTunnelSDK", "Install EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug DLL|Any CPU = Debug DLL|Any CPU + Debug DLL|x64 = Debug DLL|x64 + Debug DLL|x86 = Debug DLL|x86 Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 + Release DLL|Any CPU = Release DLL|Any CPU + Release DLL|x64 = Release DLL|x64 + Release DLL|x86 = Release DLL|x86 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution + {1584BAD4-DBEC-43D2-BC06-08C23F02489A}.Debug DLL|Any CPU.ActiveCfg = Debug|x64 + {1584BAD4-DBEC-43D2-BC06-08C23F02489A}.Debug DLL|Any CPU.Build.0 = Debug|x64 + {1584BAD4-DBEC-43D2-BC06-08C23F02489A}.Debug DLL|x64.ActiveCfg = Debug|x64 + {1584BAD4-DBEC-43D2-BC06-08C23F02489A}.Debug DLL|x64.Build.0 = Debug|x64 + {1584BAD4-DBEC-43D2-BC06-08C23F02489A}.Debug DLL|x86.ActiveCfg = Debug|Win32 + {1584BAD4-DBEC-43D2-BC06-08C23F02489A}.Debug DLL|x86.Build.0 = Debug|Win32 {1584BAD4-DBEC-43D2-BC06-08C23F02489A}.Debug|Any CPU.ActiveCfg = Debug|x64 {1584BAD4-DBEC-43D2-BC06-08C23F02489A}.Debug|Any CPU.Build.0 = Debug|x64 {1584BAD4-DBEC-43D2-BC06-08C23F02489A}.Debug|x64.ActiveCfg = Debug|x64 {1584BAD4-DBEC-43D2-BC06-08C23F02489A}.Debug|x64.Build.0 = Debug|x64 {1584BAD4-DBEC-43D2-BC06-08C23F02489A}.Debug|x86.ActiveCfg = Debug|Win32 {1584BAD4-DBEC-43D2-BC06-08C23F02489A}.Debug|x86.Build.0 = Debug|Win32 + {1584BAD4-DBEC-43D2-BC06-08C23F02489A}.Release DLL|Any CPU.ActiveCfg = Release|x64 + {1584BAD4-DBEC-43D2-BC06-08C23F02489A}.Release DLL|Any CPU.Build.0 = Release|x64 + {1584BAD4-DBEC-43D2-BC06-08C23F02489A}.Release DLL|x64.ActiveCfg = Release|x64 + {1584BAD4-DBEC-43D2-BC06-08C23F02489A}.Release DLL|x64.Build.0 = Release|x64 + {1584BAD4-DBEC-43D2-BC06-08C23F02489A}.Release DLL|x86.ActiveCfg = Release|Win32 + {1584BAD4-DBEC-43D2-BC06-08C23F02489A}.Release DLL|x86.Build.0 = Release|Win32 {1584BAD4-DBEC-43D2-BC06-08C23F02489A}.Release|Any CPU.ActiveCfg = Release|x64 {1584BAD4-DBEC-43D2-BC06-08C23F02489A}.Release|Any CPU.Build.0 = Release|x64 {1584BAD4-DBEC-43D2-BC06-08C23F02489A}.Release|x64.ActiveCfg = Release|x64 {1584BAD4-DBEC-43D2-BC06-08C23F02489A}.Release|x64.Build.0 = Release|x64 {1584BAD4-DBEC-43D2-BC06-08C23F02489A}.Release|x86.ActiveCfg = Release|Win32 {1584BAD4-DBEC-43D2-BC06-08C23F02489A}.Release|x86.Build.0 = Release|Win32 + {79995848-FD05-46F5-A7FE-46265E540E32}.Debug DLL|Any CPU.ActiveCfg = Debug|Any CPU + {79995848-FD05-46F5-A7FE-46265E540E32}.Debug DLL|Any CPU.Build.0 = Debug|Any CPU + {79995848-FD05-46F5-A7FE-46265E540E32}.Debug DLL|x64.ActiveCfg = Debug|Any CPU + {79995848-FD05-46F5-A7FE-46265E540E32}.Debug DLL|x64.Build.0 = Debug|Any CPU + {79995848-FD05-46F5-A7FE-46265E540E32}.Debug DLL|x86.ActiveCfg = Debug|Any CPU + {79995848-FD05-46F5-A7FE-46265E540E32}.Debug DLL|x86.Build.0 = Debug|Any CPU {79995848-FD05-46F5-A7FE-46265E540E32}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {79995848-FD05-46F5-A7FE-46265E540E32}.Debug|Any CPU.Build.0 = Debug|Any CPU {79995848-FD05-46F5-A7FE-46265E540E32}.Debug|x64.ActiveCfg = Debug|Any CPU {79995848-FD05-46F5-A7FE-46265E540E32}.Debug|x64.Build.0 = Debug|Any CPU {79995848-FD05-46F5-A7FE-46265E540E32}.Debug|x86.ActiveCfg = Debug|Any CPU {79995848-FD05-46F5-A7FE-46265E540E32}.Debug|x86.Build.0 = Debug|Any CPU + {79995848-FD05-46F5-A7FE-46265E540E32}.Release DLL|Any CPU.ActiveCfg = Release|Any CPU + {79995848-FD05-46F5-A7FE-46265E540E32}.Release DLL|Any CPU.Build.0 = Release|Any CPU + {79995848-FD05-46F5-A7FE-46265E540E32}.Release DLL|x64.ActiveCfg = Release|Any CPU + {79995848-FD05-46F5-A7FE-46265E540E32}.Release DLL|x64.Build.0 = Release|Any CPU + {79995848-FD05-46F5-A7FE-46265E540E32}.Release DLL|x86.ActiveCfg = Release|Any CPU + {79995848-FD05-46F5-A7FE-46265E540E32}.Release DLL|x86.Build.0 = Release|Any CPU {79995848-FD05-46F5-A7FE-46265E540E32}.Release|Any CPU.ActiveCfg = Release|Any CPU {79995848-FD05-46F5-A7FE-46265E540E32}.Release|Any CPU.Build.0 = Release|Any CPU {79995848-FD05-46F5-A7FE-46265E540E32}.Release|x64.ActiveCfg = Release|Any CPU {79995848-FD05-46F5-A7FE-46265E540E32}.Release|x64.Build.0 = Release|Any CPU {79995848-FD05-46F5-A7FE-46265E540E32}.Release|x86.ActiveCfg = Release|Any CPU {79995848-FD05-46F5-A7FE-46265E540E32}.Release|x86.Build.0 = Release|Any CPU + {61FE87EB-A3BA-4A7E-971C-69CB05F5C81C}.Debug DLL|Any CPU.ActiveCfg = Debug|x64 + {61FE87EB-A3BA-4A7E-971C-69CB05F5C81C}.Debug DLL|Any CPU.Build.0 = Debug|x64 + {61FE87EB-A3BA-4A7E-971C-69CB05F5C81C}.Debug DLL|x64.ActiveCfg = Debug|x64 + {61FE87EB-A3BA-4A7E-971C-69CB05F5C81C}.Debug DLL|x64.Build.0 = Debug|x64 + {61FE87EB-A3BA-4A7E-971C-69CB05F5C81C}.Debug DLL|x86.ActiveCfg = Debug|Win32 + {61FE87EB-A3BA-4A7E-971C-69CB05F5C81C}.Debug DLL|x86.Build.0 = Debug|Win32 {61FE87EB-A3BA-4A7E-971C-69CB05F5C81C}.Debug|Any CPU.ActiveCfg = Debug|x64 {61FE87EB-A3BA-4A7E-971C-69CB05F5C81C}.Debug|Any CPU.Build.0 = Debug|x64 {61FE87EB-A3BA-4A7E-971C-69CB05F5C81C}.Debug|x64.ActiveCfg = Debug|x64 {61FE87EB-A3BA-4A7E-971C-69CB05F5C81C}.Debug|x64.Build.0 = Debug|x64 {61FE87EB-A3BA-4A7E-971C-69CB05F5C81C}.Debug|x86.ActiveCfg = Debug|Win32 {61FE87EB-A3BA-4A7E-971C-69CB05F5C81C}.Debug|x86.Build.0 = Debug|Win32 + {61FE87EB-A3BA-4A7E-971C-69CB05F5C81C}.Release DLL|Any CPU.ActiveCfg = Release|x64 + {61FE87EB-A3BA-4A7E-971C-69CB05F5C81C}.Release DLL|Any CPU.Build.0 = Release|x64 + {61FE87EB-A3BA-4A7E-971C-69CB05F5C81C}.Release DLL|x64.ActiveCfg = Release|x64 + {61FE87EB-A3BA-4A7E-971C-69CB05F5C81C}.Release DLL|x64.Build.0 = Release|x64 + {61FE87EB-A3BA-4A7E-971C-69CB05F5C81C}.Release DLL|x86.ActiveCfg = Release|Win32 + {61FE87EB-A3BA-4A7E-971C-69CB05F5C81C}.Release DLL|x86.Build.0 = Release|Win32 {61FE87EB-A3BA-4A7E-971C-69CB05F5C81C}.Release|Any CPU.ActiveCfg = Release|x64 {61FE87EB-A3BA-4A7E-971C-69CB05F5C81C}.Release|Any CPU.Build.0 = Release|x64 {61FE87EB-A3BA-4A7E-971C-69CB05F5C81C}.Release|x64.ActiveCfg = Release|x64 {61FE87EB-A3BA-4A7E-971C-69CB05F5C81C}.Release|x64.Build.0 = Release|x64 {61FE87EB-A3BA-4A7E-971C-69CB05F5C81C}.Release|x86.ActiveCfg = Release|Win32 {61FE87EB-A3BA-4A7E-971C-69CB05F5C81C}.Release|x86.Build.0 = Release|Win32 + {9F44F41E-FACF-472D-A382-A40D0A84DB2C}.Debug DLL|Any CPU.ActiveCfg = Debug|x64 + {9F44F41E-FACF-472D-A382-A40D0A84DB2C}.Debug DLL|Any CPU.Build.0 = Debug|x64 + {9F44F41E-FACF-472D-A382-A40D0A84DB2C}.Debug DLL|x64.ActiveCfg = Debug|x64 + {9F44F41E-FACF-472D-A382-A40D0A84DB2C}.Debug DLL|x64.Build.0 = Debug|x64 + {9F44F41E-FACF-472D-A382-A40D0A84DB2C}.Debug DLL|x86.ActiveCfg = Debug|Win32 + {9F44F41E-FACF-472D-A382-A40D0A84DB2C}.Debug DLL|x86.Build.0 = Debug|Win32 {9F44F41E-FACF-472D-A382-A40D0A84DB2C}.Debug|Any CPU.ActiveCfg = Debug|x64 {9F44F41E-FACF-472D-A382-A40D0A84DB2C}.Debug|Any CPU.Build.0 = Debug|x64 {9F44F41E-FACF-472D-A382-A40D0A84DB2C}.Debug|x64.ActiveCfg = Debug|x64 {9F44F41E-FACF-472D-A382-A40D0A84DB2C}.Debug|x64.Build.0 = Debug|x64 {9F44F41E-FACF-472D-A382-A40D0A84DB2C}.Debug|x86.ActiveCfg = Debug|Win32 {9F44F41E-FACF-472D-A382-A40D0A84DB2C}.Debug|x86.Build.0 = Debug|Win32 + {9F44F41E-FACF-472D-A382-A40D0A84DB2C}.Release DLL|Any CPU.ActiveCfg = Release|x64 + {9F44F41E-FACF-472D-A382-A40D0A84DB2C}.Release DLL|Any CPU.Build.0 = Release|x64 + {9F44F41E-FACF-472D-A382-A40D0A84DB2C}.Release DLL|x64.ActiveCfg = Release|x64 + {9F44F41E-FACF-472D-A382-A40D0A84DB2C}.Release DLL|x64.Build.0 = Release|x64 + {9F44F41E-FACF-472D-A382-A40D0A84DB2C}.Release DLL|x86.ActiveCfg = Release|Win32 + {9F44F41E-FACF-472D-A382-A40D0A84DB2C}.Release DLL|x86.Build.0 = Release|Win32 {9F44F41E-FACF-472D-A382-A40D0A84DB2C}.Release|Any CPU.ActiveCfg = Release|x64 {9F44F41E-FACF-472D-A382-A40D0A84DB2C}.Release|Any CPU.Build.0 = Release|x64 {9F44F41E-FACF-472D-A382-A40D0A84DB2C}.Release|x64.ActiveCfg = Release|x64 {9F44F41E-FACF-472D-A382-A40D0A84DB2C}.Release|x64.Build.0 = Release|x64 {9F44F41E-FACF-472D-A382-A40D0A84DB2C}.Release|x86.ActiveCfg = Release|Win32 {9F44F41E-FACF-472D-A382-A40D0A84DB2C}.Release|x86.Build.0 = Release|Win32 + {FE91D4D0-29A6-4C58-874F-11F6AC1D50CD}.Debug DLL|Any CPU.ActiveCfg = Debug + {FE91D4D0-29A6-4C58-874F-11F6AC1D50CD}.Debug DLL|Any CPU.Build.0 = Debug + {FE91D4D0-29A6-4C58-874F-11F6AC1D50CD}.Debug DLL|x64.ActiveCfg = Debug + {FE91D4D0-29A6-4C58-874F-11F6AC1D50CD}.Debug DLL|x64.Build.0 = Debug + {FE91D4D0-29A6-4C58-874F-11F6AC1D50CD}.Debug DLL|x86.ActiveCfg = Debug + {FE91D4D0-29A6-4C58-874F-11F6AC1D50CD}.Debug DLL|x86.Build.0 = Debug {FE91D4D0-29A6-4C58-874F-11F6AC1D50CD}.Debug|Any CPU.ActiveCfg = Debug {FE91D4D0-29A6-4C58-874F-11F6AC1D50CD}.Debug|x64.ActiveCfg = Debug {FE91D4D0-29A6-4C58-874F-11F6AC1D50CD}.Debug|x86.ActiveCfg = Debug + {FE91D4D0-29A6-4C58-874F-11F6AC1D50CD}.Release DLL|Any CPU.ActiveCfg = Release + {FE91D4D0-29A6-4C58-874F-11F6AC1D50CD}.Release DLL|Any CPU.Build.0 = Release + {FE91D4D0-29A6-4C58-874F-11F6AC1D50CD}.Release DLL|x64.ActiveCfg = Release + {FE91D4D0-29A6-4C58-874F-11F6AC1D50CD}.Release DLL|x64.Build.0 = Release + {FE91D4D0-29A6-4C58-874F-11F6AC1D50CD}.Release DLL|x86.ActiveCfg = Release + {FE91D4D0-29A6-4C58-874F-11F6AC1D50CD}.Release DLL|x86.Build.0 = Release {FE91D4D0-29A6-4C58-874F-11F6AC1D50CD}.Release|Any CPU.ActiveCfg = Release {FE91D4D0-29A6-4C58-874F-11F6AC1D50CD}.Release|x64.ActiveCfg = Release {FE91D4D0-29A6-4C58-874F-11F6AC1D50CD}.Release|x86.ActiveCfg = Release