proxy.go 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121
  1. // Copyright 2016 fatedier, fatedier@gmail.com
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package config
  15. import (
  16. "fmt"
  17. "reflect"
  18. "strconv"
  19. "strings"
  20. "github.com/fatedier/frp/models/consts"
  21. "github.com/fatedier/frp/models/msg"
  22. "github.com/fatedier/frp/utils/util"
  23. ini "github.com/vaughan0/go-ini"
  24. )
  25. var (
  26. proxyConfTypeMap map[string]reflect.Type
  27. )
  28. func init() {
  29. proxyConfTypeMap = make(map[string]reflect.Type)
  30. proxyConfTypeMap[consts.TcpProxy] = reflect.TypeOf(TcpProxyConf{})
  31. proxyConfTypeMap[consts.TcpMuxProxy] = reflect.TypeOf(TcpMuxProxyConf{})
  32. proxyConfTypeMap[consts.UdpProxy] = reflect.TypeOf(UdpProxyConf{})
  33. proxyConfTypeMap[consts.HttpProxy] = reflect.TypeOf(HttpProxyConf{})
  34. proxyConfTypeMap[consts.HttpsProxy] = reflect.TypeOf(HttpsProxyConf{})
  35. proxyConfTypeMap[consts.StcpProxy] = reflect.TypeOf(StcpProxyConf{})
  36. proxyConfTypeMap[consts.XtcpProxy] = reflect.TypeOf(XtcpProxyConf{})
  37. }
  38. // NewConfByType creates a empty ProxyConf object by proxyType.
  39. // If proxyType isn't exist, return nil.
  40. func NewConfByType(proxyType string) ProxyConf {
  41. v, ok := proxyConfTypeMap[proxyType]
  42. if !ok {
  43. return nil
  44. }
  45. cfg := reflect.New(v).Interface().(ProxyConf)
  46. return cfg
  47. }
  48. type ProxyConf interface {
  49. GetBaseInfo() *BaseProxyConf
  50. UnmarshalFromMsg(pMsg *msg.NewProxy)
  51. UnmarshalFromIni(prefix string, name string, conf ini.Section) error
  52. MarshalToMsg(pMsg *msg.NewProxy)
  53. CheckForCli() error
  54. CheckForSvr(serverCfg ServerCommonConf) error
  55. Compare(conf ProxyConf) bool
  56. }
  57. func NewProxyConfFromMsg(pMsg *msg.NewProxy, serverCfg ServerCommonConf) (cfg ProxyConf, err error) {
  58. if pMsg.ProxyType == "" {
  59. pMsg.ProxyType = consts.TcpProxy
  60. }
  61. cfg = NewConfByType(pMsg.ProxyType)
  62. if cfg == nil {
  63. err = fmt.Errorf("proxy [%s] type [%s] error", pMsg.ProxyName, pMsg.ProxyType)
  64. return
  65. }
  66. cfg.UnmarshalFromMsg(pMsg)
  67. err = cfg.CheckForSvr(serverCfg)
  68. return
  69. }
  70. func NewProxyConfFromIni(prefix string, name string, section ini.Section) (cfg ProxyConf, err error) {
  71. proxyType := section["type"]
  72. if proxyType == "" {
  73. proxyType = consts.TcpProxy
  74. section["type"] = consts.TcpProxy
  75. }
  76. cfg = NewConfByType(proxyType)
  77. if cfg == nil {
  78. err = fmt.Errorf("proxy [%s] type [%s] error", name, proxyType)
  79. return
  80. }
  81. if err = cfg.UnmarshalFromIni(prefix, name, section); err != nil {
  82. return
  83. }
  84. if err = cfg.CheckForCli(); err != nil {
  85. return
  86. }
  87. return
  88. }
  89. // BaseProxyConf provides configuration info that is common to all proxy types.
  90. type BaseProxyConf struct {
  91. // ProxyName is the name of this proxy.
  92. ProxyName string `json:"proxy_name"`
  93. // ProxyType specifies the type of this proxy. Valid values include "tcp",
  94. // "udp", "http", "https", "stcp", and "xtcp". By default, this value is
  95. // "tcp".
  96. ProxyType string `json:"proxy_type"`
  97. // UseEncryption controls whether or not communication with the server will
  98. // be encrypted. Encryption is done using the tokens supplied in the server
  99. // and client configuration. By default, this value is false.
  100. UseEncryption bool `json:"use_encryption"`
  101. // UseCompression controls whether or not communication with the server
  102. // will be compressed. By default, this value is false.
  103. UseCompression bool `json:"use_compression"`
  104. // Group specifies which group the proxy is a part of. The server will use
  105. // this information to load balance proxies in the same group. If the value
  106. // is "", this proxy will not be in a group. By default, this value is "".
  107. Group string `json:"group"`
  108. // GroupKey specifies a group key, which should be the same among proxies
  109. // of the same group. By default, this value is "".
  110. GroupKey string `json:"group_key"`
  111. // ProxyProtocolVersion specifies which protocol version to use. Valid
  112. // values include "v1", "v2", and "". If the value is "", a protocol
  113. // version will be automatically selected. By default, this value is "".
  114. ProxyProtocolVersion string `json:"proxy_protocol_version"`
  115. // BandwidthLimit limit the proxy bandwidth
  116. // 0 means no limit
  117. BandwidthLimit BandwidthQuantity `json:"bandwidth_limit"`
  118. // meta info for each proxy
  119. Metas map[string]string `json:"metas"`
  120. LocalSvrConf
  121. HealthCheckConf
  122. }
  123. func (cfg *BaseProxyConf) GetBaseInfo() *BaseProxyConf {
  124. return cfg
  125. }
  126. func (cfg *BaseProxyConf) compare(cmp *BaseProxyConf) bool {
  127. if cfg.ProxyName != cmp.ProxyName ||
  128. cfg.ProxyType != cmp.ProxyType ||
  129. cfg.UseEncryption != cmp.UseEncryption ||
  130. cfg.UseCompression != cmp.UseCompression ||
  131. cfg.Group != cmp.Group ||
  132. cfg.GroupKey != cmp.GroupKey ||
  133. cfg.ProxyProtocolVersion != cmp.ProxyProtocolVersion ||
  134. !cfg.BandwidthLimit.Equal(&cmp.BandwidthLimit) ||
  135. !reflect.DeepEqual(cfg.Metas, cmp.Metas) {
  136. return false
  137. }
  138. if !cfg.LocalSvrConf.compare(&cmp.LocalSvrConf) {
  139. return false
  140. }
  141. if !cfg.HealthCheckConf.compare(&cmp.HealthCheckConf) {
  142. return false
  143. }
  144. return true
  145. }
  146. func (cfg *BaseProxyConf) UnmarshalFromMsg(pMsg *msg.NewProxy) {
  147. cfg.ProxyName = pMsg.ProxyName
  148. cfg.ProxyType = pMsg.ProxyType
  149. cfg.UseEncryption = pMsg.UseEncryption
  150. cfg.UseCompression = pMsg.UseCompression
  151. cfg.Group = pMsg.Group
  152. cfg.GroupKey = pMsg.GroupKey
  153. cfg.Metas = pMsg.Metas
  154. }
  155. func (cfg *BaseProxyConf) UnmarshalFromIni(prefix string, name string, section ini.Section) error {
  156. var (
  157. tmpStr string
  158. ok bool
  159. err error
  160. )
  161. cfg.ProxyName = prefix + name
  162. cfg.ProxyType = section["type"]
  163. tmpStr, ok = section["use_encryption"]
  164. if ok && tmpStr == "true" {
  165. cfg.UseEncryption = true
  166. }
  167. tmpStr, ok = section["use_compression"]
  168. if ok && tmpStr == "true" {
  169. cfg.UseCompression = true
  170. }
  171. cfg.Group = section["group"]
  172. cfg.GroupKey = section["group_key"]
  173. cfg.ProxyProtocolVersion = section["proxy_protocol_version"]
  174. if cfg.BandwidthLimit, err = NewBandwidthQuantity(section["bandwidth_limit"]); err != nil {
  175. return err
  176. }
  177. if err = cfg.LocalSvrConf.UnmarshalFromIni(prefix, name, section); err != nil {
  178. return err
  179. }
  180. if err = cfg.HealthCheckConf.UnmarshalFromIni(prefix, name, section); err != nil {
  181. return err
  182. }
  183. if cfg.HealthCheckType == "tcp" && cfg.Plugin == "" {
  184. cfg.HealthCheckAddr = cfg.LocalIp + fmt.Sprintf(":%d", cfg.LocalPort)
  185. }
  186. if cfg.HealthCheckType == "http" && cfg.Plugin == "" && cfg.HealthCheckUrl != "" {
  187. s := fmt.Sprintf("http://%s:%d", cfg.LocalIp, cfg.LocalPort)
  188. if !strings.HasPrefix(cfg.HealthCheckUrl, "/") {
  189. s += "/"
  190. }
  191. cfg.HealthCheckUrl = s + cfg.HealthCheckUrl
  192. }
  193. cfg.Metas = make(map[string]string)
  194. for k, v := range section {
  195. if strings.HasPrefix(k, "meta_") {
  196. cfg.Metas[strings.TrimPrefix(k, "meta_")] = v
  197. }
  198. }
  199. return nil
  200. }
  201. func (cfg *BaseProxyConf) MarshalToMsg(pMsg *msg.NewProxy) {
  202. pMsg.ProxyName = cfg.ProxyName
  203. pMsg.ProxyType = cfg.ProxyType
  204. pMsg.UseEncryption = cfg.UseEncryption
  205. pMsg.UseCompression = cfg.UseCompression
  206. pMsg.Group = cfg.Group
  207. pMsg.GroupKey = cfg.GroupKey
  208. pMsg.Metas = cfg.Metas
  209. }
  210. func (cfg *BaseProxyConf) checkForCli() (err error) {
  211. if cfg.ProxyProtocolVersion != "" {
  212. if cfg.ProxyProtocolVersion != "v1" && cfg.ProxyProtocolVersion != "v2" {
  213. return fmt.Errorf("no support proxy protocol version: %s", cfg.ProxyProtocolVersion)
  214. }
  215. }
  216. if err = cfg.LocalSvrConf.checkForCli(); err != nil {
  217. return
  218. }
  219. if err = cfg.HealthCheckConf.checkForCli(); err != nil {
  220. return
  221. }
  222. return nil
  223. }
  224. // Bind info
  225. type BindInfoConf struct {
  226. RemotePort int `json:"remote_port"`
  227. }
  228. func (cfg *BindInfoConf) compare(cmp *BindInfoConf) bool {
  229. if cfg.RemotePort != cmp.RemotePort {
  230. return false
  231. }
  232. return true
  233. }
  234. func (cfg *BindInfoConf) UnmarshalFromMsg(pMsg *msg.NewProxy) {
  235. cfg.RemotePort = pMsg.RemotePort
  236. }
  237. func (cfg *BindInfoConf) UnmarshalFromIni(prefix string, name string, section ini.Section) (err error) {
  238. var (
  239. tmpStr string
  240. ok bool
  241. v int64
  242. )
  243. if tmpStr, ok = section["remote_port"]; ok {
  244. if v, err = strconv.ParseInt(tmpStr, 10, 64); err != nil {
  245. return fmt.Errorf("Parse conf error: proxy [%s] remote_port error", name)
  246. } else {
  247. cfg.RemotePort = int(v)
  248. }
  249. } else {
  250. return fmt.Errorf("Parse conf error: proxy [%s] remote_port not found", name)
  251. }
  252. return nil
  253. }
  254. func (cfg *BindInfoConf) MarshalToMsg(pMsg *msg.NewProxy) {
  255. pMsg.RemotePort = cfg.RemotePort
  256. }
  257. // Domain info
  258. type DomainConf struct {
  259. CustomDomains []string `json:"custom_domains"`
  260. SubDomain string `json:"sub_domain"`
  261. }
  262. func (cfg *DomainConf) compare(cmp *DomainConf) bool {
  263. if strings.Join(cfg.CustomDomains, " ") != strings.Join(cmp.CustomDomains, " ") ||
  264. cfg.SubDomain != cmp.SubDomain {
  265. return false
  266. }
  267. return true
  268. }
  269. func (cfg *DomainConf) UnmarshalFromMsg(pMsg *msg.NewProxy) {
  270. cfg.CustomDomains = pMsg.CustomDomains
  271. cfg.SubDomain = pMsg.SubDomain
  272. }
  273. func (cfg *DomainConf) UnmarshalFromIni(prefix string, name string, section ini.Section) (err error) {
  274. var (
  275. tmpStr string
  276. ok bool
  277. )
  278. if tmpStr, ok = section["custom_domains"]; ok {
  279. cfg.CustomDomains = strings.Split(tmpStr, ",")
  280. for i, domain := range cfg.CustomDomains {
  281. cfg.CustomDomains[i] = strings.ToLower(strings.TrimSpace(domain))
  282. }
  283. }
  284. if tmpStr, ok = section["subdomain"]; ok {
  285. cfg.SubDomain = tmpStr
  286. }
  287. return
  288. }
  289. func (cfg *DomainConf) MarshalToMsg(pMsg *msg.NewProxy) {
  290. pMsg.CustomDomains = cfg.CustomDomains
  291. pMsg.SubDomain = cfg.SubDomain
  292. }
  293. func (cfg *DomainConf) check() (err error) {
  294. if len(cfg.CustomDomains) == 0 && cfg.SubDomain == "" {
  295. err = fmt.Errorf("custom_domains and subdomain should set at least one of them")
  296. return
  297. }
  298. return
  299. }
  300. func (cfg *DomainConf) checkForCli() (err error) {
  301. if err = cfg.check(); err != nil {
  302. return
  303. }
  304. return
  305. }
  306. func (cfg *DomainConf) checkForSvr(serverCfg ServerCommonConf) (err error) {
  307. if err = cfg.check(); err != nil {
  308. return
  309. }
  310. for _, domain := range cfg.CustomDomains {
  311. if serverCfg.SubDomainHost != "" && len(strings.Split(serverCfg.SubDomainHost, ".")) < len(strings.Split(domain, ".")) {
  312. if strings.Contains(domain, serverCfg.SubDomainHost) {
  313. return fmt.Errorf("custom domain [%s] should not belong to subdomain_host [%s]", domain, serverCfg.SubDomainHost)
  314. }
  315. }
  316. }
  317. if cfg.SubDomain != "" {
  318. if serverCfg.SubDomainHost == "" {
  319. return fmt.Errorf("subdomain is not supported because this feature is not enabled in remote frps")
  320. }
  321. if strings.Contains(cfg.SubDomain, ".") || strings.Contains(cfg.SubDomain, "*") {
  322. return fmt.Errorf("'.' and '*' is not supported in subdomain")
  323. }
  324. }
  325. return
  326. }
  327. // LocalSvrConf configures what location the client will proxy to, or what
  328. // plugin will be used.
  329. type LocalSvrConf struct {
  330. // LocalIp specifies the IP address or host name to proxy to.
  331. LocalIp string `json:"local_ip"`
  332. // LocalPort specifies the port to proxy to.
  333. LocalPort int `json:"local_port"`
  334. // Plugin specifies what plugin should be used for proxying. If this value
  335. // is set, the LocalIp and LocalPort values will be ignored. By default,
  336. // this value is "".
  337. Plugin string `json:"plugin"`
  338. // PluginParams specify parameters to be passed to the plugin, if one is
  339. // being used. By default, this value is an empty map.
  340. PluginParams map[string]string `json:"plugin_params"`
  341. }
  342. func (cfg *LocalSvrConf) compare(cmp *LocalSvrConf) bool {
  343. if cfg.LocalIp != cmp.LocalIp ||
  344. cfg.LocalPort != cmp.LocalPort {
  345. return false
  346. }
  347. if cfg.Plugin != cmp.Plugin ||
  348. len(cfg.PluginParams) != len(cmp.PluginParams) {
  349. return false
  350. }
  351. for k, v := range cfg.PluginParams {
  352. value, ok := cmp.PluginParams[k]
  353. if !ok || v != value {
  354. return false
  355. }
  356. }
  357. return true
  358. }
  359. func (cfg *LocalSvrConf) UnmarshalFromIni(prefix string, name string, section ini.Section) (err error) {
  360. cfg.Plugin = section["plugin"]
  361. cfg.PluginParams = make(map[string]string)
  362. if cfg.Plugin != "" {
  363. // get params begin with "plugin_"
  364. for k, v := range section {
  365. if strings.HasPrefix(k, "plugin_") {
  366. cfg.PluginParams[k] = v
  367. }
  368. }
  369. } else {
  370. if cfg.LocalIp = section["local_ip"]; cfg.LocalIp == "" {
  371. cfg.LocalIp = "127.0.0.1"
  372. }
  373. if tmpStr, ok := section["local_port"]; ok {
  374. if cfg.LocalPort, err = strconv.Atoi(tmpStr); err != nil {
  375. return fmt.Errorf("Parse conf error: proxy [%s] local_port error", name)
  376. }
  377. } else {
  378. return fmt.Errorf("Parse conf error: proxy [%s] local_port not found", name)
  379. }
  380. }
  381. return
  382. }
  383. func (cfg *LocalSvrConf) checkForCli() (err error) {
  384. if cfg.Plugin == "" {
  385. if cfg.LocalIp == "" {
  386. err = fmt.Errorf("local ip or plugin is required")
  387. return
  388. }
  389. if cfg.LocalPort <= 0 {
  390. err = fmt.Errorf("error local_port")
  391. return
  392. }
  393. }
  394. return
  395. }
  396. // HealthCheckConf configures health checking. This can be useful for load
  397. // balancing purposes to detect and remove proxies to failing services.
  398. type HealthCheckConf struct {
  399. // HealthCheckType specifies what protocol to use for health checking.
  400. // Valid values include "tcp", "http", and "". If this value is "", health
  401. // checking will not be performed. By default, this value is "".
  402. //
  403. // If the type is "tcp", a connection will be attempted to the target
  404. // server. If a connection cannot be established, the health check fails.
  405. //
  406. // If the type is "http", a GET request will be made to the endpoint
  407. // specified by HealthCheckUrl. If the response is not a 200, the health
  408. // check fails.
  409. HealthCheckType string `json:"health_check_type"` // tcp | http
  410. // HealthCheckTimeoutS specifies the number of seconds to wait for a health
  411. // check attempt to connect. If the timeout is reached, this counts as a
  412. // health check failure. By default, this value is 3.
  413. HealthCheckTimeoutS int `json:"health_check_timeout_s"`
  414. // HealthCheckMaxFailed specifies the number of allowed failures before the
  415. // proxy is stopped. By default, this value is 1.
  416. HealthCheckMaxFailed int `json:"health_check_max_failed"`
  417. // HealthCheckIntervalS specifies the time in seconds between health
  418. // checks. By default, this value is 10.
  419. HealthCheckIntervalS int `json:"health_check_interval_s"`
  420. // HealthCheckUrl specifies the address to send health checks to if the
  421. // health check type is "http".
  422. HealthCheckUrl string `json:"health_check_url"`
  423. // HealthCheckAddr specifies the address to connect to if the health check
  424. // type is "tcp".
  425. HealthCheckAddr string `json:"-"`
  426. }
  427. func (cfg *HealthCheckConf) compare(cmp *HealthCheckConf) bool {
  428. if cfg.HealthCheckType != cmp.HealthCheckType ||
  429. cfg.HealthCheckTimeoutS != cmp.HealthCheckTimeoutS ||
  430. cfg.HealthCheckMaxFailed != cmp.HealthCheckMaxFailed ||
  431. cfg.HealthCheckIntervalS != cmp.HealthCheckIntervalS ||
  432. cfg.HealthCheckUrl != cmp.HealthCheckUrl {
  433. return false
  434. }
  435. return true
  436. }
  437. func (cfg *HealthCheckConf) UnmarshalFromIni(prefix string, name string, section ini.Section) (err error) {
  438. cfg.HealthCheckType = section["health_check_type"]
  439. cfg.HealthCheckUrl = section["health_check_url"]
  440. if tmpStr, ok := section["health_check_timeout_s"]; ok {
  441. if cfg.HealthCheckTimeoutS, err = strconv.Atoi(tmpStr); err != nil {
  442. return fmt.Errorf("Parse conf error: proxy [%s] health_check_timeout_s error", name)
  443. }
  444. }
  445. if tmpStr, ok := section["health_check_max_failed"]; ok {
  446. if cfg.HealthCheckMaxFailed, err = strconv.Atoi(tmpStr); err != nil {
  447. return fmt.Errorf("Parse conf error: proxy [%s] health_check_max_failed error", name)
  448. }
  449. }
  450. if tmpStr, ok := section["health_check_interval_s"]; ok {
  451. if cfg.HealthCheckIntervalS, err = strconv.Atoi(tmpStr); err != nil {
  452. return fmt.Errorf("Parse conf error: proxy [%s] health_check_interval_s error", name)
  453. }
  454. }
  455. return
  456. }
  457. func (cfg *HealthCheckConf) checkForCli() error {
  458. if cfg.HealthCheckType != "" && cfg.HealthCheckType != "tcp" && cfg.HealthCheckType != "http" {
  459. return fmt.Errorf("unsupport health check type")
  460. }
  461. if cfg.HealthCheckType != "" {
  462. if cfg.HealthCheckType == "http" && cfg.HealthCheckUrl == "" {
  463. return fmt.Errorf("health_check_url is required for health check type 'http'")
  464. }
  465. }
  466. return nil
  467. }
  468. // TCP
  469. type TcpProxyConf struct {
  470. BaseProxyConf
  471. BindInfoConf
  472. }
  473. func (cfg *TcpProxyConf) Compare(cmp ProxyConf) bool {
  474. cmpConf, ok := cmp.(*TcpProxyConf)
  475. if !ok {
  476. return false
  477. }
  478. if !cfg.BaseProxyConf.compare(&cmpConf.BaseProxyConf) ||
  479. !cfg.BindInfoConf.compare(&cmpConf.BindInfoConf) {
  480. return false
  481. }
  482. return true
  483. }
  484. func (cfg *TcpProxyConf) UnmarshalFromMsg(pMsg *msg.NewProxy) {
  485. cfg.BaseProxyConf.UnmarshalFromMsg(pMsg)
  486. cfg.BindInfoConf.UnmarshalFromMsg(pMsg)
  487. }
  488. func (cfg *TcpProxyConf) UnmarshalFromIni(prefix string, name string, section ini.Section) (err error) {
  489. if err = cfg.BaseProxyConf.UnmarshalFromIni(prefix, name, section); err != nil {
  490. return
  491. }
  492. if err = cfg.BindInfoConf.UnmarshalFromIni(prefix, name, section); err != nil {
  493. return
  494. }
  495. return
  496. }
  497. func (cfg *TcpProxyConf) MarshalToMsg(pMsg *msg.NewProxy) {
  498. cfg.BaseProxyConf.MarshalToMsg(pMsg)
  499. cfg.BindInfoConf.MarshalToMsg(pMsg)
  500. }
  501. func (cfg *TcpProxyConf) CheckForCli() (err error) {
  502. if err = cfg.BaseProxyConf.checkForCli(); err != nil {
  503. return err
  504. }
  505. return
  506. }
  507. func (cfg *TcpProxyConf) CheckForSvr(serverCfg ServerCommonConf) error { return nil }
  508. // TCP Multiplexer
  509. type TcpMuxProxyConf struct {
  510. BaseProxyConf
  511. DomainConf
  512. Multiplexer string `json:"multiplexer"`
  513. }
  514. func (cfg *TcpMuxProxyConf) Compare(cmp ProxyConf) bool {
  515. cmpConf, ok := cmp.(*TcpMuxProxyConf)
  516. if !ok {
  517. return false
  518. }
  519. if !cfg.BaseProxyConf.compare(&cmpConf.BaseProxyConf) ||
  520. !cfg.DomainConf.compare(&cmpConf.DomainConf) ||
  521. cfg.Multiplexer != cmpConf.Multiplexer {
  522. return false
  523. }
  524. return true
  525. }
  526. func (cfg *TcpMuxProxyConf) UnmarshalFromMsg(pMsg *msg.NewProxy) {
  527. cfg.BaseProxyConf.UnmarshalFromMsg(pMsg)
  528. cfg.DomainConf.UnmarshalFromMsg(pMsg)
  529. cfg.Multiplexer = pMsg.Multiplexer
  530. }
  531. func (cfg *TcpMuxProxyConf) UnmarshalFromIni(prefix string, name string, section ini.Section) (err error) {
  532. if err = cfg.BaseProxyConf.UnmarshalFromIni(prefix, name, section); err != nil {
  533. return
  534. }
  535. if err = cfg.DomainConf.UnmarshalFromIni(prefix, name, section); err != nil {
  536. return
  537. }
  538. cfg.Multiplexer = section["multiplexer"]
  539. if cfg.Multiplexer != consts.HttpConnectTcpMultiplexer {
  540. return fmt.Errorf("parse conf error: proxy [%s] incorrect multiplexer [%s]", name, cfg.Multiplexer)
  541. }
  542. return
  543. }
  544. func (cfg *TcpMuxProxyConf) MarshalToMsg(pMsg *msg.NewProxy) {
  545. cfg.BaseProxyConf.MarshalToMsg(pMsg)
  546. cfg.DomainConf.MarshalToMsg(pMsg)
  547. pMsg.Multiplexer = cfg.Multiplexer
  548. }
  549. func (cfg *TcpMuxProxyConf) CheckForCli() (err error) {
  550. if err = cfg.BaseProxyConf.checkForCli(); err != nil {
  551. return err
  552. }
  553. if err = cfg.DomainConf.checkForCli(); err != nil {
  554. return err
  555. }
  556. if cfg.Multiplexer != consts.HttpConnectTcpMultiplexer {
  557. return fmt.Errorf("parse conf error: incorrect multiplexer [%s]", cfg.Multiplexer)
  558. }
  559. return
  560. }
  561. func (cfg *TcpMuxProxyConf) CheckForSvr(serverCfg ServerCommonConf) (err error) {
  562. if cfg.Multiplexer != consts.HttpConnectTcpMultiplexer {
  563. return fmt.Errorf("proxy [%s] incorrect multiplexer [%s]", cfg.ProxyName, cfg.Multiplexer)
  564. }
  565. if cfg.Multiplexer == consts.HttpConnectTcpMultiplexer && serverCfg.TcpMuxHttpConnectPort == 0 {
  566. return fmt.Errorf("proxy [%s] type [tcpmux] with multiplexer [httpconnect] requires tcpmux_httpconnect_port configuration", cfg.ProxyName)
  567. }
  568. if err = cfg.DomainConf.checkForSvr(serverCfg); err != nil {
  569. err = fmt.Errorf("proxy [%s] domain conf check error: %v", cfg.ProxyName, err)
  570. return
  571. }
  572. return
  573. }
  574. // UDP
  575. type UdpProxyConf struct {
  576. BaseProxyConf
  577. BindInfoConf
  578. }
  579. func (cfg *UdpProxyConf) Compare(cmp ProxyConf) bool {
  580. cmpConf, ok := cmp.(*UdpProxyConf)
  581. if !ok {
  582. return false
  583. }
  584. if !cfg.BaseProxyConf.compare(&cmpConf.BaseProxyConf) ||
  585. !cfg.BindInfoConf.compare(&cmpConf.BindInfoConf) {
  586. return false
  587. }
  588. return true
  589. }
  590. func (cfg *UdpProxyConf) UnmarshalFromMsg(pMsg *msg.NewProxy) {
  591. cfg.BaseProxyConf.UnmarshalFromMsg(pMsg)
  592. cfg.BindInfoConf.UnmarshalFromMsg(pMsg)
  593. }
  594. func (cfg *UdpProxyConf) UnmarshalFromIni(prefix string, name string, section ini.Section) (err error) {
  595. if err = cfg.BaseProxyConf.UnmarshalFromIni(prefix, name, section); err != nil {
  596. return
  597. }
  598. if err = cfg.BindInfoConf.UnmarshalFromIni(prefix, name, section); err != nil {
  599. return
  600. }
  601. return
  602. }
  603. func (cfg *UdpProxyConf) MarshalToMsg(pMsg *msg.NewProxy) {
  604. cfg.BaseProxyConf.MarshalToMsg(pMsg)
  605. cfg.BindInfoConf.MarshalToMsg(pMsg)
  606. }
  607. func (cfg *UdpProxyConf) CheckForCli() (err error) {
  608. if err = cfg.BaseProxyConf.checkForCli(); err != nil {
  609. return
  610. }
  611. return
  612. }
  613. func (cfg *UdpProxyConf) CheckForSvr(serverCfg ServerCommonConf) error { return nil }
  614. // HTTP
  615. type HttpProxyConf struct {
  616. BaseProxyConf
  617. DomainConf
  618. Locations []string `json:"locations"`
  619. HttpUser string `json:"http_user"`
  620. HttpPwd string `json:"http_pwd"`
  621. HostHeaderRewrite string `json:"host_header_rewrite"`
  622. Headers map[string]string `json:"headers"`
  623. }
  624. func (cfg *HttpProxyConf) Compare(cmp ProxyConf) bool {
  625. cmpConf, ok := cmp.(*HttpProxyConf)
  626. if !ok {
  627. return false
  628. }
  629. if !cfg.BaseProxyConf.compare(&cmpConf.BaseProxyConf) ||
  630. !cfg.DomainConf.compare(&cmpConf.DomainConf) ||
  631. strings.Join(cfg.Locations, " ") != strings.Join(cmpConf.Locations, " ") ||
  632. cfg.HostHeaderRewrite != cmpConf.HostHeaderRewrite ||
  633. cfg.HttpUser != cmpConf.HttpUser ||
  634. cfg.HttpPwd != cmpConf.HttpPwd ||
  635. len(cfg.Headers) != len(cmpConf.Headers) {
  636. return false
  637. }
  638. for k, v := range cfg.Headers {
  639. if v2, ok := cmpConf.Headers[k]; !ok {
  640. return false
  641. } else {
  642. if v != v2 {
  643. return false
  644. }
  645. }
  646. }
  647. return true
  648. }
  649. func (cfg *HttpProxyConf) UnmarshalFromMsg(pMsg *msg.NewProxy) {
  650. cfg.BaseProxyConf.UnmarshalFromMsg(pMsg)
  651. cfg.DomainConf.UnmarshalFromMsg(pMsg)
  652. cfg.Locations = pMsg.Locations
  653. cfg.HostHeaderRewrite = pMsg.HostHeaderRewrite
  654. cfg.HttpUser = pMsg.HttpUser
  655. cfg.HttpPwd = pMsg.HttpPwd
  656. cfg.Headers = pMsg.Headers
  657. }
  658. func (cfg *HttpProxyConf) UnmarshalFromIni(prefix string, name string, section ini.Section) (err error) {
  659. if err = cfg.BaseProxyConf.UnmarshalFromIni(prefix, name, section); err != nil {
  660. return
  661. }
  662. if err = cfg.DomainConf.UnmarshalFromIni(prefix, name, section); err != nil {
  663. return
  664. }
  665. var (
  666. tmpStr string
  667. ok bool
  668. )
  669. if tmpStr, ok = section["locations"]; ok {
  670. cfg.Locations = strings.Split(tmpStr, ",")
  671. } else {
  672. cfg.Locations = []string{""}
  673. }
  674. cfg.HostHeaderRewrite = section["host_header_rewrite"]
  675. cfg.HttpUser = section["http_user"]
  676. cfg.HttpPwd = section["http_pwd"]
  677. cfg.Headers = make(map[string]string)
  678. for k, v := range section {
  679. if strings.HasPrefix(k, "header_") {
  680. cfg.Headers[strings.TrimPrefix(k, "header_")] = v
  681. }
  682. }
  683. return
  684. }
  685. func (cfg *HttpProxyConf) MarshalToMsg(pMsg *msg.NewProxy) {
  686. cfg.BaseProxyConf.MarshalToMsg(pMsg)
  687. cfg.DomainConf.MarshalToMsg(pMsg)
  688. pMsg.Locations = cfg.Locations
  689. pMsg.HostHeaderRewrite = cfg.HostHeaderRewrite
  690. pMsg.HttpUser = cfg.HttpUser
  691. pMsg.HttpPwd = cfg.HttpPwd
  692. pMsg.Headers = cfg.Headers
  693. }
  694. func (cfg *HttpProxyConf) CheckForCli() (err error) {
  695. if err = cfg.BaseProxyConf.checkForCli(); err != nil {
  696. return
  697. }
  698. if err = cfg.DomainConf.checkForCli(); err != nil {
  699. return
  700. }
  701. return
  702. }
  703. func (cfg *HttpProxyConf) CheckForSvr(serverCfg ServerCommonConf) (err error) {
  704. if serverCfg.VhostHttpPort == 0 {
  705. return fmt.Errorf("type [http] not support when vhost_http_port is not set")
  706. }
  707. if err = cfg.DomainConf.checkForSvr(serverCfg); err != nil {
  708. err = fmt.Errorf("proxy [%s] domain conf check error: %v", cfg.ProxyName, err)
  709. return
  710. }
  711. return
  712. }
  713. // HTTPS
  714. type HttpsProxyConf struct {
  715. BaseProxyConf
  716. DomainConf
  717. }
  718. func (cfg *HttpsProxyConf) Compare(cmp ProxyConf) bool {
  719. cmpConf, ok := cmp.(*HttpsProxyConf)
  720. if !ok {
  721. return false
  722. }
  723. if !cfg.BaseProxyConf.compare(&cmpConf.BaseProxyConf) ||
  724. !cfg.DomainConf.compare(&cmpConf.DomainConf) {
  725. return false
  726. }
  727. return true
  728. }
  729. func (cfg *HttpsProxyConf) UnmarshalFromMsg(pMsg *msg.NewProxy) {
  730. cfg.BaseProxyConf.UnmarshalFromMsg(pMsg)
  731. cfg.DomainConf.UnmarshalFromMsg(pMsg)
  732. }
  733. func (cfg *HttpsProxyConf) UnmarshalFromIni(prefix string, name string, section ini.Section) (err error) {
  734. if err = cfg.BaseProxyConf.UnmarshalFromIni(prefix, name, section); err != nil {
  735. return
  736. }
  737. if err = cfg.DomainConf.UnmarshalFromIni(prefix, name, section); err != nil {
  738. return
  739. }
  740. return
  741. }
  742. func (cfg *HttpsProxyConf) MarshalToMsg(pMsg *msg.NewProxy) {
  743. cfg.BaseProxyConf.MarshalToMsg(pMsg)
  744. cfg.DomainConf.MarshalToMsg(pMsg)
  745. }
  746. func (cfg *HttpsProxyConf) CheckForCli() (err error) {
  747. if err = cfg.BaseProxyConf.checkForCli(); err != nil {
  748. return
  749. }
  750. if err = cfg.DomainConf.checkForCli(); err != nil {
  751. return
  752. }
  753. return
  754. }
  755. func (cfg *HttpsProxyConf) CheckForSvr(serverCfg ServerCommonConf) (err error) {
  756. if serverCfg.VhostHttpsPort == 0 {
  757. return fmt.Errorf("type [https] not support when vhost_https_port is not set")
  758. }
  759. if err = cfg.DomainConf.checkForSvr(serverCfg); err != nil {
  760. err = fmt.Errorf("proxy [%s] domain conf check error: %v", cfg.ProxyName, err)
  761. return
  762. }
  763. return
  764. }
  765. // STCP
  766. type StcpProxyConf struct {
  767. BaseProxyConf
  768. Role string `json:"role"`
  769. Sk string `json:"sk"`
  770. }
  771. func (cfg *StcpProxyConf) Compare(cmp ProxyConf) bool {
  772. cmpConf, ok := cmp.(*StcpProxyConf)
  773. if !ok {
  774. return false
  775. }
  776. if !cfg.BaseProxyConf.compare(&cmpConf.BaseProxyConf) ||
  777. cfg.Role != cmpConf.Role ||
  778. cfg.Sk != cmpConf.Sk {
  779. return false
  780. }
  781. return true
  782. }
  783. // Only for role server.
  784. func (cfg *StcpProxyConf) UnmarshalFromMsg(pMsg *msg.NewProxy) {
  785. cfg.BaseProxyConf.UnmarshalFromMsg(pMsg)
  786. cfg.Sk = pMsg.Sk
  787. }
  788. func (cfg *StcpProxyConf) UnmarshalFromIni(prefix string, name string, section ini.Section) (err error) {
  789. if err = cfg.BaseProxyConf.UnmarshalFromIni(prefix, name, section); err != nil {
  790. return
  791. }
  792. cfg.Role = section["role"]
  793. if cfg.Role != "server" {
  794. return fmt.Errorf("Parse conf error: proxy [%s] incorrect role [%s]", name, cfg.Role)
  795. }
  796. cfg.Sk = section["sk"]
  797. if err = cfg.LocalSvrConf.UnmarshalFromIni(prefix, name, section); err != nil {
  798. return
  799. }
  800. return
  801. }
  802. func (cfg *StcpProxyConf) MarshalToMsg(pMsg *msg.NewProxy) {
  803. cfg.BaseProxyConf.MarshalToMsg(pMsg)
  804. pMsg.Sk = cfg.Sk
  805. }
  806. func (cfg *StcpProxyConf) CheckForCli() (err error) {
  807. if err = cfg.BaseProxyConf.checkForCli(); err != nil {
  808. return
  809. }
  810. if cfg.Role != "server" {
  811. err = fmt.Errorf("role should be 'server'")
  812. return
  813. }
  814. return
  815. }
  816. func (cfg *StcpProxyConf) CheckForSvr(serverCfg ServerCommonConf) (err error) {
  817. return
  818. }
  819. // XTCP
  820. type XtcpProxyConf struct {
  821. BaseProxyConf
  822. Role string `json:"role"`
  823. Sk string `json:"sk"`
  824. }
  825. func (cfg *XtcpProxyConf) Compare(cmp ProxyConf) bool {
  826. cmpConf, ok := cmp.(*XtcpProxyConf)
  827. if !ok {
  828. return false
  829. }
  830. if !cfg.BaseProxyConf.compare(&cmpConf.BaseProxyConf) ||
  831. !cfg.LocalSvrConf.compare(&cmpConf.LocalSvrConf) ||
  832. cfg.Role != cmpConf.Role ||
  833. cfg.Sk != cmpConf.Sk {
  834. return false
  835. }
  836. return true
  837. }
  838. // Only for role server.
  839. func (cfg *XtcpProxyConf) UnmarshalFromMsg(pMsg *msg.NewProxy) {
  840. cfg.BaseProxyConf.UnmarshalFromMsg(pMsg)
  841. cfg.Sk = pMsg.Sk
  842. }
  843. func (cfg *XtcpProxyConf) UnmarshalFromIni(prefix string, name string, section ini.Section) (err error) {
  844. if err = cfg.BaseProxyConf.UnmarshalFromIni(prefix, name, section); err != nil {
  845. return
  846. }
  847. cfg.Role = section["role"]
  848. if cfg.Role != "server" {
  849. return fmt.Errorf("Parse conf error: proxy [%s] incorrect role [%s]", name, cfg.Role)
  850. }
  851. cfg.Sk = section["sk"]
  852. if err = cfg.LocalSvrConf.UnmarshalFromIni(prefix, name, section); err != nil {
  853. return
  854. }
  855. return
  856. }
  857. func (cfg *XtcpProxyConf) MarshalToMsg(pMsg *msg.NewProxy) {
  858. cfg.BaseProxyConf.MarshalToMsg(pMsg)
  859. pMsg.Sk = cfg.Sk
  860. }
  861. func (cfg *XtcpProxyConf) CheckForCli() (err error) {
  862. if err = cfg.BaseProxyConf.checkForCli(); err != nil {
  863. return
  864. }
  865. if cfg.Role != "server" {
  866. err = fmt.Errorf("role should be 'server'")
  867. return
  868. }
  869. return
  870. }
  871. func (cfg *XtcpProxyConf) CheckForSvr(serverCfg ServerCommonConf) (err error) {
  872. return
  873. }
  874. func ParseRangeSection(name string, section ini.Section) (sections map[string]ini.Section, err error) {
  875. localPorts, errRet := util.ParseRangeNumbers(section["local_port"])
  876. if errRet != nil {
  877. err = fmt.Errorf("Parse conf error: range section [%s] local_port invalid, %v", name, errRet)
  878. return
  879. }
  880. remotePorts, errRet := util.ParseRangeNumbers(section["remote_port"])
  881. if errRet != nil {
  882. err = fmt.Errorf("Parse conf error: range section [%s] remote_port invalid, %v", name, errRet)
  883. return
  884. }
  885. if len(localPorts) != len(remotePorts) {
  886. err = fmt.Errorf("Parse conf error: range section [%s] local ports number should be same with remote ports number", name)
  887. return
  888. }
  889. if len(localPorts) == 0 {
  890. err = fmt.Errorf("Parse conf error: range section [%s] local_port and remote_port is necessary", name)
  891. return
  892. }
  893. sections = make(map[string]ini.Section)
  894. for i, port := range localPorts {
  895. subName := fmt.Sprintf("%s_%d", name, i)
  896. subSection := copySection(section)
  897. subSection["local_port"] = fmt.Sprintf("%d", port)
  898. subSection["remote_port"] = fmt.Sprintf("%d", remotePorts[i])
  899. sections[subName] = subSection
  900. }
  901. return
  902. }
  903. // if len(startProxy) is 0, start all
  904. // otherwise just start proxies in startProxy map
  905. func LoadAllConfFromIni(prefix string, content string, startProxy map[string]struct{}) (
  906. proxyConfs map[string]ProxyConf, visitorConfs map[string]VisitorConf, err error) {
  907. conf, errRet := ini.Load(strings.NewReader(content))
  908. if errRet != nil {
  909. err = errRet
  910. return
  911. }
  912. if prefix != "" {
  913. prefix += "."
  914. }
  915. startAll := true
  916. if len(startProxy) > 0 {
  917. startAll = false
  918. }
  919. proxyConfs = make(map[string]ProxyConf)
  920. visitorConfs = make(map[string]VisitorConf)
  921. for name, section := range conf {
  922. if name == "common" {
  923. continue
  924. }
  925. _, shouldStart := startProxy[name]
  926. if !startAll && !shouldStart {
  927. continue
  928. }
  929. subSections := make(map[string]ini.Section)
  930. if strings.HasPrefix(name, "range:") {
  931. // range section
  932. rangePrefix := strings.TrimSpace(strings.TrimPrefix(name, "range:"))
  933. subSections, err = ParseRangeSection(rangePrefix, section)
  934. if err != nil {
  935. return
  936. }
  937. } else {
  938. subSections[name] = section
  939. }
  940. for subName, subSection := range subSections {
  941. if subSection["role"] == "" {
  942. subSection["role"] = "server"
  943. }
  944. role := subSection["role"]
  945. if role == "server" {
  946. cfg, errRet := NewProxyConfFromIni(prefix, subName, subSection)
  947. if errRet != nil {
  948. err = errRet
  949. return
  950. }
  951. proxyConfs[prefix+subName] = cfg
  952. } else if role == "visitor" {
  953. cfg, errRet := NewVisitorConfFromIni(prefix, subName, subSection)
  954. if errRet != nil {
  955. err = errRet
  956. return
  957. }
  958. visitorConfs[prefix+subName] = cfg
  959. } else {
  960. err = fmt.Errorf("role should be 'server' or 'visitor'")
  961. return
  962. }
  963. }
  964. }
  965. return
  966. }
  967. func copySection(section ini.Section) (out ini.Section) {
  968. out = make(ini.Section)
  969. for k, v := range section {
  970. out[k] = v
  971. }
  972. return
  973. }