From 6930c948a525201322280942b4f5fcc6f29745a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BB=84=E6=98=95?= Date: Tue, 25 Jul 2023 09:02:16 +0800 Subject: [PATCH] =?UTF-8?q?OCT=201.=20=E5=A2=9E=E5=8A=A0=20WinDivert=20?= =?UTF-8?q?=E5=BA=93=202.=20=E5=A2=9E=E5=8A=A0=20UTHASH=20=E5=BA=93=203.?= =?UTF-8?q?=20=E5=A2=9E=E5=8A=A0=E9=83=A8=E5=88=86=20SCG=20=E4=BB=A3?= =?UTF-8?q?=E7=90=86=E4=BB=A3=E7=A0=81=204.=20=E5=A4=87=E4=BB=BD=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 11 +- InstallTunnelSDK/InstallTunnelSDK.vdproj | 70 +- NetTunnelApp/MainForm.Designer.cs | 124 +- NetTunnelApp/MainForm.cs | 46 +- NetTunnelApp/NetTunnelLib.cs | 26 +- NetTunnelSDK/ControlService.cpp | 45 +- NetTunnelSDK/NetTunnelSDK.vcxproj | 3 + NetTunnelSDK/NetTunnelSDK.vcxproj.filters | 6 + NetTunnelSDK/ProxyService.cpp | 377 + NetTunnelSDK/UserManager.cpp | 139 +- NetTunnelSDK/WinDivert/include/windivert.h | 630 + NetTunnelSDK/WinDivert/x86/WinDivert.dll | Bin 0 -> 43520 bytes NetTunnelSDK/WinDivert/x86/WinDivert.lib | Bin 0 -> 25294 bytes NetTunnelSDK/WinDivert/x86/WinDivert32.sys | Bin 0 -> 79792 bytes NetTunnelSDK/WinDivert/x86/WinDivert64.sys | Bin 0 -> 94144 bytes NetTunnelSDK/dllmain.cpp | 3 +- NetTunnelSDK/globalcfg.h | 2 + NetTunnelSDK/httplib.h | 13216 ++++++++-------- NetTunnelSDK/ipcalc.cpp | 82 +- NetTunnelSDK/misc.h | 21 +- NetTunnelSDK/network.cpp | 677 +- NetTunnelSDK/network.h | 101 +- NetTunnelSDK/protocol.cpp | 12 + NetTunnelSDK/resource/iconsTray.ico | Bin 0 -> 163212 bytes NetTunnelSDK/tunnel.cpp | 158 +- NetTunnelSDK/tunnel.h | 55 +- NetTunnelSDK/user.h | 1 + NetTunnelSDK/usrerr.h | 20 +- NetTunnelSDK/uthash/utarray.h | 285 + NetTunnelSDK/uthash/uthash.h | 1136 ++ NetTunnelSDK/uthash/utlist.h | 1131 ++ NetTunnelSDK/uthash/utringbuffer.h | 128 + NetTunnelSDK/uthash/utstack.h | 87 + NetTunnelSDK/uthash/utstring.h | 351 + NetTunnelSDK/wireguard.cpp | 15 +- NetTunnelSDKTestApp/NetShare.cpp | 157 +- NetTunnelSDKTestApp/NetTunnelSDKTestApp.cpp | 40 +- .../NetTunnelSDKTestApp.vcxproj | 1 + .../NetTunnelSDKTestApp.vcxproj.filters | 3 + NetTunnelSDKTestApp/firewall.cpp | 292 + TestNetTunnelSDK/TestNetTunnelSDK.cpp | 50 +- tunnel_windows.sln | 66 + 42 files changed, 12828 insertions(+), 6739 deletions(-) create mode 100644 NetTunnelSDK/ProxyService.cpp create mode 100644 NetTunnelSDK/WinDivert/include/windivert.h create mode 100644 NetTunnelSDK/WinDivert/x86/WinDivert.dll create mode 100644 NetTunnelSDK/WinDivert/x86/WinDivert.lib create mode 100644 NetTunnelSDK/WinDivert/x86/WinDivert32.sys create mode 100644 NetTunnelSDK/WinDivert/x86/WinDivert64.sys create mode 100644 NetTunnelSDK/resource/iconsTray.ico create mode 100644 NetTunnelSDK/uthash/utarray.h create mode 100644 NetTunnelSDK/uthash/uthash.h create mode 100644 NetTunnelSDK/uthash/utlist.h create mode 100644 NetTunnelSDK/uthash/utringbuffer.h create mode 100644 NetTunnelSDK/uthash/utstack.h create mode 100644 NetTunnelSDK/uthash/utstring.h create mode 100644 NetTunnelSDKTestApp/firewall.cpp 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 0000000000000000000000000000000000000000..b9602c0cda1c6df6fc386b5e7575f225c06b6165 GIT binary patch literal 43520 zcmeFa3tUvy`aiq}1{`#BqoAQ_QjwP|W713%6@iVKj-ohTN-9LA$O{I0K+Q>TGs$K* z9ZyF)cCxY)r_;q>$I85bmq88CtWe2FJw;}nnTFHB?1-0+{J+oIdk>({Isf;4|L^bf zdEejgd05YS*0Y}VtoySrdvEK5>$zZ#ofo}4H|Me3jHS_;8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NetTunnelSDK/WinDivert/x86/WinDivert64.sys new file mode 100644 index 0000000000000000000000000000000000000000..218ccaf423ef0a67696226f9ef3a09149e4441d0 GIT binary patch literal 94144 zcmeFa3wTu3)%ZQRGLVE5gwa?pM2$6yVr;x526TqZz!{xL6cMbV(Q3rjD#eM!8zxLf zm>x!{V)d<7X=_`pz7?%PK!pq-3837piq`_#ml;L{?OO;?ng4I?J!g_|vF-Q0-}C?e z-}CWsa?W1+w)Wa~YpHkaxY8frcEgRs zi;4!6rHdZ7c>RM%eYoT!`#I;;_K#hJkN?fN9}Q9OGd_~=Q6Db-XgKe4US0a}@#_8h z$4995V)bqbFaG#Q!r`#zBYC%kUsK`BZvMe!Df_^d)cYKc8}4^HmK|~G5A3*|juRaP z*#jMpB|v_mp>2bB7pre~mb~OU+u<0%OP+j(f;t=>ydmPl?`8pMAfPkZuYsi?j5<_;nl}`5=;okI$7mj#S@@KHZimAhu9G>c z2slcq7+N{@^Yr@Xb~w6*Ptgfg8)>V%AlxF1WGN&22rL5SD1j|Y$kgv4z3)A}AwDy=a zZ#5NGu8MaZ=Wrx8L&kO|++s$GW=g5iqKUj3BYERgC~t-eolz^HNS>Eh%5{GS7)Oi7 z5(q@|<`|OAb%La@*2Uj@&f%ze!5X$8yNP^t9V<5w^m*?v7pba*)+{YKdOTV+O$^9wLt{eNC8_!V7rVD*mxPgg&jxNt{vfuN9lsT~=VMgUS( z*`(@Ct7u-TNR`?xubSBHBg|o4X8T)kr~Csu6`xvV?%rZrd(GI6JTuj4S~-GLK1>>^ z?WVGFGqfYCDc-xWx&U2D=<|tn)}<8zYj)Wz7|COKN}kCw+J4D*UAV(&n=9O9UF!5z zerOawG>1^5aog%fWBU3=u+Y<)m0v1!UNLdGQGD5yKqOG+ z_FJn15pP+QXORdPFYHipU?Hn1L?X()ktfP#lZq1G7C>oau0qTw{h>eOop+~e(EL&| z-i+Q-w#aP#d>$F$)d__Vta61J@ttQ{qoxF`jRDK!3|N!y^IKO|0N!m{Gdffy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eU~_ixXf zG4ZVx`_t{e+_}u&e(CcI?yg>#w|Uat6Mr__neoi3>dsp;+pm1`#8VBft!2+2Qu})0 V#@4Fw^FaA^S6x3f #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

_))<%L%@4Opt2|0besS?==CH(Aq941JT^G^7TzD)&ab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BHHNF@b}ZcuE}Lfwl26Q-SNiU$%msq=*2 zSK5b{4$d}LR6E~jK|j}G<3{KE(5^mYTk4vWIO?Y!>Av)E0+}#2H|ZK3K{C6bt&9?* z+;eHPTq5KmP7fbV2|~%fMh1<=G~2D1KTcn4dH$sSVnR_ozwwf|RBX2b=bi9Lr6$^q z6r9frGn+bN^BGLsSbOYkiQ)#*@mHRHW+tjmTP8&VwL%U<%`d}k31iu8*N$_GtSXn2 z>6Lr5b(-q=Ms_NH?h0MpUNmM4ZEFmSb}Ew=y&WkaTmYXD)V82z|8iVRq#?T9K*|4u z>M>Q6GNTr2Lj7w}RE-tkCQArw0<-&(#pB69kxNqWgunL3i7C3dW2z}U){r))kMv1}iN=>*d3y^?XKZn+I Mok_m={2+h)7u^}>0RR91 literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..ce87a9851a02f42132c9793b7ebc07d6cf5f2ffb GIT binary patch literal 163212 zcmeHQ2YejG)juKIV1uzg6G||}U?6mpMuH(=z_b*q6H|i?gq{Eaf*~<+AR#~!N+2Nw zLI@!tF|lO13R~{o*m5tbr`~%zNvFI0-v90GmA%{3-rZi2^!Dem_I77y-n{wGn>RCW z-q>tuwvo26V{PslQ(yX|uWM*@Ow|@BdJ|myWdAF1Wz+`*fS_ z{F80ADO1$nXI^2m?VoD1U3;zP`)Tz3OE%k#8J_rW)At27+nhO`_=lz0&VM}3h70*$ zINWCY!K_1UXVP!Vik_&?>5t7ubm*`AjA4p3A)V6k5BhZd-{Ic(z94I~Qnc`BrI13= zqNA09tRn;7BQBod9mk<~_=cZn9;#G-{zIjD>m5qf<{v24TW(Wow*N>en18r8je_~3 z_*wPV+tfG|7vB_Q9>($T9C7mJr78KDBk0{-O5uXB-tP++jNxZ^hd2fEM=DiYZsl(| z?cDp7vQ?9n(v@GM@C~JQ$D;vd0PT2&cZgHA>LL$~lqZ#~B(l!fm-eCeuRt=O|C zs_A;ZN4=qpm78u-<8Hm3`1F0Ht?XYE{>}H*^bF}#Zn~M{s&(zFLzIK*{hy8Ak5kIl zT&gq|zDePaN;%yZE*z)i(K{{=<0SA~e9wW(iukCLlAH@TpiaxzT&C8K7SHG}e}5VC zn)9PPOIKbP(f6e*zC!i&2-Wd)4!AE}@l|vAgD%2k;liUBuPSDb;%DA68qpr`+_=3& zmW~0RJ$dQnL8QMSXGql9NSv|!;qOW2=`Sm39?WUw5q`NHdD^~qpFi&quRIDWKfTl9 z1^y*@=EYPx%d7IWSCAaJUKegqN|v8XaRcSD`fWPDtK4{l?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