serve_test.go 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556
  1. package main
  2. import (
  3. "bufio"
  4. "crypto/tls"
  5. "encoding/json"
  6. "errors"
  7. "io"
  8. "io/ioutil"
  9. "math"
  10. "os"
  11. "os/exec"
  12. "runtime"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "testing"
  17. "time"
  18. "github.com/flashmob/go-guerrilla"
  19. "github.com/flashmob/go-guerrilla/backends"
  20. "github.com/flashmob/go-guerrilla/log"
  21. "github.com/flashmob/go-guerrilla/tests"
  22. "github.com/flashmob/go-guerrilla/tests/testcert"
  23. "github.com/spf13/cobra"
  24. )
  25. var configJsonA = `
  26. {
  27. "log_file" : "../../tests/testlog",
  28. "log_level" : "debug",
  29. "pid_file" : "./pidfile.pid",
  30. "allowed_hosts": [
  31. "guerrillamail.com",
  32. "guerrillamailblock.com",
  33. "sharklasers.com",
  34. "guerrillamail.net",
  35. "guerrillamail.org"
  36. ],
  37. "backend_config": {
  38. "save_workers_size" : 1,
  39. "save_process": "HeadersParser|Debugger",
  40. "log_received_mails": true
  41. },
  42. "servers" : [
  43. {
  44. "is_enabled" : true,
  45. "host_name":"mail.test.com",
  46. "max_size": 1000000,
  47. "timeout":180,
  48. "listen_interface":"127.0.0.1:3536",
  49. "max_clients": 200,
  50. "log_file" : "../../tests/testlog",
  51. "tls" : {
  52. "private_key_file":"../../tests/mail2.guerrillamail.com.key.pem",
  53. "public_key_file":"../../tests/mail2.guerrillamail.com.cert.pem",
  54. "start_tls_on":true,
  55. "tls_always_on":false
  56. }
  57. },
  58. {
  59. "is_enabled" : false,
  60. "host_name":"enable.test.com",
  61. "max_size": 1000000,
  62. "timeout":180,
  63. "listen_interface":"127.0.0.1:2228",
  64. "max_clients": 200,
  65. "log_file" : "../../tests/testlog",
  66. "tls" : {
  67. "private_key_file":"../../tests/mail2.guerrillamail.com.key.pem",
  68. "public_key_file":"../../tests/mail2.guerrillamail.com.cert.pem",
  69. "start_tls_on":true,
  70. "tls_always_on":false
  71. }
  72. }
  73. ]
  74. }
  75. `
  76. // backend config changed, log_received_mails is false
  77. var configJsonB = `
  78. {
  79. "log_file" : "../../tests/testlog",
  80. "log_level" : "debug",
  81. "pid_file" : "./pidfile2.pid",
  82. "allowed_hosts": [
  83. "guerrillamail.com",
  84. "guerrillamailblock.com",
  85. "sharklasers.com",
  86. "guerrillamail.net",
  87. "guerrillamail.org"
  88. ],
  89. "backend_config": {
  90. "save_workers_size" : 1,
  91. "save_process": "HeadersParser|Debugger",
  92. "log_received_mails": false
  93. },
  94. "servers" : [
  95. {
  96. "is_enabled" : true,
  97. "host_name":"mail.test.com",
  98. "max_size": 1000000,
  99. "timeout":180,
  100. "listen_interface":"127.0.0.1:3536",
  101. "max_clients": 200,
  102. "log_file" : "../../tests/testlog",
  103. "tls" : {
  104. "private_key_file":"../../tests/mail2.guerrillamail.com.key.pem",
  105. "public_key_file":"../../tests/mail2.guerrillamail.com.cert.pem",
  106. "start_tls_on":true,
  107. "tls_always_on":false
  108. }
  109. }
  110. ]
  111. }
  112. `
  113. // added a server
  114. var configJsonC = `
  115. {
  116. "log_file" : "../../tests/testlog",
  117. "log_level" : "debug",
  118. "pid_file" : "./pidfile.pid",
  119. "allowed_hosts": [
  120. "guerrillamail.com",
  121. "guerrillamailblock.com",
  122. "sharklasers.com",
  123. "guerrillamail.net",
  124. "guerrillamail.org"
  125. ],
  126. "backend_config" :
  127. {
  128. "sql_driver": "mysql",
  129. "sql_dsn": "root:ok@tcp(127.0.0.1:3306)/gmail_mail?readTimeout=10s&writeTimeout=10s",
  130. "mail_table":"new_mail",
  131. "redis_interface" : "127.0.0.1:6379",
  132. "redis_expire_seconds" : 7200,
  133. "save_workers_size" : 3,
  134. "primary_mail_host":"sharklasers.com",
  135. "save_workers_size" : 1,
  136. "save_process": "HeadersParser|Debugger",
  137. "log_received_mails": true
  138. },
  139. "servers" : [
  140. {
  141. "is_enabled" : true,
  142. "host_name":"mail.test.com",
  143. "max_size": 1000000,
  144. "timeout":180,
  145. "listen_interface":"127.0.0.1:25",
  146. "max_clients": 200,
  147. "log_file" : "../../tests/testlog",
  148. "tls" : {
  149. "private_key_file":"../../tests/mail2.guerrillamail.com.key.pem",
  150. "public_key_file":"../../tests/mail2.guerrillamail.com.cert.pem",
  151. "start_tls_on":true,
  152. "tls_always_on":false
  153. }
  154. },
  155. {
  156. "is_enabled" : true,
  157. "host_name":"mail.test.com",
  158. "max_size":1000000,
  159. "timeout":180,
  160. "listen_interface":"127.0.0.1:465",
  161. "max_clients":200,
  162. "log_file" : "../../tests/testlog",
  163. "tls" : {
  164. "private_key_file":"../../tests/mail2.guerrillamail.com.key.pem",
  165. "public_key_file":"../../tests/mail2.guerrillamail.com.cert.pem",
  166. "start_tls_on":false,
  167. "tls_always_on":true
  168. }
  169. }
  170. ]
  171. }
  172. `
  173. // adds 127.0.0.1:4655, a secure server
  174. var configJsonD = `
  175. {
  176. "log_file" : "../../tests/testlog",
  177. "log_level" : "debug",
  178. "pid_file" : "./pidfile.pid",
  179. "allowed_hosts": [
  180. "guerrillamail.com",
  181. "guerrillamailblock.com",
  182. "sharklasers.com",
  183. "guerrillamail.net",
  184. "guerrillamail.org"
  185. ],
  186. "backend_config": {
  187. "save_workers_size" : 1,
  188. "save_process": "HeadersParser|Debugger",
  189. "log_received_mails": false
  190. },
  191. "servers" : [
  192. {
  193. "is_enabled" : true,
  194. "host_name":"mail.test.com",
  195. "max_size": 1000000,
  196. "timeout":180,
  197. "listen_interface":"127.0.0.1:2552",
  198. "max_clients": 200,
  199. "log_file" : "../../tests/testlog",
  200. "tls" : {
  201. "private_key_file":"../../tests/mail2.guerrillamail.com.key.pem",
  202. "public_key_file":"../../tests/mail2.guerrillamail.com.cert.pem",
  203. "start_tls_on":true,
  204. "tls_always_on":false
  205. }
  206. },
  207. {
  208. "is_enabled" : true,
  209. "host_name":"secure.test.com",
  210. "max_size":1000000,
  211. "timeout":180,
  212. "listen_interface":"127.0.0.1:4655",
  213. "max_clients":200,
  214. "log_file" : "../../tests/testlog",
  215. "tls" : {
  216. "private_key_file":"../../tests/mail2.guerrillamail.com.key.pem",
  217. "public_key_file":"../../tests/mail2.guerrillamail.com.cert.pem",
  218. "start_tls_on":false,
  219. "tls_always_on":true
  220. }
  221. }
  222. ]
  223. }
  224. `
  225. // adds 127.0.0.1:4655, a secure server
  226. var configJsonE = `
  227. {
  228. "log_file" : "../../tests/testlog",
  229. "log_level" : "debug",
  230. "pid_file" : "./pidfile2.pid",
  231. "allowed_hosts": [
  232. "guerrillamail.com",
  233. "guerrillamailblock.com",
  234. "sharklasers.com",
  235. "guerrillamail.net",
  236. "guerrillamail.org"
  237. ],
  238. "backend_config" :
  239. {
  240. "save_process_old": "HeadersParser|Debugger|Hasher|Header|Compressor|Redis|MySql",
  241. "save_process": "GuerrillaRedisDB",
  242. "log_received_mails" : true,
  243. "sql_driver": "mysql",
  244. "sql_dsn": "root:secret@tcp(127.0.0.1:3306)/gmail_mail?readTimeout=10s&writeTimeout=10s",
  245. "mail_table":"new_mail",
  246. "redis_interface" : "127.0.0.1:6379",
  247. "redis_expire_seconds" : 7200,
  248. "save_workers_size" : 3,
  249. "primary_mail_host":"sharklasers.com"
  250. },
  251. "servers" : [
  252. {
  253. "is_enabled" : true,
  254. "host_name":"mail.test.com",
  255. "max_size": 1000000,
  256. "timeout":180,
  257. "listen_interface":"127.0.0.1:2552",
  258. "max_clients": 200,
  259. "log_file" : "../../tests/testlog",
  260. "tls" : {
  261. "private_key_file":"../../tests/mail2.guerrillamail.com.key.pem",
  262. "public_key_file":"../../tests/mail2.guerrillamail.com.cert.pem",
  263. "start_tls_on":true,
  264. "tls_always_on":false
  265. }
  266. },
  267. {
  268. "is_enabled" : true,
  269. "host_name":"secure.test.com",
  270. "max_size":1000000,
  271. "timeout":180,
  272. "listen_interface":"127.0.0.1:4655",
  273. "max_clients":200,
  274. "log_file" : "../../tests/testlog",
  275. "tls" : {
  276. "private_key_file":"../../tests/mail2.guerrillamail.com.key.pem",
  277. "public_key_file":"../../tests/mail2.guerrillamail.com.cert.pem",
  278. "start_tls_on":false,
  279. "tls_always_on":true
  280. }
  281. }
  282. ]
  283. }
  284. `
  285. const testPauseDuration = time.Millisecond * 1010
  286. // reload config
  287. func sigHup() {
  288. if data, err := ioutil.ReadFile("pidfile.pid"); err == nil {
  289. mainlog.Infof("pid read is %s", data)
  290. ecmd := exec.Command("kill", "-HUP", string(data))
  291. _, err = ecmd.Output()
  292. if err != nil {
  293. mainlog.Infof("could not SIGHUP", err)
  294. }
  295. } else {
  296. mainlog.WithError(err).Info("sighup - Could not read pidfle")
  297. }
  298. }
  299. // shutdown after calling serve()
  300. func sigKill() {
  301. if data, err := ioutil.ReadFile("pidfile.pid"); err == nil {
  302. mainlog.Infof("pid read is %s", data)
  303. ecmd := exec.Command("kill", string(data))
  304. _, err = ecmd.Output()
  305. if err != nil {
  306. mainlog.Infof("could not sigkill", err)
  307. }
  308. } else {
  309. mainlog.WithError(err).Info("sigKill - Could not read pidfle")
  310. }
  311. }
  312. func Round(x float64) float64 {
  313. t := math.Trunc(x)
  314. if math.Abs(x-t) >= 0.5 {
  315. return t + math.Copysign(1, x)
  316. }
  317. return t
  318. }
  319. // exponentialBackoff sleeps in nanoseconds, according to this formula 2^(i-1) * 25 / 2
  320. func exponentialBackoff(i int) {
  321. time.Sleep(time.Duration(Round(math.Pow(3.0, float64(i))-1.0)*100.0/2.0) * time.Millisecond)
  322. }
  323. var grepNotFound error
  324. // grepTestlog looks for the `match` string in the testlog
  325. // the lineNumber indicates what line to start the search from
  326. // returns line number it was found on
  327. // error otherwise
  328. //
  329. // It will attempt to search the log multiple times, pausing loner for each re-try
  330. //
  331. func grepTestlog(match string, lineNumber int) (found int, err error) {
  332. found = 0
  333. fd, err := os.Open("../../tests/testlog")
  334. if err != nil {
  335. return found, err
  336. }
  337. defer func() {
  338. _ = fd.Close()
  339. }()
  340. buff := bufio.NewReader(fd)
  341. var ln int
  342. var line string
  343. for tries := 0; tries < 6; tries++ {
  344. //fmt.Println("try..", tries)
  345. for {
  346. ln++
  347. line, err = buff.ReadString('\n')
  348. if err != nil {
  349. break
  350. }
  351. if ln > lineNumber {
  352. //fmt.Print(ln, line)
  353. if i := strings.Index(line, match); i != -1 {
  354. return ln, nil
  355. }
  356. }
  357. }
  358. if err != nil && err != io.EOF {
  359. return found, err
  360. }
  361. err = fd.Close()
  362. if err != nil {
  363. return 0, err
  364. }
  365. fd = nil
  366. // sleep
  367. exponentialBackoff(tries)
  368. _ = mainlog.Reopen()
  369. // re-open
  370. fd, err = os.OpenFile("../../tests/testlog", os.O_RDONLY, 0644)
  371. if err != nil {
  372. return found, err
  373. }
  374. buff.Reset(fd)
  375. ln = 0
  376. }
  377. grepNotFound = errors.New("could not find " + match + " in tests/testlog after line" + strconv.Itoa(lineNumber))
  378. return found, grepNotFound
  379. }
  380. // In all the tests, there will be a minimum of about 2000 available
  381. func TestFileLimit(t *testing.T) {
  382. cfg := &guerrilla.AppConfig{LogFile: log.OutputOff.String()}
  383. sc := guerrilla.ServerConfig{
  384. ListenInterface: "127.0.0.1:2526",
  385. IsEnabled: true,
  386. MaxClients: 1000,
  387. }
  388. cfg.Servers = append(cfg.Servers, sc)
  389. d := guerrilla.Daemon{Config: cfg}
  390. if ok, maxClients, fileLimit := guerrilla.CheckFileLimit(d.Config); !ok {
  391. t.Errorf("Combined max clients for all servers (%d) is greater than open file limit (%d). "+
  392. "Please increase your open file limit. Please check your OS docs for how to increase the limit.", maxClients, fileLimit)
  393. }
  394. }
  395. func getTestLog() (mainlog log.Logger, err error) {
  396. return log.GetLogger("../../tests/testlog", "debug")
  397. }
  398. func truncateIfExists(filename string) error {
  399. if _, err := os.Stat(filename); !os.IsNotExist(err) {
  400. return os.Truncate(filename, 0)
  401. }
  402. return nil
  403. }
  404. func deleteIfExists(filename string) error {
  405. if _, err := os.Stat(filename); !os.IsNotExist(err) {
  406. return os.Remove(filename)
  407. }
  408. return nil
  409. }
  410. func cleanTestArtifacts(t *testing.T) {
  411. if err := truncateIfExists("../../tests/testlog"); err != nil {
  412. t.Error("could not clean tests/testlog:", err)
  413. }
  414. if err := truncateIfExists("../../tests/testlog2"); err != nil {
  415. t.Error("could not clean tests/testlog2:", err)
  416. }
  417. letters := []byte{'A', 'B', 'C', 'D', 'E'}
  418. for _, l := range letters {
  419. if err := deleteIfExists("configJson" + string(l) + ".json"); err != nil {
  420. t.Error("could not delete configJson"+string(l)+".json:", err)
  421. }
  422. }
  423. if err := deleteIfExists("./pidfile.pid"); err != nil {
  424. t.Error("could not delete ./pidfile.pid", err)
  425. }
  426. if err := deleteIfExists("./pidfile2.pid"); err != nil {
  427. t.Error("could not delete ./pidfile2.pid", err)
  428. }
  429. if err := deleteIfExists("../../tests/mail.guerrillamail.com.cert.pem"); err != nil {
  430. t.Error("could not delete ../../tests/mail.guerrillamail.com.cert.pem", err)
  431. }
  432. if err := deleteIfExists("../../tests/mail.guerrillamail.com.key.pem"); err != nil {
  433. t.Error("could not delete ../../tests/mail.guerrillamail.com.key.pem", err)
  434. }
  435. if err := deleteIfExists("../../tests/mail2.guerrillamail.com.cert.pem"); err != nil {
  436. t.Error("could not delete ../../tests/mail2.guerrillamail.com.cert.pem", err)
  437. }
  438. if err := deleteIfExists("../../tests/mail2.guerrillamail.com.key.pem"); err != nil {
  439. t.Error("could not delete ../../tests/mail2.guerrillamail.com.key.pem", err)
  440. }
  441. }
  442. // make sure that we get all the config change events
  443. func TestCmdConfigChangeEvents(t *testing.T) {
  444. defer cleanTestArtifacts(t)
  445. var err error
  446. err = testcert.GenerateCert("mail2.guerrillamail.com", "", 365*24*time.Hour, false, 2048, "P256", "../../tests/")
  447. if err != nil {
  448. t.Error("failed to generate a test certificate", err)
  449. t.FailNow()
  450. }
  451. oldconf := &guerrilla.AppConfig{}
  452. if err := oldconf.Load([]byte(configJsonA)); err != nil {
  453. t.Error("configJsonA is invalid", err)
  454. }
  455. newconf := &guerrilla.AppConfig{}
  456. if err := newconf.Load([]byte(configJsonB)); err != nil {
  457. t.Error("configJsonB is invalid", err)
  458. }
  459. newerconf := &guerrilla.AppConfig{}
  460. if err := newerconf.Load([]byte(configJsonC)); err != nil {
  461. t.Error("configJsonC is invalid", err)
  462. }
  463. expectedEvents := map[guerrilla.Event]bool{
  464. guerrilla.EventConfigBackendConfig: false,
  465. guerrilla.EventConfigServerNew: false,
  466. }
  467. mainlog, err = getTestLog()
  468. if err != nil {
  469. t.Error("could not get logger,", err)
  470. t.FailNow()
  471. }
  472. bcfg := backends.BackendConfig{"log_received_mails": true}
  473. backend, err := backends.New(bcfg, mainlog)
  474. app, err := guerrilla.New(oldconf, backend, mainlog)
  475. if err != nil {
  476. t.Error("Failed to create new app", err)
  477. }
  478. toUnsubscribe := map[guerrilla.Event]func(c *guerrilla.AppConfig){}
  479. toUnsubscribeS := map[guerrilla.Event]func(c *guerrilla.ServerConfig){}
  480. for event := range expectedEvents {
  481. // Put in anon func since range is overwriting event
  482. func(e guerrilla.Event) {
  483. if strings.Index(e.String(), "server_change") == 0 {
  484. f := func(c *guerrilla.ServerConfig) {
  485. expectedEvents[e] = true
  486. }
  487. _ = app.Subscribe(e, f)
  488. toUnsubscribeS[e] = f
  489. } else {
  490. f := func(c *guerrilla.AppConfig) {
  491. expectedEvents[e] = true
  492. }
  493. _ = app.Subscribe(e, f)
  494. toUnsubscribe[e] = f
  495. }
  496. }(event)
  497. }
  498. // emit events
  499. newconf.EmitChangeEvents(oldconf, app)
  500. newerconf.EmitChangeEvents(newconf, app)
  501. // unsubscribe
  502. for unevent, unfun := range toUnsubscribe {
  503. _ = app.Unsubscribe(unevent, unfun)
  504. }
  505. for unevent, unfun := range toUnsubscribeS {
  506. _ = app.Unsubscribe(unevent, unfun)
  507. }
  508. for event, val := range expectedEvents {
  509. if val == false {
  510. t.Error("Did not fire config change event:", event)
  511. t.FailNow()
  512. break
  513. }
  514. }
  515. }
  516. // start server, change config, send SIG HUP, confirm that the pidfile changed & backend reloaded
  517. func TestServe(t *testing.T) {
  518. defer cleanTestArtifacts(t)
  519. var err error
  520. err = testcert.GenerateCert("mail2.guerrillamail.com", "", 365*24*time.Hour, false, 2048, "P256", "../../tests/")
  521. if err != nil {
  522. t.Error("failed to generate a test certificate", err)
  523. t.FailNow()
  524. }
  525. mainlog, err = getTestLog()
  526. if err != nil {
  527. t.Error("could not get logger,", err)
  528. t.FailNow()
  529. }
  530. if err := ioutil.WriteFile("configJsonA.json", []byte(configJsonA), 0644); err != nil {
  531. t.Error(err)
  532. t.FailNow()
  533. }
  534. cmd := &cobra.Command{}
  535. configPath = "configJsonA.json"
  536. go func() {
  537. serve(cmd, []string{})
  538. }()
  539. if _, err := grepTestlog("istening on TCP 127.0.0.1:3536", 0); err != nil {
  540. t.Error("server not started")
  541. }
  542. data, err := ioutil.ReadFile("pidfile.pid")
  543. if err != nil {
  544. t.Error("error reading pidfile.pid", err)
  545. t.FailNow()
  546. }
  547. _, err = strconv.Atoi(string(data))
  548. if err != nil {
  549. t.Error("could not parse pidfile.pid", err)
  550. t.FailNow()
  551. }
  552. // change the config file
  553. err = ioutil.WriteFile("configJsonA.json", []byte(configJsonB), 0644)
  554. if err != nil {
  555. t.Error(err)
  556. t.FailNow()
  557. }
  558. // test SIGHUP via the kill command
  559. // Would not work on windows as kill is not available.
  560. // TODO: Implement an alternative test for windows.
  561. if runtime.GOOS != "windows" {
  562. sigHup()
  563. // did the pidfile change as expected?
  564. if _, err := grepTestlog("Configuration was reloaded", 0); err != nil {
  565. t.Error("server did not catch sighp")
  566. }
  567. }
  568. // send kill signal and wait for exit
  569. d.Shutdown()
  570. // did backend started as expected?
  571. if _, err := grepTestlog("new backend started", 0); err != nil {
  572. t.Error("Dummy backend not restarted")
  573. }
  574. // wait for shutdown
  575. if _, err := grepTestlog("Backend shutdown completed", 0); err != nil {
  576. t.Error("server didn't stop")
  577. }
  578. }
  579. // Start with configJsonA.json,
  580. // then add a new server to it (127.0.0.1:2526),
  581. // then SIGHUP (to reload config & trigger config update events),
  582. // then connect to it & HELO.
  583. func TestServerAddEvent(t *testing.T) {
  584. var err error
  585. err = testcert.GenerateCert("mail2.guerrillamail.com", "", 365*24*time.Hour, false, 2048, "P256", "../../tests/")
  586. if err != nil {
  587. t.Error("failed to generate a test certificate", err)
  588. t.FailNow()
  589. }
  590. defer cleanTestArtifacts(t)
  591. mainlog, err = getTestLog()
  592. if err != nil {
  593. t.Error("could not get logger,", err)
  594. t.FailNow()
  595. }
  596. // start the server by emulating the serve command
  597. if err := ioutil.WriteFile("configJsonA.json", []byte(configJsonA), 0644); err != nil {
  598. t.Error(err)
  599. t.FailNow()
  600. }
  601. cmd := &cobra.Command{}
  602. configPath = "configJsonA.json"
  603. go func() {
  604. serve(cmd, []string{})
  605. }()
  606. // allow the server to start
  607. if _, err := grepTestlog("Listening on TCP 127.0.0.1:3536", 0); err != nil {
  608. t.Error("server didn't start")
  609. }
  610. // now change the config by adding a server
  611. conf := &guerrilla.AppConfig{} // blank one
  612. err = conf.Load([]byte(configJsonA)) // load configJsonA
  613. if err != nil {
  614. t.Error(err)
  615. }
  616. newServer := conf.Servers[0] // copy the first server config
  617. newServer.ListenInterface = "127.0.0.1:2526" // change it
  618. newConf := conf // copy the cmdConfg
  619. newConf.Servers = append(newConf.Servers, newServer) // add the new server
  620. if jsonbytes, err := json.Marshal(newConf); err == nil {
  621. if err := ioutil.WriteFile("configJsonA.json", []byte(jsonbytes), 0644); err != nil {
  622. t.Error(err)
  623. }
  624. }
  625. // send a sighup signal to the server
  626. sigHup()
  627. if _, err := grepTestlog("[127.0.0.1:2526] Waiting for a new client", 0); err != nil {
  628. t.Error("new server didn't start")
  629. }
  630. if conn, buffin, err := test.Connect(newServer, 20); err != nil {
  631. t.Error("Could not connect to new server", newServer.ListenInterface, err)
  632. } else {
  633. if result, err := test.Command(conn, buffin, "HELO"); err == nil {
  634. expect := "250 mail.test.com Hello"
  635. if strings.Index(result, expect) != 0 {
  636. t.Error("Expected", expect, "but got", result)
  637. }
  638. } else {
  639. t.Error(err)
  640. }
  641. }
  642. // shutdown the server
  643. d.Shutdown()
  644. // did backend started as expected?
  645. if _, err := grepTestlog("New server added [127.0.0.1:2526]", 0); err != nil {
  646. t.Error("Did not add server [127.0.0.1:2526] after sighup")
  647. }
  648. if _, err := grepTestlog("Backend shutdown completed", 0); err != nil {
  649. t.Error("Server failed to stop")
  650. }
  651. }
  652. // Start with configJsonA.json,
  653. // then change the config to enable 127.0.0.1:2228,
  654. // then write the new config,
  655. // then SIGHUP (to reload config & trigger config update events),
  656. // then connect to 127.0.0.1:2228 & HELO.
  657. func TestServerStartEvent(t *testing.T) {
  658. var err error
  659. err = testcert.GenerateCert("mail2.guerrillamail.com", "", 365*24*time.Hour, false, 2048, "P256", "../../tests/")
  660. if err != nil {
  661. t.Error("failed to generate a test certificate", err)
  662. t.FailNow()
  663. }
  664. defer cleanTestArtifacts(t)
  665. mainlog, err = getTestLog()
  666. if err != nil {
  667. t.Error("could not get logger,", err)
  668. t.FailNow()
  669. }
  670. if err := ioutil.WriteFile("configJsonA.json", []byte(configJsonA), 0644); err != nil {
  671. t.Error(err)
  672. t.FailNow()
  673. }
  674. cmd := &cobra.Command{}
  675. configPath = "configJsonA.json"
  676. go func() {
  677. serve(cmd, []string{})
  678. }()
  679. if _, err := grepTestlog("Listening on TCP 127.0.0.1:3536", 0); err != nil {
  680. t.Error("server didn't start")
  681. }
  682. // now change the config by adding a server
  683. conf := &guerrilla.AppConfig{} // blank one
  684. if err = conf.Load([]byte(configJsonA)); err != nil { // load configJsonA
  685. t.Error(err)
  686. }
  687. newConf := conf // copy the cmdConfg
  688. newConf.Servers[1].IsEnabled = true
  689. if jsonbytes, err := json.Marshal(newConf); err == nil {
  690. //fmt.Println(string(jsonbytes))
  691. if err = ioutil.WriteFile("configJsonA.json", []byte(jsonbytes), 0644); err != nil {
  692. t.Error(err)
  693. }
  694. } else {
  695. t.Error(err)
  696. }
  697. // send a sighup signal to the server
  698. sigHup()
  699. // see if the new server started?
  700. if _, err := grepTestlog("Listening on TCP 127.0.0.1:2228", 0); err != nil {
  701. t.Error("second server didn't start")
  702. }
  703. // can we talk to it?
  704. if conn, buffin, err := test.Connect(newConf.Servers[1], 20); err != nil {
  705. t.Error("Could not connect to new server", newConf.Servers[1].ListenInterface)
  706. } else {
  707. if result, err := test.Command(conn, buffin, "HELO"); err == nil {
  708. expect := "250 enable.test.com Hello"
  709. if strings.Index(result, expect) != 0 {
  710. t.Error("Expected", expect, "but got", result)
  711. }
  712. } else {
  713. t.Error(err)
  714. }
  715. }
  716. // shutdown and wait for exit
  717. d.Shutdown()
  718. if _, err := grepTestlog("Backend shutdown completed", 0); err != nil {
  719. t.Error("server didn't stop")
  720. }
  721. }
  722. // Start with configJsonA.json,
  723. // then change the config to enable 127.0.0.1:2228,
  724. // then write the new config,
  725. // then SIGHUP (to reload config & trigger config update events),
  726. // then connect to 127.0.0.1:2228 & HELO.
  727. // then change the config to dsiable 127.0.0.1:2228,
  728. // then SIGHUP (to reload config & trigger config update events),
  729. // then connect to 127.0.0.1:2228 - it should not connect
  730. func TestServerStopEvent(t *testing.T) {
  731. var err error
  732. err = testcert.GenerateCert("mail2.guerrillamail.com", "", 365*24*time.Hour, false, 2048, "P256", "../../tests/")
  733. if err != nil {
  734. t.Error("failed to generate a test certificate", err)
  735. t.FailNow()
  736. }
  737. defer cleanTestArtifacts(t)
  738. mainlog, err = getTestLog()
  739. if err != nil {
  740. t.Error("could not get logger,", err)
  741. t.FailNow()
  742. }
  743. if err := ioutil.WriteFile("configJsonA.json", []byte(configJsonA), 0644); err != nil {
  744. t.Error(err)
  745. t.FailNow()
  746. }
  747. cmd := &cobra.Command{}
  748. configPath = "configJsonA.json"
  749. go func() {
  750. serve(cmd, []string{})
  751. }()
  752. // allow the server to start
  753. if _, err := grepTestlog("Listening on TCP 127.0.0.1:3536", 0); err != nil {
  754. t.Error("server didn't start")
  755. }
  756. // now change the config by enabling a server
  757. conf := &guerrilla.AppConfig{} // blank one
  758. if err = conf.Load([]byte(configJsonA)); err != nil { // load configJsonA
  759. t.Error(err)
  760. }
  761. newConf := conf // copy the cmdConfg
  762. newConf.Servers[1].IsEnabled = true // enable 2nd server
  763. if jsonbytes, err := json.Marshal(newConf); err == nil {
  764. //fmt.Println(string(jsonbytes))
  765. if err = ioutil.WriteFile("configJsonA.json", []byte(jsonbytes), 0644); err != nil {
  766. t.Error(err)
  767. }
  768. } else {
  769. t.Error(err)
  770. }
  771. // send a sighup signal to the server
  772. sigHup()
  773. // detect config change
  774. if _, err := grepTestlog("Listening on TCP 127.0.0.1:2228", 0); err != nil {
  775. t.Error("new server didn't start")
  776. }
  777. if conn, buffin, err := test.Connect(newConf.Servers[1], 20); err != nil {
  778. t.Error("Could not connect to new server", newConf.Servers[1].ListenInterface)
  779. } else {
  780. if result, err := test.Command(conn, buffin, "HELO"); err == nil {
  781. expect := "250 enable.test.com Hello"
  782. if strings.Index(result, expect) != 0 {
  783. t.Error("Expected", expect, "but got", result)
  784. }
  785. } else {
  786. t.Error(err)
  787. }
  788. if err = conn.Close(); err != nil {
  789. t.Error(err)
  790. }
  791. }
  792. // now disable the server
  793. newerConf := newConf // copy the cmdConfg
  794. newerConf.Servers[1].IsEnabled = false
  795. if jsonbytes, err := json.Marshal(newerConf); err == nil {
  796. //fmt.Println(string(jsonbytes))
  797. if err = ioutil.WriteFile("configJsonA.json", []byte(jsonbytes), 0644); err != nil {
  798. t.Error(err)
  799. }
  800. } else {
  801. t.Error(err)
  802. }
  803. // send a sighup signal to the server
  804. sigHup()
  805. // detect config change
  806. if _, err := grepTestlog("Server [127.0.0.1:2228] has stopped accepting new clients", 27); err != nil {
  807. t.Error("127.0.0.1:2228 did not stop")
  808. }
  809. // it should not connect to the server
  810. if _, _, err := test.Connect(newConf.Servers[1], 20); err == nil {
  811. t.Error("127.0.0.1:2228 was disabled, but still accepting connections", newConf.Servers[1].ListenInterface)
  812. }
  813. // shutdown wait for exit
  814. d.Shutdown()
  815. // wait for shutdown
  816. if _, err := grepTestlog("Backend shutdown completed", 0); err != nil {
  817. t.Error("server didn't stop")
  818. }
  819. }
  820. // just a utility for debugging when using the debugger, skipped by default
  821. func TestDebug(t *testing.T) {
  822. t.SkipNow()
  823. conf := guerrilla.ServerConfig{ListenInterface: "127.0.0.1:2526"}
  824. if conn, buffin, err := test.Connect(conf, 20); err != nil {
  825. t.Error("Could not connect to new server", conf.ListenInterface, err)
  826. } else {
  827. if result, err := test.Command(conn, buffin, "HELO"); err == nil {
  828. expect := "250 mai1.guerrillamail.com Hello"
  829. if strings.Index(result, expect) != 0 {
  830. t.Error("Expected", expect, "but got", result)
  831. } else {
  832. if result, err = test.Command(conn, buffin, "RCPT TO:<[email protected]>"); err == nil {
  833. expect := "250 2.1.5 OK"
  834. if strings.Index(result, expect) != 0 {
  835. t.Error("Expected:", expect, "but got:", result)
  836. }
  837. }
  838. }
  839. }
  840. _ = conn.Close()
  841. }
  842. }
  843. // Start with configJsonD.json,
  844. // then connect to 127.0.0.1:4655 & HELO & try RCPT TO with an invalid host [grr.la]
  845. // then change the config to enable add new host [grr.la] to allowed_hosts
  846. // then write the new config,
  847. // then SIGHUP (to reload config & trigger config update events),
  848. // connect to 127.0.0.1:4655 & HELO & try RCPT TO, grr.la should work
  849. func TestAllowedHostsEvent(t *testing.T) {
  850. var err error
  851. err = testcert.GenerateCert("mail2.guerrillamail.com", "", 365*24*time.Hour, false, 2048, "P256", "../../tests/")
  852. if err != nil {
  853. t.Error("failed to generate a test certificate", err)
  854. t.FailNow()
  855. }
  856. defer cleanTestArtifacts(t)
  857. mainlog, err = getTestLog()
  858. if err != nil {
  859. t.Error("could not get logger,", err)
  860. t.FailNow()
  861. }
  862. if err := ioutil.WriteFile("configJsonD.json", []byte(configJsonD), 0644); err != nil {
  863. t.Error(err)
  864. t.FailNow()
  865. }
  866. // start the server by emulating the serve command
  867. conf := &guerrilla.AppConfig{} // blank one
  868. if err = conf.Load([]byte(configJsonD)); err != nil { // load configJsonD
  869. t.Error(err)
  870. }
  871. cmd := &cobra.Command{}
  872. configPath = "configJsonD.json"
  873. go func() {
  874. serve(cmd, []string{})
  875. }()
  876. // wait for start
  877. if _, err := grepTestlog("Listening on TCP 127.0.0.1:2552", 0); err != nil {
  878. t.Error("server didn't start")
  879. }
  880. // now connect and try RCPT TO with an invalid host
  881. if conn, buffin, err := test.Connect(conf.Servers[1], 20); err != nil {
  882. t.Error("Could not connect to new server", conf.Servers[1].ListenInterface, err)
  883. } else {
  884. if result, err := test.Command(conn, buffin, "HELO"); err == nil {
  885. expect := "250 secure.test.com Hello"
  886. if strings.Index(result, expect) != 0 {
  887. t.Error("Expected", expect, "but got", result)
  888. } else {
  889. if result, err = test.Command(conn, buffin, "RCPT TO:<[email protected]>"); err == nil {
  890. expect := "454 4.1.1 Error: Relay access denied: grr.la"
  891. if strings.Index(result, expect) != 0 {
  892. t.Error("Expected:", expect, "but got:", result)
  893. }
  894. }
  895. }
  896. }
  897. _ = conn.Close()
  898. }
  899. // now change the config by adding a host to allowed hosts
  900. newConf := conf
  901. newConf.AllowedHosts = append(newConf.AllowedHosts, "grr.la")
  902. if jsonbytes, err := json.Marshal(newConf); err == nil {
  903. if err = ioutil.WriteFile("configJsonD.json", []byte(jsonbytes), 0644); err != nil {
  904. t.Error(err)
  905. }
  906. } else {
  907. t.Error(err)
  908. }
  909. // send a sighup signal to the server to reload config
  910. sigHup()
  911. if _, err := grepTestlog("allowed_hosts config changed", 0); err != nil {
  912. t.Error("allowed_hosts config not changed")
  913. t.FailNow()
  914. }
  915. // now repeat the same conversion, RCPT TO should be accepted
  916. if conn, buffin, err := test.Connect(conf.Servers[1], 20); err != nil {
  917. t.Error("Could not connect to new server", conf.Servers[1].ListenInterface, err)
  918. } else {
  919. if result, err := test.Command(conn, buffin, "HELO"); err == nil {
  920. expect := "250 secure.test.com Hello"
  921. if strings.Index(result, expect) != 0 {
  922. t.Error("Expected", expect, "but got", result)
  923. } else {
  924. if result, err = test.Command(conn, buffin, "RCPT TO:<[email protected]>"); err == nil {
  925. expect := "250 2.1.5 OK"
  926. if strings.Index(result, expect) != 0 {
  927. t.Error("Expected:", expect, "but got:", result)
  928. }
  929. }
  930. }
  931. }
  932. _ = conn.Close()
  933. }
  934. // shutdown wait for exit
  935. d.Shutdown()
  936. // wait for shutdown
  937. if _, err := grepTestlog("Backend shutdown completed", 0); err != nil {
  938. t.Error("server didn't stop")
  939. }
  940. }
  941. // Test TLS config change event
  942. // start with configJsonD
  943. // should be able to STARTTLS to 127.0.0.1:2525 with no problems
  944. // generate new certs & reload config
  945. // should get a new tls event & able to STARTTLS with no problem
  946. func TestTLSConfigEvent(t *testing.T) {
  947. var err error
  948. err = testcert.GenerateCert("mail2.guerrillamail.com", "", 365*24*time.Hour, false, 2048, "P256", "../../tests/")
  949. if err != nil {
  950. t.Error("failed to generate a test certificate", err)
  951. t.FailNow()
  952. }
  953. defer cleanTestArtifacts(t)
  954. mainlog, err = getTestLog()
  955. if err != nil {
  956. t.Error("could not get logger,", err)
  957. t.FailNow()
  958. }
  959. if err := ioutil.WriteFile("configJsonD.json", []byte(configJsonD), 0644); err != nil {
  960. t.Error(err)
  961. t.FailNow()
  962. }
  963. conf := &guerrilla.AppConfig{} // blank one
  964. if err = conf.Load([]byte(configJsonD)); err != nil { // load configJsonD
  965. t.Error(err)
  966. t.FailNow()
  967. }
  968. cmd := &cobra.Command{}
  969. configPath = "configJsonD.json"
  970. go func() {
  971. serve(cmd, []string{})
  972. }()
  973. // wait for server to start
  974. if _, err := grepTestlog("Listening on TCP 127.0.0.1:2552", 0); err != nil {
  975. t.Error("server didn't start")
  976. }
  977. // Test STARTTLS handshake
  978. testTlsHandshake := func() {
  979. if conn, buffin, err := test.Connect(conf.Servers[0], 20); err != nil {
  980. t.Error("Could not connect to server", conf.Servers[0].ListenInterface, err)
  981. } else {
  982. if result, err := test.Command(conn, buffin, "HELO"); err == nil {
  983. expect := "250 mail.test.com Hello"
  984. if strings.Index(result, expect) != 0 {
  985. t.Error("Expected", expect, "but got", result)
  986. } else {
  987. if result, err = test.Command(conn, buffin, "STARTTLS"); err == nil {
  988. expect := "220 2.0.0 Ready to start TLS"
  989. if strings.Index(result, expect) != 0 {
  990. t.Error("Expected:", expect, "but got:", result)
  991. } else {
  992. tlsConn := tls.Client(conn, &tls.Config{
  993. InsecureSkipVerify: true,
  994. ServerName: "127.0.0.1",
  995. })
  996. if err := tlsConn.Handshake(); err != nil {
  997. t.Error("Failed to handshake", conf.Servers[0].ListenInterface)
  998. } else {
  999. conn = tlsConn
  1000. mainlog.Info("TLS Handshake succeeded")
  1001. }
  1002. }
  1003. }
  1004. }
  1005. }
  1006. _ = conn.Close()
  1007. }
  1008. }
  1009. testTlsHandshake()
  1010. // TLS Handshake succeeded?
  1011. if _, err := grepTestlog("TLS Handshake succeeded", 0); err != nil {
  1012. t.Error("TLS Handshake did not succeed")
  1013. t.FailNow()
  1014. }
  1015. // now delete old certs, configure new certs, and send a sighup to load them in
  1016. if err := deleteIfExists("../../tests/mail2.guerrillamail.com.cert.pem"); err != nil {
  1017. t.Error("could not delete ../../tests/mail2.guerrillamail.com.cert.pem", err)
  1018. }
  1019. if err := deleteIfExists("../../tests/mail2.guerrillamail.com.key.pem"); err != nil {
  1020. t.Error("could not delete ../../tests/mail2.guerrillamail.com.key.pem", err)
  1021. }
  1022. time.Sleep(testPauseDuration) // need to pause so that the new certs have different timestamps!
  1023. // generate a new cert
  1024. err = testcert.GenerateCert("mail2.guerrillamail.com", "", 365*24*time.Hour, false, 2048, "P256", "../../tests/")
  1025. if err != nil {
  1026. t.Error("failed to generate a test certificate", err)
  1027. t.FailNow()
  1028. }
  1029. // pause for generated cert to output (don't need, since we've fsynced)
  1030. // time.Sleep(testPauseDuration) // (don't need, since we've fsynced)
  1031. // did cert output?
  1032. if _, err := os.Stat("../../tests/mail2.guerrillamail.com.cert.pem"); err != nil {
  1033. t.Error("Did not create cert ", err)
  1034. }
  1035. sigHup()
  1036. // wait for config to reload
  1037. if _, err := grepTestlog("Server [127.0.0.1:4655] re-opened", 0); err != nil {
  1038. t.Error("server didn't catch sighup")
  1039. }
  1040. // did tls configuration reload as expected?
  1041. if _, err := grepTestlog("new TLS configuration loaded", 0); err != nil {
  1042. t.Error("server didn't catch sighup")
  1043. }
  1044. // test again
  1045. testTlsHandshake()
  1046. // after line 25
  1047. if _, err := grepTestlog("TLS Handshake succeeded", 25); err != nil {
  1048. t.Error("TLS Handshake did not succeed")
  1049. t.FailNow()
  1050. }
  1051. d.Shutdown()
  1052. // wait for shutdown
  1053. if _, err := grepTestlog("Backend shutdown completed", 0); err != nil {
  1054. t.Error("server didn't stop")
  1055. }
  1056. }
  1057. // Testing starting a server with a bad TLS config
  1058. // It should not start, return exit code 1
  1059. func TestBadTLSStart(t *testing.T) {
  1060. var err error
  1061. mainlog, err = getTestLog()
  1062. if err != nil {
  1063. t.Error("could not get logger,", err)
  1064. t.FailNow()
  1065. }
  1066. // Need to run the test in a different process by executing a command
  1067. // because the serve() does os.Exit when starting with a bad TLS config
  1068. if os.Getenv("BE_CRASHER") == "1" {
  1069. // do the test
  1070. // first, remove the good certs, if any
  1071. if err := deleteIfExists("../../tests/mail2.guerrillamail.com.cert.pem"); err != nil {
  1072. t.Error("could not delete ../../tests/mail2.guerrillamail.com.cert.pem", err)
  1073. }
  1074. if err := deleteIfExists("../../tests/mail2.guerrillamail.com.key.pem"); err != nil {
  1075. t.Error("could not delete ../../tests/mail2.guerrillamail.com.key.pem", err)
  1076. }
  1077. // next run the server
  1078. if err = ioutil.WriteFile("configJsonD.json", []byte(configJsonD), 0644); err != nil {
  1079. t.Error(err)
  1080. }
  1081. conf := &guerrilla.AppConfig{} // blank one
  1082. if err = conf.Load([]byte(configJsonD)); err != nil { // load configJsonD
  1083. t.Error(err)
  1084. }
  1085. cmd := &cobra.Command{}
  1086. configPath = "configJsonD.json"
  1087. var serveWG sync.WaitGroup
  1088. serveWG.Add(1)
  1089. go func() {
  1090. serve(cmd, []string{})
  1091. serveWG.Done()
  1092. }()
  1093. // it should exit by now because the TLS config is incorrect
  1094. time.Sleep(testPauseDuration)
  1095. sigKill()
  1096. serveWG.Wait()
  1097. return
  1098. }
  1099. defer cleanTestArtifacts(t)
  1100. cmd := exec.Command(os.Args[0], "-test.run=TestBadTLSStart")
  1101. cmd.Env = append(os.Environ(), "BE_CRASHER=1")
  1102. err = cmd.Run()
  1103. if e, ok := err.(*exec.ExitError); ok && !e.Success() {
  1104. if _, err := grepTestlog("level=fatal", 0); err != nil {
  1105. t.Error("server didn't exit with a fatal error")
  1106. }
  1107. return
  1108. }
  1109. t.Error("Server started with a bad TLS config, was expecting exit status 0")
  1110. }
  1111. // Test config reload with a bad TLS config
  1112. // It should ignore the config reload, keep running with old settings
  1113. func TestBadTLSReload(t *testing.T) {
  1114. var err error
  1115. mainlog, err = getTestLog()
  1116. if err != nil {
  1117. t.Error("could not get logger,", err)
  1118. t.FailNow()
  1119. }
  1120. defer cleanTestArtifacts(t)
  1121. // start with a good cert
  1122. err = testcert.GenerateCert("mail2.guerrillamail.com", "", 365*24*time.Hour, false, 2048, "P256", "../../tests/")
  1123. if err != nil {
  1124. t.Error("failed to generate a test certificate", err)
  1125. t.FailNow()
  1126. }
  1127. // start the server by emulating the serve command
  1128. if err = ioutil.WriteFile("configJsonD.json", []byte(configJsonD), 0644); err != nil {
  1129. t.Error(err)
  1130. t.FailNow()
  1131. }
  1132. conf := &guerrilla.AppConfig{} // blank one
  1133. if err = conf.Load([]byte(configJsonD)); err != nil { // load configJsonD
  1134. t.Error(err)
  1135. t.FailNow()
  1136. }
  1137. cmd := &cobra.Command{}
  1138. configPath = "configJsonD.json"
  1139. go func() {
  1140. serve(cmd, []string{})
  1141. }()
  1142. // wait for server to start
  1143. if _, err := grepTestlog("Listening on TCP 127.0.0.1:4655", 0); err != nil {
  1144. t.Error("server didn't start")
  1145. }
  1146. if conn, buffin, err := test.Connect(conf.Servers[0], 20); err != nil {
  1147. t.Error("Could not connect to server", conf.Servers[0].ListenInterface, err)
  1148. } else {
  1149. if result, err := test.Command(conn, buffin, "HELO"); err == nil {
  1150. expect := "250 mail.test.com Hello"
  1151. if strings.Index(result, expect) != 0 {
  1152. t.Error("Expected", expect, "but got", result)
  1153. }
  1154. }
  1155. }
  1156. // write some trash data
  1157. if err = ioutil.WriteFile("./../../tests/mail2.guerrillamail.com.cert.pem",
  1158. []byte("trash data"),
  1159. 0664); err != nil {
  1160. t.Error(err)
  1161. }
  1162. if err = ioutil.WriteFile("./../../tests/mail2.guerrillamail.com.key.pem",
  1163. []byte("trash data"),
  1164. 0664); err != nil {
  1165. t.Error(err)
  1166. }
  1167. newConf := conf // copy the cmdConfg
  1168. if jsonbytes, err := json.Marshal(newConf); err == nil {
  1169. if err = ioutil.WriteFile("configJsonD.json", []byte(jsonbytes), 0644); err != nil {
  1170. t.Error(err)
  1171. }
  1172. } else {
  1173. t.Error(err)
  1174. }
  1175. // send a sighup signal to the server to reload config
  1176. sigHup()
  1177. // did the config reload reload event fire? There should be config read error
  1178. if _, err := grepTestlog("could not read config file", 0); err != nil {
  1179. t.Error("was expecting an error reading config")
  1180. }
  1181. // we should still be able to to talk to it
  1182. if conn, buffin, err := test.Connect(conf.Servers[0], 20); err != nil {
  1183. t.Error("Could not connect to server", conf.Servers[0].ListenInterface, err)
  1184. } else {
  1185. if result, err := test.Command(conn, buffin, "HELO"); err == nil {
  1186. expect := "250 mail.test.com Hello"
  1187. if strings.Index(result, expect) != 0 {
  1188. t.Error("Expected", expect, "but got", result)
  1189. }
  1190. }
  1191. }
  1192. // shutdown & wait for exit
  1193. d.Shutdown()
  1194. // wait for shutdown
  1195. if _, err := grepTestlog("Backend shutdown completed", 0); err != nil {
  1196. t.Error("server didn't stop")
  1197. }
  1198. }
  1199. // Test for when the server config Timeout value changes
  1200. // Start with configJsonD.json
  1201. func TestSetTimeoutEvent(t *testing.T) {
  1202. var err error
  1203. mainlog, err = getTestLog()
  1204. if err != nil {
  1205. t.Error("could not get logger,", err)
  1206. t.FailNow()
  1207. }
  1208. defer cleanTestArtifacts(t)
  1209. err = testcert.GenerateCert("mail2.guerrillamail.com", "", 365*24*time.Hour, false, 2048, "P256", "../../tests/")
  1210. if err != nil {
  1211. t.Error("failed to generate a test certificate", err)
  1212. t.FailNow()
  1213. }
  1214. // start the server by emulating the serve command
  1215. if err = ioutil.WriteFile("configJsonD.json", []byte(configJsonD), 0644); err != nil {
  1216. t.Error(err)
  1217. }
  1218. conf := &guerrilla.AppConfig{} // blank one
  1219. if err = conf.Load([]byte(configJsonD)); err != nil { // load configJsonD
  1220. t.Error(err)
  1221. }
  1222. cmd := &cobra.Command{}
  1223. configPath = "configJsonD.json"
  1224. go func() {
  1225. serve(cmd, []string{})
  1226. }()
  1227. // wait for start
  1228. if _, err := grepTestlog("Listening on TCP 127.0.0.1:4655", 0); err != nil {
  1229. t.Error("server didn't start")
  1230. }
  1231. // set the timeout to 1 second
  1232. newConf := conf // copy the cmdConfg
  1233. newConf.Servers[0].Timeout = 1
  1234. if jsonbytes, err := json.Marshal(newConf); err == nil {
  1235. if err = ioutil.WriteFile("configJsonD.json", []byte(jsonbytes), 0644); err != nil {
  1236. t.Error(err)
  1237. }
  1238. } else {
  1239. t.Error(err)
  1240. }
  1241. // send a sighup signal to the server to reload config
  1242. sigHup()
  1243. // did config update?
  1244. if _, err := grepTestlog("a new config has been saved", 0); err != nil {
  1245. t.Error("config didn't update")
  1246. }
  1247. var waitTimeout sync.WaitGroup
  1248. if conn, buffin, err := test.Connect(conf.Servers[0], 20); err != nil {
  1249. t.Error("Could not connect to server", conf.Servers[0].ListenInterface, err)
  1250. } else {
  1251. waitTimeout.Add(1)
  1252. go func() {
  1253. if result, err := test.Command(conn, buffin, "HELO"); err == nil {
  1254. expect := "250 mail.test.com Hello"
  1255. if strings.Index(result, expect) != 0 {
  1256. t.Error("Expected", expect, "but got", result)
  1257. } else {
  1258. b := make([]byte, 1024)
  1259. _, _ = conn.Read(b)
  1260. }
  1261. }
  1262. waitTimeout.Done()
  1263. }()
  1264. }
  1265. // wait for timeout
  1266. waitTimeout.Wait()
  1267. d.Shutdown()
  1268. // wait for shutdown
  1269. if _, err := grepTestlog("Backend shutdown completed", 0); err != nil {
  1270. t.Error("server didn't stop")
  1271. }
  1272. // so the connection we have opened should timeout by now
  1273. // did we get timeout as expected?
  1274. if _, err := grepTestlog("i/o timeout", 0); err != nil {
  1275. t.Error("it looks like the timeout config didnt change")
  1276. t.FailNow()
  1277. }
  1278. }
  1279. // Test debug level config change
  1280. // Start in log_level = debug
  1281. // Load config & start server
  1282. func TestDebugLevelChange(t *testing.T) {
  1283. var err error
  1284. mainlog, err = getTestLog()
  1285. if err != nil {
  1286. t.Error("could not get logger,", err)
  1287. t.FailNow()
  1288. }
  1289. defer cleanTestArtifacts(t)
  1290. err = testcert.GenerateCert("mail2.guerrillamail.com", "", 365*24*time.Hour, false, 2048, "P256", "../../tests/")
  1291. if err != nil {
  1292. t.Error("failed to generate a test certificate", err)
  1293. t.FailNow()
  1294. } // start the server by emulating the serve command
  1295. if err = ioutil.WriteFile("configJsonD.json", []byte(configJsonD), 0644); err != nil {
  1296. t.Error(err)
  1297. }
  1298. conf := &guerrilla.AppConfig{} // blank one
  1299. if err = conf.Load([]byte(configJsonD)); err != nil { // load configJsonD
  1300. t.Error(err)
  1301. }
  1302. conf.LogLevel = "debug"
  1303. cmd := &cobra.Command{}
  1304. configPath = "configJsonD.json"
  1305. go func() {
  1306. serve(cmd, []string{})
  1307. }()
  1308. if _, err := grepTestlog("Listening on TCP 127.0.0.1:2552", 0); err != nil {
  1309. t.Error("server didn't start")
  1310. }
  1311. if conn, buffin, err := test.Connect(conf.Servers[0], 20); err != nil {
  1312. t.Error("Could not connect to server", conf.Servers[0].ListenInterface, err)
  1313. } else {
  1314. if result, err := test.Command(conn, buffin, "HELO"); err == nil {
  1315. expect := "250 mail.test.com Hello"
  1316. if strings.Index(result, expect) != 0 {
  1317. t.Error("Expected", expect, "but got", result)
  1318. }
  1319. }
  1320. _ = conn.Close()
  1321. }
  1322. // set the log_level to info
  1323. newConf := conf // copy the cmdConfg
  1324. newConf.LogLevel = log.InfoLevel.String()
  1325. if jsonbytes, err := json.Marshal(newConf); err == nil {
  1326. if err = ioutil.WriteFile("configJsonD.json", []byte(jsonbytes), 0644); err != nil {
  1327. t.Error(err)
  1328. }
  1329. } else {
  1330. t.Error(err)
  1331. }
  1332. // send a sighup signal to the server to reload config
  1333. sigHup()
  1334. // did the config reload?
  1335. if _, err := grepTestlog("Configuration was reloaded", 0); err != nil {
  1336. t.Error("config did not reload")
  1337. t.FailNow()
  1338. }
  1339. // connect again, this time we should see info
  1340. if conn, buffin, err := test.Connect(conf.Servers[0], 20); err != nil {
  1341. t.Error("Could not connect to server", conf.Servers[0].ListenInterface, err)
  1342. } else {
  1343. if result, err := test.Command(conn, buffin, "NOOP"); err == nil {
  1344. expect := "200 2.0.0 OK"
  1345. if strings.Index(result, expect) != 0 {
  1346. t.Error("Expected", expect, "but got", result)
  1347. }
  1348. }
  1349. _ = conn.Close()
  1350. }
  1351. d.Shutdown()
  1352. // did the log level change to info?
  1353. if _, err := grepTestlog("log level changed to [info]", 0); err != nil {
  1354. t.Error("log level did not change to [info]")
  1355. t.FailNow()
  1356. }
  1357. }
  1358. // When reloading with a bad backend config, it should revert to old backend config
  1359. func TestBadBackendReload(t *testing.T) {
  1360. var err error
  1361. err = testcert.GenerateCert("mail2.guerrillamail.com", "", 365*24*time.Hour, false, 2048, "P256", "../../tests/")
  1362. if err != nil {
  1363. t.Error("failed to generate a test certificate", err)
  1364. t.FailNow()
  1365. }
  1366. defer cleanTestArtifacts(t)
  1367. mainlog, err = getTestLog()
  1368. if err != nil {
  1369. t.Error("could not get logger,", err)
  1370. t.FailNow()
  1371. }
  1372. if err = ioutil.WriteFile("configJsonA.json", []byte(configJsonA), 0644); err != nil {
  1373. t.Error(err)
  1374. }
  1375. cmd := &cobra.Command{}
  1376. configPath = "configJsonA.json"
  1377. go func() {
  1378. serve(cmd, []string{})
  1379. }()
  1380. if _, err := grepTestlog("Listening on TCP 127.0.0.1:3536", 0); err != nil {
  1381. t.Error("server didn't start")
  1382. }
  1383. // change the config file to the one with a broken backend
  1384. if err = ioutil.WriteFile("configJsonA.json", []byte(configJsonE), 0644); err != nil {
  1385. t.Error(err)
  1386. }
  1387. // test SIGHUP via the kill command
  1388. // Would not work on windows as kill is not available.
  1389. // TODO: Implement an alternative test for windows.
  1390. if runtime.GOOS != "windows" {
  1391. sigHup()
  1392. // did config update?
  1393. if _, err := grepTestlog("Configuration was reloaded", 0); err != nil {
  1394. t.Error("config didn't update")
  1395. }
  1396. // did the pidfile change as expected?
  1397. if _, err := grepTestlog("pid_file (./pidfile2.pid) written", 0); err != nil {
  1398. t.Error("pid_file (./pidfile2.pid) not written")
  1399. }
  1400. if _, err := os.Stat("./pidfile2.pid"); os.IsNotExist(err) {
  1401. t.Error("pidfile not changed after sighup SIGHUP", err)
  1402. }
  1403. }
  1404. // send kill signal and wait for exit
  1405. d.Shutdown()
  1406. // did backend started as expected?
  1407. if _, err := grepTestlog("reverted to old backend config", 0); err != nil {
  1408. t.Error("did not revert to old backend config")
  1409. t.FailNow()
  1410. }
  1411. }