예제 #1
0
파일: smtp.go 프로젝트: wk66/grafana
func (c *smtpSender) Send(from string, to []string, msg io.WriterTo) error {
	if err := c.Mail(from); err != nil {
		if err == io.EOF {
			// This is probably due to a timeout, so reconnect and try again.
			sc, derr := c.d.Dial()
			if derr == nil {
				if s, ok := sc.(*smtpSender); ok {
					*c = *s
					return c.Send(from, to, msg)
				}
			}
		}
		return err
	}

	for _, addr := range to {
		if err := c.Rcpt(addr); err != nil {
			return err
		}
	}

	w, err := c.Data()
	if err != nil {
		return err
	}

	if _, err = msg.WriteTo(w); err != nil {
		w.Close()
		return err
	}

	return w.Close()
}
예제 #2
0
// Redirect -- only accessible if method == POST
func (p *wmDecisionCore) doV3n11() WMDecision {
	var postIsCreate bool
	var httpCode int
	var httpError error
	var httpHeaders http.Header
	var writerTo io.WriterTo
	postIsCreate, p.req, p.cxt, httpCode, httpError = p.handler.PostIsCreate(p.req, p.cxt)
	if httpCode > 0 {
		p.writeHaltOrError(httpCode, httpError)
		return wmResponded
	}
	if postIsCreate {
		log.Print("[WM]: v3n11: Creating Path\n")
		_, p.req, p.cxt, httpCode, httpError = p.handler.CreatePath(p.req, p.cxt)
		if httpCode > 0 {
			p.writeHaltOrError(httpCode, httpError)
			return wmResponded
		}
		log.Print("[WM]: v3n11: Running Accept Helper\n")
		if p.runAcceptHelper() {
			return wmResponded
		}
	} else {
		log.Print("[WM]: v3n11: Running Process Post\n")
		p.req, p.cxt, httpCode, httpHeaders, writerTo, httpError = p.handler.ProcessPost(p.req, p.cxt)
		if httpCode > 0 {
			p.updateHttpResponseHeaders(httpHeaders)
			if httpError != nil {
				p.writeHaltOrError(httpCode, httpError)
			} else if writerTo != nil {
				p.resp.WriteHeader(httpCode)
				writerTo.WriteTo(p.resp)
			} else {
				p.resp.WriteHeader(httpCode)
			}
			return wmResponded
		}
		// TODO Aalok check what should be done here
		//p.resp.WriteHeader(n)
		//log.Print("Wrote Header but may not return wmResponded in doV3n11()\n")
		//p.encodeBodyIfSet()
	}
	log.Print("[WM]: v3n11: Running Response is Redirect?\n")
	var respIsRedirect bool
	respIsRedirect, p.req, p.cxt, httpCode, httpError = p.handler.ResponseIsRedirect(p.req, p.cxt)
	if httpCode > 0 {
		p.writeHaltOrError(httpCode, httpError)
		return wmResponded
	}
	if respIsRedirect {
		if len(p.resp.Header().Get("Location")) > 0 {
			p.resp.WriteHeader(http.StatusSeeOther)
		} else {
			p.resp.WriteHeader(http.StatusInternalServerError)
			io.WriteString(p.resp, "Response had do_redirect but no Location")
		}
		return wmResponded
	}
	return v3p11
}
예제 #3
0
파일: main.go 프로젝트: WalterShe/captcha
func main() {
	flag.Parse()
	fname := flag.Arg(0)
	if fname == "" {
		usage()
		os.Exit(1)
	}
	f, err := os.Create(fname)
	if err != nil {
		log.Fatalf("%s", err)
	}
	defer f.Close()
	var w io.WriterTo
	d := captcha.RandomDigits(*flagLen)
	switch {
	case *flagAudio:
		w = captcha.NewAudio(d, *flagLang)
	case *flagImage:
		w = captcha.NewImage(d, *flagImgW, *flagImgH)
	}
	_, err = w.WriteTo(f)
	if err != nil {
		log.Fatalf("%s", err)
	}
	fmt.Println(d)
}
예제 #4
0
func stringifyWriterTo(w io.WriterTo) (string, error) {
	var buf bytes.Buffer
	_, err := w.WriteTo(&buf)
	if err != nil {
		return "", err
	}
	return buf.String(), nil
}
예제 #5
0
func writeFile(dst string, src io.WriterTo) (int64, error) {
	f, err := os.Create(dst)
	if err != nil {
		return 0, fmt.Errorf("error creating file %q: %v", dst, err)
	}
	defer fi.SafeClose(f)
	return src.WriteTo(f)
}
예제 #6
0
파일: writer.go 프로젝트: BenLubar/bit
func writeTo(w io.Writer, wt io.WriterTo, n *int64, err *error) {
	if *err != nil {
		return
	}
	var nn int64
	nn, *err = wt.WriteTo(w)
	*n += nn
}
예제 #7
0
파일: daemon.go 프로젝트: hafeez3000/csfw
func offlineSend(from string, to []string, msg io.WriterTo) error {
	if OfflineLogger.IsInfo() {
		var buf bytes.Buffer
		if _, err := msg.WriteTo(&buf); err != nil {
			return log.Error("mail.daemon.OfflineSend", "err", err, "buf", buf.String(), "message", msg)
		}
		OfflineLogger.Info("mail.Send", "from", from, "to", to, "msg", buf.String())
	}
	return nil
}
예제 #8
0
// writeToFile creates the specified output file from the contents of w.
func writeToFile(ctx context.Context, w io.WriterTo, path string) error {
	f, err := os.Create(path)
	if err != nil {
		return err
	}
	if _, err := w.WriteTo(f); err != nil {
		f.Close()
		return err
	}
	return f.Close()
}
예제 #9
0
func (msc mockSendCloser) Send(from string, to []string, msg io.WriterTo) error {
	assert.NotEmpty(msc.t, from)
	assert.NotEmpty(msc.t, to)

	var buf bytes.Buffer
	msg.WriteTo(&buf)
	assert.NotEmpty(msc.t, buf.String())

	//msc.t.Log(buf.String())

	return msc.sendErr
}
예제 #10
0
파일: smtp.go 프로젝트: rmasoni/heim
func (s *SMTPDeliverer) Deliver(ctx scope.Context, from, to string, email io.WriterTo) error {
	// Connect and authenticate to SMTP server.
	c, err := smtp.Dial(s.addr)
	if err != nil {
		return fmt.Errorf("%s: dial error: %s", s, err)
	}
	defer c.Quit()

	if err := c.Hello(s.localName); err != nil {
		return fmt.Errorf("%s: ehlo error: %s", s, err)
	}

	if s.tlsConfig != nil {
		if err := c.StartTLS(s.tlsConfig); err != nil {
			return fmt.Errorf("%s: starttls error: %s", s, err)
		}
	}

	if s.auth != nil {
		if err := c.Auth(s.auth); err != nil {
			return fmt.Errorf("%s: auth error: %s", s, err)
		}
	}

	// Send email.
	if from == "" {
		from = "noreply@" + s.localName
	}
	if err := c.Mail(from); err != nil {
		return fmt.Errorf("%s: mail error: %s", s, err)
	}

	if err := c.Rcpt(to); err != nil {
		return fmt.Errorf("%s: rcpt error: %s", s, err)
	}

	wc, err := c.Data()
	if err != nil {
		return fmt.Errorf("%s: data error: %s", s, err)
	}

	if _, err := email.WriteTo(wc); err != nil {
		return fmt.Errorf("%s: write error: %s", s, err)
	}
	if err := wc.Close(); err != nil {
		return fmt.Errorf("%s: close error: %s", s, err)
	}

	return nil
}
예제 #11
0
파일: deliverer.go 프로젝트: rmasoni/heim
func (td *TestDeliverer) Deliver(ctx scope.Context, from, to string, email io.WriterTo) error {
	td.Lock()
	defer td.Unlock()

	buf := &bytes.Buffer{}
	if _, err := email.WriteTo(buf); err != nil {
		return err
	}

	if ch, ok := td.channels[to]; ok {
		ch <- buf.Bytes()
	} else {
		fmt.Printf("delivered:\n%s\n", buf.String())
	}

	return nil
}
예제 #12
0
func gen(fname string) (Id string) {

	f, err := os.Create(fname)
	if err != nil {
		log.Fatalf("%s", err)
	}
	defer f.Close()
	var w io.WriterTo
	d := captcha.RandomDigits(6) // six digits is enough
	w = captcha.NewImage(d, captcha.StdWidth, captcha.StdHeight)
	_, err = w.WriteTo(f)
	if err != nil {
		log.Fatalf("%s", err)
	}
	log.Println("DEBUG Captcha: Created new image ", d)
	str := trans(d)
	return str
}
예제 #13
0
파일: buffers.go 프로젝트: basvanbeek/kit
func stats(w io.WriterTo, regex string, h *generic.Histogram) (sum, final float64) {
	re := regexp.MustCompile(regex)
	buf := &bytes.Buffer{}
	w.WriteTo(buf)
	//fmt.Fprintf(os.Stderr, "%s\n", buf.String())
	s := bufio.NewScanner(buf)
	for s.Scan() {
		match := re.FindStringSubmatch(s.Text())
		f, err := strconv.ParseFloat(match[1], 64)
		if err != nil {
			panic(err)
		}
		sum += f
		final = f
		if h != nil {
			h.Observe(f)
		}
	}
	return sum, final
}
예제 #14
0
파일: io.go 프로젝트: jcantrill/geard
func WriteToPathExclusive(path string, source io.WriterTo, mode os.FileMode) error {
	file, exists, err := OpenFileExclusive(path, mode)
	if err != nil {
		return err
	}
	if exists {
		if _, err := file.Seek(0, 0); err != nil {
			file.Close()
			return err
		}
		if err := file.Truncate(0); err != nil {
			file.Close()
			return err
		}
	}
	if _, err := source.WriteTo(file); err != nil {
		file.Close()
		return err
	}
	return file.Close()
}
예제 #15
0
파일: server.go 프로젝트: zmj/MTG-Drafter
func (serv *Server) HandlePageRequestById(w http.ResponseWriter, r *http.Request) {
	m := draftPageReg.FindStringSubmatch(r.URL.Path)
	if m == nil {
		http.Error(w, "Not found", 404)
		return
	}
	id := m[1]
	fmt.Println("req by id", id)

	var d io.WriterTo
	var ok bool
	d, ok = serv.activeDrafts[id]
	if !ok {
		d, ok = serv.archive.GetDraft(id)
	}
	if !ok {
		//404
	}
	_, err := d.WriteTo(w)
	if err != nil {
		//server error
	}
}
예제 #16
0
파일: smtp.go 프로젝트: rpau/gomail
func (c *smtpSender) Send(from string, to []string, msg io.WriterTo) error {
	if err := c.Mail(from); err != nil {
		return err
	}

	for _, addr := range to {
		if err := c.Rcpt(addr); err != nil {
			return err
		}
	}

	w, err := c.Data()
	if err != nil {
		return err
	}

	if _, err = msg.WriteTo(w); err != nil {
		w.Close()
		return err
	}

	return w.Close()
}
예제 #17
0
func pipeTo(dest io.WriteCloser, src io.WriterTo) (err error) {
	if _, err = src.WriteTo(dest); err != nil {
		return
	}
	return dest.Close()
}
예제 #18
0
func (p *promH) graphHook(w http.ResponseWriter, r *http.Request) {
	q, ok := r.URL.Query()["q"]
	if !ok || len(q) != 1 {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	s, ok := r.URL.Query()["s"]
	if !ok || len(s) != 1 {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	e, ok := r.URL.Query()["e"]
	if !ok || len(e) != 1 {
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	st, _ := strconv.Atoi(s[0])
	et, _ := strconv.Atoi(e[0])

	ctx := r.Context()

	qapi := prom.NewQueryAPI(*p.client)
	d, err := qapi.QueryRange(ctx, q[0], prom.Range{time.Unix(0, int64(st)), time.Unix(0, int64(et)), 15 * time.Second})
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	var mx model.Matrix
	switch d.Type() {
	case model.ValMatrix:
		mx = d.(model.Matrix)
		sort.Sort(mx)
	default:
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	plt, err := plot.New()
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	plt.Title.Text = q[0]
	plt.X.Tick.Marker = plot.UnixTimeTicks{Format: "Mon 15:04:05"}

	for _, ss := range mx {
		for _, sps := range mx {
			err = plotutil.AddLinePoints(plt, ss.Metric.String(), modelToPlot(sps.Values))
			if err != nil {
				w.WriteHeader(http.StatusInternalServerError)
				return
			}
		}
	}

	// Save the plot to a PNG file.
	var wt io.WriterTo
	if wt, err = plt.WriterTo(4*vg.Inch, 2*vg.Inch, "png"); err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "image/png")
	if _, err := wt.WriteTo(w); err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
}
예제 #19
0
func (this *DataWriter) WriteWriterTo(value io.WriterTo) error {
	i, err := value.WriteTo(this.w)
	this.count += int64(i)
	return err
}
예제 #20
0
func (s *Sender) Send(from string, to []string, msg io.WriterTo) error {
	opts := setting.MailService

	host, port, err := net.SplitHostPort(opts.Host)
	if err != nil {
		return err
	}

	tlsconfig := &tls.Config{
		InsecureSkipVerify: opts.SkipVerify,
		ServerName:         host,
	}

	if opts.UseCertificate {
		cert, err := tls.LoadX509KeyPair(opts.CertFile, opts.KeyFile)
		if err != nil {
			return err
		}
		tlsconfig.Certificates = []tls.Certificate{cert}
	}

	conn, err := net.Dial("tcp", net.JoinHostPort(host, port))
	if err != nil {
		return err
	}
	defer conn.Close()

	isSecureConn := false
	// Start TLS directly if the port ends with 465 (SMTPS protocol)
	if strings.HasSuffix(port, "465") {
		conn = tls.Client(conn, tlsconfig)
		isSecureConn = true
	}

	client, err := smtp.NewClient(conn, host)
	if err != nil {
		return fmt.Errorf("NewClient: %v", err)
	}

	if !opts.DisableHelo {
		hostname := opts.HeloHostname
		if len(hostname) == 0 {
			hostname, err = os.Hostname()
			if err != nil {
				return err
			}
		}

		if err = client.Hello(hostname); err != nil {
			return fmt.Errorf("Hello: %v", err)
		}
	}

	// If not using SMTPS, alway use STARTTLS if available
	hasStartTLS, _ := client.Extension("STARTTLS")
	if !isSecureConn && hasStartTLS {
		if err = client.StartTLS(tlsconfig); err != nil {
			return fmt.Errorf("StartTLS: %v", err)
		}
	}

	canAuth, options := client.Extension("AUTH")
	if canAuth && len(opts.User) > 0 {
		var auth smtp.Auth

		if strings.Contains(options, "CRAM-MD5") {
			auth = smtp.CRAMMD5Auth(opts.User, opts.Passwd)
		} else if strings.Contains(options, "PLAIN") {
			auth = smtp.PlainAuth("", opts.User, opts.Passwd, host)
		} else if strings.Contains(options, "LOGIN") {
			// Patch for AUTH LOGIN
			auth = LoginAuth(opts.User, opts.Passwd)
		}

		if auth != nil {
			if err = client.Auth(auth); err != nil {
				return fmt.Errorf("Auth: %v", err)
			}
		}
	}

	if err = client.Mail(from); err != nil {
		return fmt.Errorf("Mail: %v", err)
	}

	for _, rec := range to {
		if err = client.Rcpt(rec); err != nil {
			return fmt.Errorf("Rcpt: %v", err)
		}
	}

	w, err := client.Data()
	if err != nil {
		return fmt.Errorf("Data: %v", err)
	} else if _, err = msg.WriteTo(w); err != nil {
		return fmt.Errorf("WriteTo: %v", err)
	} else if err = w.Close(); err != nil {
		return fmt.Errorf("Close: %v", err)
	}

	return client.Quit()
}