api_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. package guerrilla
  2. import (
  3. "bufio"
  4. "fmt"
  5. "github.com/flashmob/go-guerrilla/backends"
  6. "github.com/flashmob/go-guerrilla/log"
  7. "github.com/flashmob/go-guerrilla/mail"
  8. "io/ioutil"
  9. "net"
  10. "os"
  11. "strings"
  12. "testing"
  13. "time"
  14. )
  15. // Test Starting smtp without setting up logger / backend
  16. func TestSMTP(t *testing.T) {
  17. done := make(chan bool)
  18. go func() {
  19. select {
  20. case <-time.After(time.Second * 40):
  21. t.Error("timeout")
  22. return
  23. case <-done:
  24. return
  25. }
  26. }()
  27. d := Daemon{}
  28. err := d.Start()
  29. if err != nil {
  30. t.Error(err)
  31. }
  32. // it should set to stderr automatically
  33. if d.Config.LogFile != log.OutputStderr.String() {
  34. t.Error("smtp.config.LogFile is not", log.OutputStderr.String())
  35. }
  36. if len(d.Config.AllowedHosts) == 0 {
  37. t.Error("smtp.config.AllowedHosts len should be 1, not 0", d.Config.AllowedHosts)
  38. }
  39. if d.Config.LogLevel != "debug" {
  40. t.Error("smtp.config.LogLevel expected'debug', it is", d.Config.LogLevel)
  41. }
  42. if len(d.Config.Servers) != 1 {
  43. t.Error("len(smtp.config.Servers) should be 1, got", len(d.Config.Servers))
  44. }
  45. time.Sleep(time.Second * 2)
  46. d.Shutdown()
  47. done <- true
  48. }
  49. // Suppressing log output
  50. func TestSMTPNoLog(t *testing.T) {
  51. // configure a default server with no log output
  52. cfg := &AppConfig{LogFile: log.OutputOff.String()}
  53. d := Daemon{Config: cfg}
  54. err := d.Start()
  55. if err != nil {
  56. t.Error(err)
  57. }
  58. time.Sleep(time.Second * 2)
  59. d.Shutdown()
  60. }
  61. // our custom server
  62. func TestSMTPCustomServer(t *testing.T) {
  63. cfg := &AppConfig{LogFile: log.OutputOff.String()}
  64. sc := ServerConfig{
  65. ListenInterface: "127.0.0.1:2526",
  66. IsEnabled: true,
  67. }
  68. cfg.Servers = append(cfg.Servers, sc)
  69. d := Daemon{Config: cfg}
  70. err := d.Start()
  71. if err != nil {
  72. t.Error("start error", err)
  73. } else {
  74. time.Sleep(time.Second * 2)
  75. d.Shutdown()
  76. }
  77. }
  78. // with a backend config
  79. func TestSMTPCustomBackend(t *testing.T) {
  80. cfg := &AppConfig{LogFile: log.OutputOff.String()}
  81. sc := ServerConfig{
  82. ListenInterface: "127.0.0.1:2526",
  83. IsEnabled: true,
  84. }
  85. cfg.Servers = append(cfg.Servers, sc)
  86. bcfg := backends.BackendConfig{
  87. "save_workers_size": 3,
  88. "save_process": "HeadersParser|Header|Hasher|Debugger",
  89. "log_received_mails": true,
  90. "primary_mail_host": "example.com",
  91. }
  92. cfg.BackendConfig = bcfg
  93. d := Daemon{Config: cfg}
  94. err := d.Start()
  95. if err != nil {
  96. t.Error("start error", err)
  97. } else {
  98. time.Sleep(time.Second * 2)
  99. d.Shutdown()
  100. }
  101. }
  102. // with a config from a json file
  103. func TestSMTPLoadFile(t *testing.T) {
  104. json := `{
  105. "log_file" : "./tests/testlog",
  106. "log_level" : "debug",
  107. "pid_file" : "tests/go-guerrilla.pid",
  108. "allowed_hosts": ["spam4.me","grr.la"],
  109. "backend_config" :
  110. {
  111. "log_received_mails" : true,
  112. "save_process": "HeadersParser|Header|Hasher|Debugger",
  113. "save_workers_size": 3
  114. },
  115. "servers" : [
  116. {
  117. "is_enabled" : true,
  118. "host_name":"mail.guerrillamail.com",
  119. "max_size": 100017,
  120. "private_key_file":"config_test.go",
  121. "public_key_file":"config_test.go",
  122. "timeout":160,
  123. "listen_interface":"127.0.0.1:2526",
  124. "start_tls_on":false,
  125. "tls_always_on":false,
  126. "max_clients": 2
  127. }
  128. ]
  129. }
  130. `
  131. json2 := `{
  132. "log_file" : "./tests/testlog2",
  133. "log_level" : "debug",
  134. "pid_file" : "tests/go-guerrilla2.pid",
  135. "allowed_hosts": ["spam4.me","grr.la"],
  136. "backend_config" :
  137. {
  138. "log_received_mails" : true,
  139. "save_process": "HeadersParser|Header|Hasher|Debugger",
  140. "save_workers_size": 3
  141. },
  142. "servers" : [
  143. {
  144. "is_enabled" : true,
  145. "host_name":"mail.guerrillamail.com",
  146. "max_size": 100017,
  147. "private_key_file":"config_test.go",
  148. "public_key_file":"config_test.go",
  149. "timeout":160,
  150. "listen_interface":"127.0.0.1:2526",
  151. "start_tls_on":false,
  152. "tls_always_on":false,
  153. "max_clients": 2
  154. }
  155. ]
  156. }
  157. `
  158. err := ioutil.WriteFile("goguerrilla.conf.api", []byte(json), 0644)
  159. if err != nil {
  160. t.Error("could not write guerrilla.conf.api", err)
  161. return
  162. }
  163. d := Daemon{}
  164. _, err = d.LoadConfig("goguerrilla.conf.api")
  165. if err != nil {
  166. t.Error("ReadConfig error", err)
  167. return
  168. }
  169. err = d.Start()
  170. if err != nil {
  171. t.Error("start error", err)
  172. return
  173. } else {
  174. time.Sleep(time.Second * 2)
  175. if d.Config.LogFile != "./tests/testlog" {
  176. t.Error("d.Config.LogFile != \"./tests/testlog\"")
  177. }
  178. if d.Config.PidFile != "tests/go-guerrilla.pid" {
  179. t.Error("d.Config.LogFile != tests/go-guerrilla.pid")
  180. }
  181. err := ioutil.WriteFile("goguerrilla.conf.api", []byte(json2), 0644)
  182. if err != nil {
  183. t.Error("could not write guerrilla.conf.api", err)
  184. return
  185. }
  186. d.ReloadConfigFile("goguerrilla.conf.api")
  187. if d.Config.LogFile != "./tests/testlog2" {
  188. t.Error("d.Config.LogFile != \"./tests/testlog\"")
  189. }
  190. if d.Config.PidFile != "tests/go-guerrilla2.pid" {
  191. t.Error("d.Config.LogFile != \"go-guerrilla.pid\"")
  192. }
  193. d.Shutdown()
  194. }
  195. }
  196. func TestReopenLog(t *testing.T) {
  197. os.Truncate("test/testlog", 0)
  198. cfg := &AppConfig{LogFile: "tests/testlog"}
  199. sc := ServerConfig{
  200. ListenInterface: "127.0.0.1:2526",
  201. IsEnabled: true,
  202. }
  203. cfg.Servers = append(cfg.Servers, sc)
  204. d := Daemon{Config: cfg}
  205. err := d.Start()
  206. if err != nil {
  207. t.Error("start error", err)
  208. } else {
  209. d.ReopenLogs()
  210. time.Sleep(time.Second * 2)
  211. d.Shutdown()
  212. }
  213. b, err := ioutil.ReadFile("tests/testlog")
  214. if err != nil {
  215. t.Error("could not read logfile")
  216. return
  217. }
  218. if strings.Index(string(b), "re-opened log file") < 0 {
  219. t.Error("Server log did not re-opened, expecting \"re-opened log file\"")
  220. }
  221. if strings.Index(string(b), "re-opened main log file") < 0 {
  222. t.Error("Main log did not re-opened, expecting \"re-opened main log file\"")
  223. }
  224. }
  225. func TestSetConfig(t *testing.T) {
  226. os.Truncate("test/testlog", 0)
  227. cfg := AppConfig{LogFile: "tests/testlog"}
  228. sc := ServerConfig{
  229. ListenInterface: "127.0.0.1:2526",
  230. IsEnabled: true,
  231. }
  232. cfg.Servers = append(cfg.Servers, sc)
  233. d := Daemon{Config: &cfg}
  234. // lets add a new server
  235. sc.ListenInterface = "127.0.0.1:2527"
  236. cfg.Servers = append(cfg.Servers, sc)
  237. err := d.SetConfig(cfg)
  238. if err != nil {
  239. t.Error("SetConfig returned an error:", err)
  240. return
  241. }
  242. err = d.Start()
  243. if err != nil {
  244. t.Error("start error", err)
  245. } else {
  246. time.Sleep(time.Second * 2)
  247. d.Shutdown()
  248. }
  249. b, err := ioutil.ReadFile("tests/testlog")
  250. if err != nil {
  251. t.Error("could not read logfile")
  252. return
  253. }
  254. //fmt.Println(string(b))
  255. // has 127.0.0.1:2527 started?
  256. if strings.Index(string(b), "127.0.0.1:2527") < 0 {
  257. t.Error("expecting 127.0.0.1:2527 to start")
  258. }
  259. }
  260. func TestSetConfigError(t *testing.T) {
  261. os.Truncate("tests/testlog", 0)
  262. cfg := AppConfig{LogFile: "tests/testlog"}
  263. sc := ServerConfig{
  264. ListenInterface: "127.0.0.1:2526",
  265. IsEnabled: true,
  266. }
  267. cfg.Servers = append(cfg.Servers, sc)
  268. d := Daemon{Config: &cfg}
  269. // lets add a new server with bad TLS
  270. sc.ListenInterface = "127.0.0.1:2527"
  271. sc.StartTLSOn = true
  272. sc.PublicKeyFile = "tests/testlog" // totally wrong :->
  273. sc.PublicKeyFile = "tests/testlog" // totally wrong :->
  274. cfg.Servers = append(cfg.Servers, sc)
  275. err := d.SetConfig(cfg)
  276. if err == nil {
  277. t.Error("SetConfig should have returned an error compalning about bad tls settings")
  278. return
  279. }
  280. }
  281. var funkyLogger = func() backends.Decorator {
  282. backends.Svc.AddInitializer(
  283. backends.InitializeWith(
  284. func(backendConfig backends.BackendConfig) error {
  285. backends.Log().Info("Funky logger is up & down to funk!")
  286. return nil
  287. }),
  288. )
  289. backends.Svc.AddShutdowner(
  290. backends.ShutdownWith(
  291. func() error {
  292. backends.Log().Info("The funk has been stopped!")
  293. return nil
  294. }),
  295. )
  296. return func(p backends.Processor) backends.Processor {
  297. return backends.ProcessWith(
  298. func(e *mail.Envelope, task backends.SelectTask) (backends.Result, error) {
  299. if task == backends.TaskValidateRcpt {
  300. // validate the last recipient appended to e.Rcpt
  301. backends.Log().Infof(
  302. "another funky recipient [%s]",
  303. e.RcptTo[len(e.RcptTo)-1])
  304. // if valid then forward call to the next processor in the chain
  305. return p.Process(e, task)
  306. // if invalid, return a backend result
  307. //return backends.NewResult(response.Canned.FailRcptCmd), nil
  308. } else if task == backends.TaskSaveMail {
  309. backends.Log().Info("Another funky email!")
  310. }
  311. return p.Process(e, task)
  312. })
  313. }
  314. }
  315. // How about a custom processor?
  316. func TestSetAddProcessor(t *testing.T) {
  317. os.Truncate("tests/testlog", 0)
  318. cfg := &AppConfig{
  319. LogFile: "tests/testlog",
  320. AllowedHosts: []string{"grr.la"},
  321. BackendConfig: backends.BackendConfig{
  322. "save_process": "HeadersParser|Debugger|FunkyLogger",
  323. "validate_process": "FunkyLogger",
  324. },
  325. }
  326. d := Daemon{Config: cfg}
  327. d.AddProcessor("FunkyLogger", funkyLogger)
  328. d.Start()
  329. // lets have a talk with the server
  330. talkToServer("127.0.0.1:2525")
  331. d.Shutdown()
  332. b, err := ioutil.ReadFile("tests/testlog")
  333. if err != nil {
  334. t.Error("could not read logfile")
  335. return
  336. }
  337. // lets check for fingerprints
  338. if strings.Index(string(b), "another funky recipient") < 0 {
  339. t.Error("did not log: another funky recipient")
  340. }
  341. if strings.Index(string(b), "Another funky email!") < 0 {
  342. t.Error("Did not log: Another funky email!")
  343. }
  344. if strings.Index(string(b), "Funky logger is up & down to funk") < 0 {
  345. t.Error("Did not log: Funky logger is up & down to funk")
  346. }
  347. if strings.Index(string(b), "The funk has been stopped!") < 0 {
  348. t.Error("Did not log:The funk has been stopped!")
  349. }
  350. }
  351. func talkToServer(address string) {
  352. conn, err := net.Dial("tcp", address)
  353. if err != nil {
  354. return
  355. }
  356. in := bufio.NewReader(conn)
  357. str, err := in.ReadString('\n')
  358. fmt.Fprint(conn, "HELO maildiranasaurustester\r\n")
  359. str, err = in.ReadString('\n')
  360. fmt.Fprint(conn, "MAIL FROM:<[email protected]>r\r\n")
  361. str, err = in.ReadString('\n')
  362. fmt.Fprint(conn, "RCPT TO:[email protected]\r\n")
  363. str, err = in.ReadString('\n')
  364. fmt.Fprint(conn, "DATA\r\n")
  365. str, err = in.ReadString('\n')
  366. fmt.Fprint(conn, "Subject: Test subject\r\n")
  367. fmt.Fprint(conn, "\r\n")
  368. fmt.Fprint(conn, "A an email body\r\n")
  369. fmt.Fprint(conn, ".\r\n")
  370. str, err = in.ReadString('\n')
  371. _ = str
  372. }
  373. // Test hot config reload
  374. // Here we forgot to add FunkyLogger so backend will fail to init
  375. func TestReloadConfig(t *testing.T) {
  376. os.Truncate("tests/testlog", 0)
  377. d := Daemon{}
  378. d.Start()
  379. defer d.Shutdown()
  380. cfg := AppConfig{
  381. LogFile: "tests/testlog",
  382. AllowedHosts: []string{"grr.la"},
  383. BackendConfig: backends.BackendConfig{
  384. "save_process": "HeadersParser|Debugger|FunkyLogger",
  385. "validate_process": "FunkyLogger",
  386. },
  387. }
  388. // Look mom, reloading the config without shutting down!
  389. d.ReloadConfig(cfg)
  390. }
  391. func TestPubSubAPI(t *testing.T) {
  392. os.Truncate("tests/testlog", 0)
  393. d := Daemon{Config: &AppConfig{LogFile: "tests/testlog"}}
  394. d.Start()
  395. defer d.Shutdown()
  396. // new config
  397. cfg := AppConfig{
  398. PidFile: "tests/pidfilex.pid",
  399. LogFile: "tests/testlog",
  400. AllowedHosts: []string{"grr.la"},
  401. BackendConfig: backends.BackendConfig{
  402. "save_process": "HeadersParser|Debugger|FunkyLogger",
  403. "validate_process": "FunkyLogger",
  404. },
  405. }
  406. var i = 0
  407. pidEvHandler := func(c *AppConfig) {
  408. i++
  409. if i > 1 {
  410. t.Error("number > 1, it means d.Unsubscribe didn't work")
  411. }
  412. d.Logger.Info("number", i)
  413. }
  414. d.Subscribe(EventConfigPidFile, pidEvHandler)
  415. d.ReloadConfig(cfg)
  416. d.Unsubscribe(EventConfigPidFile, pidEvHandler)
  417. cfg.PidFile = "tests/pidfile2.pid"
  418. d.Publish(EventConfigPidFile, &cfg)
  419. d.ReloadConfig(cfg)
  420. b, err := ioutil.ReadFile("tests/testlog")
  421. if err != nil {
  422. t.Error("could not read logfile")
  423. return
  424. }
  425. // lets interrogate the log
  426. if strings.Index(string(b), "number1") < 0 {
  427. t.Error("it lools like d.ReloadConfig(cfg) did not fire EventConfigPidFile, pidEvHandler not called")
  428. }
  429. }
  430. func TestAPILog(t *testing.T) {
  431. os.Truncate("tests/testlog", 0)
  432. d := Daemon{}
  433. l := d.Log()
  434. l.Info("logtest1") // to stderr
  435. if l.GetLevel() != log.InfoLevel.String() {
  436. t.Error("Log level does not eq info, it is ", l.GetLevel())
  437. }
  438. d.Logger = nil
  439. d.Config = &AppConfig{LogFile: "tests/testlog"}
  440. l = d.Log()
  441. l.Info("logtest1") // to tests/testlog
  442. //
  443. l = d.Log()
  444. if l.GetLogDest() != "tests/testlog" {
  445. t.Error("log dest is not tests/testlog, it was ", l.GetLogDest())
  446. }
  447. b, err := ioutil.ReadFile("tests/testlog")
  448. if err != nil {
  449. t.Error("could not read logfile")
  450. return
  451. }
  452. // lets interrogate the log
  453. if strings.Index(string(b), "logtest1") < 0 {
  454. t.Error("hai was not found in the log, it should have been in tests/testlog")
  455. }
  456. }
  457. // Test the allowed_hosts config option with a single entry of ".", which will allow all hosts.
  458. func TestSkipAllowsHost(t *testing.T) {
  459. d := Daemon{}
  460. defer d.Shutdown()
  461. // setting the allowed hosts to a single entry with a dot will let any host through
  462. d.Config = &AppConfig{AllowedHosts: []string{"."}, LogFile: "off"}
  463. d.Start()
  464. conn, err := net.Dial("tcp", d.Config.Servers[0].ListenInterface)
  465. if err != nil {
  466. t.Error(t)
  467. return
  468. }
  469. in := bufio.NewReader(conn)
  470. fmt.Fprint(conn, "HELO test\r\n")
  471. fmt.Fprint(conn, "RCPT TO: [email protected]\r\n")
  472. in.ReadString('\n')
  473. in.ReadString('\n')
  474. str, _ := in.ReadString('\n')
  475. if strings.Index(str, "250") != 0 {
  476. t.Error("expected 250 reply, got:", str)
  477. }
  478. }