package main import ( "bytes" "encoding/json" "io/ioutil" "log" "net/http" "net/smtp" "text/template" "time" ) func (c *vpnSession) LogPrintln(v ...interface{}) { log.Println(c.Login, c.IP, v) } func (s *OpenVpnMgt) Log(c *vpnSession) error { if s.vpnlogUrl != "" { if err := c.getASInfos(s.vpnlogUrl); err != nil { log.Println(err) } } c.Time = time.Now().Round(time.Second) jsonStr, err := json.Marshal(c) if err != nil { return err } log.Println(string(jsonStr)) if err := s.SendMail(c); err != nil { log.Println(err) } return nil } func (c *vpnSession) getASInfos(vpnlogUrl string) error { jsonStr, err := json.Marshal(c) if err != nil { return err } req, err := http.NewRequest("POST", vpnlogUrl, bytes.NewBuffer(jsonStr)) req.Header.Set("Content-Type", "application/json") timeout := time.Duration(3 * time.Second) client := http.Client{ Timeout: timeout, } resp, err := client.Do(req) if err != nil { return err } defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) err = json.Unmarshal(body, c) if err != nil { return err } return nil } func (s *OpenVpnMgt) MailTemplate(c *vpnSession) error { var buf1 bytes.Buffer var buf2 bytes.Buffer tmpl, err := template.New("pwnTemplate").Parse(s.pwnTemplate) if err != nil { return err } if err := tmpl.Execute(&buf1, c); err != nil { return err } c.pwnMail = buf1.String() tmpl, err = template.New("newAsTemplate").Parse(s.newAsTemplate) if err != nil { return err } if err := tmpl.Execute(&buf2, c); err != nil { return err } c.newAsMail = buf2.String() return nil } func (s *OpenVpnMgt) SendMail(c *vpnSession) error { if c.Mail == "" { return nil } if (s.newAsTemplate == "" || !c.NewAS) && (s.pwnTemplate == "" || !c.PwnedPasswd) { // can not send mail without template or cause return nil } // needed for the templating c.MailFrom = s.MailFrom c.CcPwnPassword = s.CcPwnPassword // complete the templates if err := s.MailTemplate(c); err != nil { return err } mail, err := smtp.Dial(s.mailRelay) if err != nil { return err } defer mail.Close() if c.PwnedPasswd { mail.Mail(s.MailFrom) mail.Rcpt(c.Mail) if c.TooMuchPwn && s.CcPwnPassword != "" { mail.Rcpt(s.CcPwnPassword) } wc, err := mail.Data() if err != nil { return nil } defer wc.Close() buf := bytes.NewBufferString(c.pwnMail) if _, err = buf.WriteTo(wc); err != nil { return err } wc.Close() } if c.NewAS { mail.Mail(s.MailFrom) mail.Rcpt(c.Mail) wc, err := mail.Data() if err != nil { return nil } defer wc.Close() buf := bytes.NewBufferString(c.newAsMail) if _, err = buf.WriteTo(wc); err != nil { return err } wc.Close() } return nil }