api_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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. go func() {
  18. select {
  19. case <-time.After(time.Second * 40):
  20. //buf := make([]byte, 1<<16)
  21. //stackSize := runtime.Stack(buf, true)
  22. //fmt.Printf("%s\n", string(buf[0:stackSize]))
  23. //panic("timeout")
  24. t.Error("timeout")
  25. return
  26. }
  27. }()
  28. d := Daemon{}
  29. err := d.Start()
  30. if err != nil {
  31. t.Error(err)
  32. }
  33. // it should set to stderr automatically
  34. if d.Config.LogFile != log.OutputStderr.String() {
  35. t.Error("smtp.config.LogFile is not", log.OutputStderr.String())
  36. }
  37. if len(d.Config.AllowedHosts) == 0 {
  38. t.Error("smtp.config.AllowedHosts len should be 1, not 0", d.Config.AllowedHosts)
  39. }
  40. if d.Config.LogLevel != "debug" {
  41. t.Error("smtp.config.LogLevel expected'debug', it is", d.Config.LogLevel)
  42. }
  43. if len(d.Config.Servers) != 1 {
  44. t.Error("len(smtp.config.Servers) should be 1, got", len(d.Config.Servers))
  45. }
  46. time.Sleep(time.Second * 2)
  47. d.Shutdown()
  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.Println(str)
  359. fmt.Fprint(conn, "HELO maildiranasaurustester\r\n")
  360. str, err = in.ReadString('\n')
  361. // fmt.Println(str)
  362. fmt.Fprint(conn, "MAIL FROM:<[email protected]>r\r\n")
  363. str, err = in.ReadString('\n')
  364. // fmt.Println(str)
  365. fmt.Fprint(conn, "RCPT TO:[email protected]\r\n")
  366. str, err = in.ReadString('\n')
  367. // fmt.Println(str)
  368. fmt.Fprint(conn, "DATA\r\n")
  369. str, err = in.ReadString('\n')
  370. // fmt.Println(str)
  371. fmt.Fprint(conn, "Subject: Test subject\r\n")
  372. fmt.Fprint(conn, "\r\n")
  373. fmt.Fprint(conn, "A an email body\r\n")
  374. fmt.Fprint(conn, ".\r\n")
  375. str, err = in.ReadString('\n')
  376. // fmt.Println(str)
  377. _ = str
  378. }
  379. // Test hot config reload
  380. // Here we forgot to add FunkyLogger so backend will fail to init
  381. func TestReloadConfig(t *testing.T) {
  382. os.Truncate("tests/testlog", 0)
  383. d := Daemon{}
  384. d.Start()
  385. defer d.Shutdown()
  386. cfg := AppConfig{
  387. LogFile: "tests/testlog",
  388. AllowedHosts: []string{"grr.la"},
  389. BackendConfig: backends.BackendConfig{
  390. "save_process": "HeadersParser|Debugger|FunkyLogger",
  391. "validate_process": "FunkyLogger",
  392. },
  393. }
  394. // Look mom, reloading the config without shutting down!
  395. d.ReloadConfig(cfg)
  396. }
  397. func TestPubSubAPI(t *testing.T) {
  398. os.Truncate("tests/testlog", 0)
  399. d := Daemon{Config: &AppConfig{LogFile: "tests/testlog"}}
  400. d.Start()
  401. defer d.Shutdown()
  402. // new config
  403. cfg := AppConfig{
  404. PidFile: "tests/pidfilex.pid",
  405. LogFile: "tests/testlog",
  406. AllowedHosts: []string{"grr.la"},
  407. BackendConfig: backends.BackendConfig{
  408. "save_process": "HeadersParser|Debugger|FunkyLogger",
  409. "validate_process": "FunkyLogger",
  410. },
  411. }
  412. var i = 0
  413. pidEvHandler := func(c *AppConfig) {
  414. i++
  415. if i > 1 {
  416. t.Error("number > 1, it means d.Unsubscribe didn't work")
  417. }
  418. d.Logger.Info("number", i)
  419. }
  420. d.Subscribe(EventConfigPidFile, pidEvHandler)
  421. d.ReloadConfig(cfg)
  422. d.Unsubscribe(EventConfigPidFile, pidEvHandler)
  423. cfg.PidFile = "tests/pidfile2.pid"
  424. d.Publish(EventConfigPidFile, &cfg)
  425. d.ReloadConfig(cfg)
  426. b, err := ioutil.ReadFile("tests/testlog")
  427. if err != nil {
  428. t.Error("could not read logfile")
  429. return
  430. }
  431. // lets interrogate the log
  432. if strings.Index(string(b), "number1") < 0 {
  433. t.Error("it lools like d.ReloadConfig(cfg) did not fire EventConfigPidFile, pidEvHandler not called")
  434. }
  435. }
  436. func TestAPILog(t *testing.T) {
  437. os.Truncate("tests/testlog", 0)
  438. d := Daemon{}
  439. l := d.Log()
  440. l.Info("logtest1") // to stderr
  441. if l.GetLevel() != log.InfoLevel.String() {
  442. t.Error("Log level does not eq info, it is ", l.GetLevel())
  443. }
  444. d.Logger = nil
  445. d.Config = &AppConfig{LogFile: "tests/testlog"}
  446. l = d.Log()
  447. l.Info("logtest1") // to tests/testlog
  448. //
  449. l = d.Log()
  450. if l.GetLogDest() != "tests/testlog" {
  451. t.Error("log dest is not tests/testlog, it was ", l.GetLogDest())
  452. }
  453. b, err := ioutil.ReadFile("tests/testlog")
  454. if err != nil {
  455. t.Error("could not read logfile")
  456. return
  457. }
  458. // lets interrogate the log
  459. if strings.Index(string(b), "logtest1") < 0 {
  460. t.Error("hai was not found in the log, it should have been in tests/testlog")
  461. }
  462. }
  463. // Test the allowed_hosts config option with a single entry of ".", which will allow all hosts.
  464. func TestSkipAllowsHost(t *testing.T) {
  465. d := Daemon{}
  466. defer d.Shutdown()
  467. // setting the allowed hosts to a single entry with a dot will let any host through
  468. d.Config = &AppConfig{AllowedHosts: []string{"."}, LogFile: "off"}
  469. d.Start()
  470. conn, err := net.Dial("tcp", d.Config.Servers[0].ListenInterface)
  471. if err != nil {
  472. t.Error(t)
  473. return
  474. }
  475. in := bufio.NewReader(conn)
  476. fmt.Fprint(conn, "HELO test\r\n")
  477. fmt.Fprint(conn, "RCPT TO: [email protected]\r\n")
  478. in.ReadString('\n')
  479. in.ReadString('\n')
  480. str, _ := in.ReadString('\n')
  481. if strings.Index(str, "250") != 0 {
  482. t.Error("expected 250 reply, got:", str)
  483. }
  484. }