Skip to content
This repository has been archived by the owner on Feb 5, 2024. It is now read-only.

Commit

Permalink
Add optional Sentry integration
Browse files Browse the repository at this point in the history
  • Loading branch information
spotlightishere committed May 9, 2018
1 parent 030ef2b commit d41147a
Show file tree
Hide file tree
Showing 10 changed files with 99 additions and 45 deletions.
11 changes: 5 additions & 6 deletions account.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func Account(w http.ResponseWriter, r *http.Request) {
stmt, err := db.Prepare("INSERT IGNORE INTO `accounts` (`mlid`,`passwd`, `mlchkid` ) VALUES (?, ?, ?)")
if err != nil {
fmt.Fprint(w, GenAccountErrorCode(410, is, "Database error."))
log.Fatal(err)
LogError("Unable to prepare account statement", err)
return
}

Expand All @@ -47,14 +47,14 @@ func Account(w http.ResponseWriter, r *http.Request) {
result, err := stmt.Exec(wiiID, passwdHash, mlchkidHash)
if err != nil {
fmt.Fprint(w, GenAccountErrorCode(410, is, "Database error."))
log.Println(err)
LogError("Unable to execute statement", err)
return
}

affected, err := result.RowsAffected()
if err != nil {
fmt.Fprint(w, GenAccountErrorCode(410, is, "Database error."))
log.Println(err)
LogError("Unable to get rows affected", err)
return
}

Expand All @@ -70,9 +70,8 @@ func Account(w http.ResponseWriter, r *http.Request) {
}

func GenAccountErrorCode(error int, is string, reason string) string {
if error == 410 {
log.Println(aurora.Red("[Warning]"), "Encountered error", error, "with reason", reason)
}
log.Println(aurora.Red("[Warning]"), "Encountered error", error, "with reason", reason)

return fmt.Sprint(
"cd", is, strconv.Itoa(error), "\n",
"msg", is, reason, "\n")
Expand Down
30 changes: 16 additions & 14 deletions check.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"database/sql"
"encoding/hex"
"fmt"
"log"
"net/http"
"strconv"
)
Expand All @@ -14,10 +13,10 @@ import (
// challenge solving and future mail existence checking.
// BUG(spotlightishere): Challenge solving isn't implemented whatsoever.
func Check(w http.ResponseWriter, r *http.Request, db *sql.DB, inter int) {
stmt, err := db.Prepare("SELECT `mlid` FROM accounts WHERE `mlchkid` = ?")
mlchkidStmt, err := db.Prepare("SELECT `mlid` FROM accounts WHERE `mlchkid` = ?")
if err != nil {
fmt.Fprintf(w, GenNormalErrorCode(420, "Unable to formulate authentication statement."))
log.Fatal(err)
LogError("Unable to prepare check statement", err)
return
}
// Grab string of interval
Expand All @@ -37,7 +36,7 @@ func Check(w http.ResponseWriter, r *http.Request, db *sql.DB, inter int) {
err = r.ParseForm()
if err != nil {
fmt.Fprint(w, GenNormalErrorCode(320, "Unable to parse parameters."))
log.Fatal(err)
LogError("Unable to parse form", err)
return
}

Expand All @@ -52,13 +51,18 @@ func Check(w http.ResponseWriter, r *http.Request, db *sql.DB, inter int) {
hash := hex.EncodeToString(hashByte[:])

// Check mlchkid
result, err := stmt.Query(hash)
result, err := mlchkidStmt.Query(hash)
if err != nil {
fmt.Fprintf(w, GenNormalErrorCode(320, "Unable to parse parameters."))
log.Fatal(err)
LogError("Unable to run mlchkid query", err)
return
}

mlidStatement, err := db.Prepare("SELECT * FROM `mails` WHERE `recipient_id` =? AND `sent` = 0 ORDER BY `timestamp` ASC")
if err != nil {
LogError("Unable to prepare mlid statement", err)
}

// By default, we'll assume there's no mail.
mailFlag := "0"
resultsLoop := 0
Expand All @@ -68,14 +72,12 @@ func Check(w http.ResponseWriter, r *http.Request, db *sql.DB, inter int) {
for result.Next() {
var mlid string
err = result.Scan(&mlid)
stmt, err := db.Prepare("SELECT * FROM `mails` WHERE `recipient_id` =? AND `sent` = 0 ORDER BY `timestamp` ASC")
if err != nil {
log.Fatal(err)
}

// Splice off w from mlid
storedMail, err := stmt.Query(mlid[1:])
storedMail, err := mlidStatement.Query(mlid[1:])
if err != nil {
log.Fatal(err)
LogError("Unable to run mlid", err)
return
}

size := 0
Expand All @@ -86,7 +88,7 @@ func Check(w http.ResponseWriter, r *http.Request, db *sql.DB, inter int) {
err = result.Err()
if err != nil {
fmt.Fprintf(w, GenNormalErrorCode(420, "Unable to formulate authentication statement."))
log.Fatal(err)
LogError("Unable to get user mail", err)
return
}

Expand All @@ -98,7 +100,7 @@ func Check(w http.ResponseWriter, r *http.Request, db *sql.DB, inter int) {
err = result.Err()
if err != nil {
fmt.Fprintf(w, GenNormalErrorCode(420, "Unable to formulate authentication statement."))
log.Fatal(err)
LogError("Generic database issue", err)
return
}

Expand Down
7 changes: 3 additions & 4 deletions delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"strconv"
)
Expand All @@ -14,14 +13,14 @@ func Delete(w http.ResponseWriter, r *http.Request, db *sql.DB) {
if err != nil {
// Welp, that went downhill fast.
fmt.Fprint(w, GenNormalErrorCode(440, "Database error."))
log.Fatal(err)
LogError("Error creating delete prepared statement", err)
return
}

isVerified, err := Auth(r.Form)
if err != nil {
fmt.Fprintf(w, GenNormalErrorCode(541, "Something weird happened."))
log.Printf("Error deleting: %v", err)
LogError("Error parsing delete authentication", err)
return
} else if !isVerified {
fmt.Fprintf(w, GenNormalErrorCode(240, "An authentication error occurred."))
Expand All @@ -40,7 +39,7 @@ func Delete(w http.ResponseWriter, r *http.Request, db *sql.DB) {
_, err = stmt.Exec(wiiID, actualDelnum)

if err != nil {
log.Fatal(err)
LogError("Error deleting from database", err)
fmt.Fprint(w, GenNormalErrorCode(541, "Issue deleting mail from the database."))
} else {
fmt.Fprint(w, GenSuccessResponse(),
Expand Down
18 changes: 14 additions & 4 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,14 @@ import (
"log"
"net/http"
"os"
"github.com/getsentry/raven-go"
)

var global patch.Config
var db *sql.DB
var templates *template.Template
var salt []byte
var ravenClient *raven.Client

func logRequest(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -62,25 +64,26 @@ func configHandle(w http.ResponseWriter, r *http.Request) {

fileWriter, _, err := r.FormFile("uploaded_config")
if err != nil || err == http.ErrMissingFile {
log.Printf("incorrect file: %v", err)
LogError("Incorrect file", err)
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "It seems your file upload went awry. Contact our support email: support@riiconnect24.net.\nError: %v", err)
return
}

file, err := ioutil.ReadAll(fileWriter)
if err != nil {
log.Printf("unable to read file entirely: %v", err)
LogError("Unable to read file", err)
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "It seems your file upload went awry. Contact our support email support@riiconnect24.net.\nError: %v", err)
return
}

patched, err := patch.ModifyNwcConfig(file, db, global, salt)
patched, err := patch.ModifyNwcConfig(file, db, global, ravenClient, salt)
if err != nil {
log.Printf("unable to patch: %v", err)
LogError("Unable to patch", err)
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "It seems your patching went awry. Contact our support email: support@riiconnect24.net.\nError: %v", err)
return
}
w.Header().Add("Content-Type", "application/octet-stream")
w.Header().Add("Content-Disposition", "attachment; filename=\"nwc24msg.cfg\"")
Expand Down Expand Up @@ -138,6 +141,13 @@ func main() {
panic(err)
}

if global.RavenDSN != "" {
ravenClient, err = raven.New(global.RavenDSN)
if err != nil {
panic(err)
}
}

// Load templates for HTML serving later on
templateLocation := "./patch/templates"
templateDir, err := os.Open(templateLocation)
Expand Down
8 changes: 4 additions & 4 deletions patch/patch.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@ import (
"bytes"
"io/ioutil"
"database/sql"
"log"
"crypto/sha512"
"encoding/hex"
"fmt"
"github.com/getsentry/raven-go"
)

// ModifyNwcConfig takes an original config, applies needed patches to the URL and such,
// updates the checksum and returns either nil, error or a patched config w/o error.
func ModifyNwcConfig(originalConfig []byte, db *sql.DB, global Config, salt []byte) ([]byte, error) {
func ModifyNwcConfig(originalConfig []byte, db *sql.DB, global Config, ravenClient *raven.Client, salt []byte) ([]byte, error) {
if len(originalConfig) == 0 {
return nil, errors.New("config seems to be empty. double check you uploaded a file")
}
Expand Down Expand Up @@ -48,13 +48,13 @@ func ModifyNwcConfig(originalConfig []byte, db *sql.DB, global Config, salt []by

stmt, err := db.Prepare("INSERT IGNORE INTO `accounts` (`mlid`,`mlchkid`, `passwd` ) VALUES (?, ?, ?)")
if err != nil {
log.Printf("Database error: %v", err)
LogError(ravenClient, "Error preparing account statement", err)
return nil, err
}

_, err = stmt.Exec(mlid, mlchkidHash, passwdHash)
if err != nil {
log.Printf("Database error: %v", err)
LogError(ravenClient, "Error running account statement", err)
return nil, err
}

Expand Down
3 changes: 2 additions & 1 deletion patch/structures.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,5 @@ type Config struct {
SendGridDomain string
Debug bool
PatchBaseDomain string
}
RavenDSN string
}
19 changes: 19 additions & 0 deletions patch/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ package patch
import (
"time"
"math/rand"
"runtime"
"log"
"github.com/getsentry/raven-go"
)

// https://stackoverflow.com/a/31832326/3874884
Expand Down Expand Up @@ -33,3 +36,19 @@ func RandStringBytesMaskImprSrc(n int) string {

return string(b)
}

func LogError(ravenClient *raven.Client,reason string, err error) {
// Adapted from
// https://stackoverflow.com/a/38551362
pc, _, _, ok := runtime.Caller(1)
details := runtime.FuncForPC(pc)
if ok && details != nil {
// Log to console
log.Printf("%s: %v", reason, err)

// and if it's available, Sentry.
if ravenClient != nil {
raven.CaptureError(err, map[string]string{"given_reason": reason})
}
}
}
19 changes: 11 additions & 8 deletions receive.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package main
import (
"database/sql"
"fmt"
"log"
"math/rand"
"net/http"
"strconv"
Expand All @@ -17,13 +16,14 @@ func Receive(w http.ResponseWriter, r *http.Request, db *sql.DB) {
// Parse form.
err := r.ParseForm()
if err != nil {
log.Fatal(err)
LogError("Error parsing form", err)
return
}

isVerified, err := Auth(r.Form)
if err != nil {
fmt.Fprintf(w, GenNormalErrorCode(531, "Something weird happened."))
log.Printf("Error receiving: %v", err)
LogError("Error receiving.", err)
return
} else if !isVerified {
fmt.Fprintf(w, GenNormalErrorCode(230, "An authentication error occurred."))
Expand All @@ -43,11 +43,13 @@ func Receive(w http.ResponseWriter, r *http.Request, db *sql.DB) {

stmt, err := db.Prepare("SELECT * FROM `mails` WHERE `recipient_id` = ? AND `sent` = 0 ORDER BY `timestamp` ASC")
if err != nil {
log.Fatal(err)
LogError("Error preparing statement", err)
return
}
storedMail, err := stmt.Query(mlid)
if err != nil {
log.Fatal(err)
LogError("Error running query against mlid", err)
return
}

var totalMailOutput string
Expand All @@ -57,7 +59,8 @@ func Receive(w http.ResponseWriter, r *http.Request, db *sql.DB) {
// Statement to mark as sent once put in mail output
updateMailState, err := db.Prepare("UPDATE `mails` SET `sent` = 1 WHERE `mail_id` = ?")
if err != nil {
log.Fatal(err)
LogError("Error preparing sent statement", err)
return
}

// Loop through mail and make the output.
Expand Down Expand Up @@ -104,15 +107,15 @@ func Receive(w http.ResponseWriter, r *http.Request, db *sql.DB) {
// We're committed at this point. Mark it that way in the db.
_, err := updateMailState.Exec(mailId)
if err != nil {
log.Fatal(err)
LogError("Unable to mark mail as sent", err)
}
}
}

// Make sure nothing failed.
err = storedMail.Err()
if err != nil {
panic(err)
LogError("General database error", err)
}

request := fmt.Sprint("--", wc24MimeBoundary, "\r\n",
Expand Down
Loading

0 comments on commit d41147a

Please sign in to comment.