Don't unwrap errors when checking errors.

v0.6
Martin Dosch 10 months ago
parent d56e528680
commit b004015e18
No known key found for this signature in database
GPG Key ID: 52A57CFCE13D657D

@ -7,7 +7,6 @@ package main
import (
"bytes"
"crypto/rand"
"errors"
"fmt"
"log"
"math/big"
@ -34,16 +33,16 @@ func validURI(s string) (*url.URL, error) {
func readFile(path string) (*bytes.Buffer, error) {
file, err := os.Open(path)
if errors.Unwrap(err) != nil {
if err != nil {
return nil, fmt.Errorf("readFile: %w", err)
}
buffer := new(bytes.Buffer)
_, err = buffer.ReadFrom(file)
if errors.Unwrap(err) != nil {
if err != nil {
return nil, fmt.Errorf("readFile: %w", err)
}
err = file.Close()
if errors.Unwrap(err) != nil {
if err != nil {
fmt.Println("error while closing file:", err)
}
return buffer, nil
@ -56,7 +55,7 @@ func getRpad(messageLength int) string {
rpad := make([]rune, length)
for i := range rpad {
randInt, err := rand.Int(rand.Reader, max)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
rpad[i] = rpadRunes[randInt.Int64()]
@ -67,7 +66,7 @@ func getRpad(messageLength int) string {
func getID() string {
id := make([]byte, defaultIDBytes)
_, err := rand.Read(id)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
return fmt.Sprintf("%x-%x-%x", id[0:4], id[4:8], id[8:])
@ -76,7 +75,7 @@ func getID() string {
func getShortID() string {
id := make([]byte, defaultShortIDBytes)
_, err := rand.Read(id)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
return fmt.Sprintf("%x", id[0:4])

@ -7,7 +7,6 @@ package main
import (
"bytes"
"encoding/xml"
"errors"
"fmt"
"log"
"net/http"
@ -27,14 +26,14 @@ func httpUpload(client *xmpp.Client, iqc chan xmpp.IQ, jserver string, filePath
// Get file size
fileInfo, err := os.Stat(filePath)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
fileSize := fileInfo.Size()
// Read file
buffer, err := readFile(filePath)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
@ -53,12 +52,12 @@ func httpUpload(client *xmpp.Client, iqc chan xmpp.IQ, jserver string, filePath
// Query server for disco#items
iqContent, err := sendIQ(client, iqc, jserver, "get",
"<query xmlns='http://jabber.org/protocol/disco#items'/>")
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
iqDiscoItemsXML := etree.NewDocument()
err = iqDiscoItemsXML.ReadFromBytes(iqContent.Query)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
iqDiscoItemsXMLQuery := iqDiscoItemsXML.SelectElement("query")
@ -75,11 +74,11 @@ func httpUpload(client *xmpp.Client, iqc chan xmpp.IQ, jserver string, filePath
iqDiscoInfoReqXMLQuery := iqDiscoInfoReqXML.CreateElement("query")
iqDiscoInfoReqXMLQuery.CreateAttr("xmlns", nsDiscoInfo)
iqdi, err := iqDiscoInfoReqXML.WriteToString()
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
iqDiscoInfo, err := sendIQ(client, iqc, jid.Value, "get", iqdi)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
if iqDiscoInfo.Type != strResult {
@ -87,7 +86,7 @@ func httpUpload(client *xmpp.Client, iqc chan xmpp.IQ, jserver string, filePath
}
iqDiscoInfoXML := etree.NewDocument()
err = iqDiscoInfoXML.ReadFromBytes(iqDiscoInfo.Query)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
iqDiscoInfoXMLQuery := iqDiscoInfoXML.SelectElement("query")
@ -132,7 +131,7 @@ func httpUpload(client *xmpp.Client, iqc chan xmpp.IQ, jserver string, filePath
}
if varAttr.Value == "max-file-size" && prevFieldVal.Text() == nsHTTPUpload {
maxFileSize, err = strconv.ParseInt(curFieldVal.Text(), 10, 64)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal("error while checking server maximum http upload file size.")
}
}
@ -157,13 +156,13 @@ func httpUpload(client *xmpp.Client, iqc chan xmpp.IQ, jserver string, filePath
requestReq.CreateAttr("size", fmt.Sprint(fileSize))
requestReq.CreateAttr("content-type", mimeType)
r, err := request.WriteToString()
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
// Request http upload slot
uploadSlot, err := sendIQ(client, iqc, uploadComponent, "get", r)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
if uploadSlot.Type != strResult {
@ -171,7 +170,7 @@ func httpUpload(client *xmpp.Client, iqc chan xmpp.IQ, jserver string, filePath
}
iqHTTPUploadSlotXML := etree.NewDocument()
err = iqHTTPUploadSlotXML.ReadFromBytes(uploadSlot.Query)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
iqHTTPUploadSlotXMLSlot := iqHTTPUploadSlotXML.SelectElement("slot")
@ -191,7 +190,7 @@ func httpUpload(client *xmpp.Client, iqc chan xmpp.IQ, jserver string, filePath
httpClient := &http.Client{}
req, err := http.NewRequest(http.MethodPut, iqHTTPUploadSlotXMLPutURL.Value,
buffer)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
req.Header.Set("Content-Type", mimeTypeEscaped.String())
@ -207,7 +206,7 @@ func httpUpload(client *xmpp.Client, iqc chan xmpp.IQ, jserver string, filePath
}
}
resp, err := httpClient.Do(req)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
// Test for http status code "200 OK" or "201 Created"
@ -225,7 +224,7 @@ func httpUpload(client *xmpp.Client, iqc chan xmpp.IQ, jserver string, filePath
log.Fatal("http-upload: no url attribute")
}
err = resp.Body.Close()
if errors.Unwrap(err) != nil {
if err != nil {
fmt.Println("error while closing http request body:", err)
}
return iqHTTPUploadSlotXMLGetURL.Value

@ -8,7 +8,6 @@ import (
"bufio"
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"log"
@ -46,7 +45,7 @@ func readMessage(messageFilePath string) (string, error) {
// Open message file.
file, err := os.Open(messageFilePath)
if errors.Unwrap(err) != nil {
if err != nil {
return output, fmt.Errorf("readMessage: %w", err)
}
scanner := bufio.NewScanner(file)
@ -59,14 +58,14 @@ func readMessage(messageFilePath string) (string, error) {
}
}
if err := scanner.Err(); errors.Unwrap(err) != nil {
if errors.Unwrap(err) != io.EOF {
if err := scanner.Err(); err != nil {
if err != io.EOF {
return "", fmt.Errorf("readMessage: %w", err)
}
}
err = file.Close()
if errors.Unwrap(err) != nil {
if err != nil {
fmt.Println("error while closing file:", err)
}
@ -174,7 +173,7 @@ func main() {
if *flagUser == "" || *flagPassword == "" {
// Read configuration from file.
config, err := parseConfig(*flagFile)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal("Error parsing ", *flagFile, ": ", err)
}
// Set connection options according to config.
@ -273,7 +272,7 @@ func main() {
// Read message from file.
if *flagMessageFile != "" {
message, err = readMessage(*flagMessageFile)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
}
@ -294,7 +293,7 @@ func main() {
}
if err := scanner.Err(); err != nil {
if errors.Unwrap(err) != io.EOF {
if err != io.EOF {
log.Fatal(err)
}
}
@ -311,7 +310,7 @@ func main() {
// Connect to server.
client, err := connect(options, *flagDirectTLS)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
@ -324,7 +323,7 @@ func main() {
re.Jid = r
if *flagOx {
re.OxKeyRing, err = oxGetPublicKeyRing(client, iqc, r)
if errors.Unwrap(err) != nil {
if err != nil {
re.OxKeyRing = nil
fmt.Println("ox: error fetching key for", r+":", err)
}
@ -335,7 +334,7 @@ func main() {
// Check that all recipient JIDs are valid.
for i, recipient := range recipients {
validatedJid, err := MarshalJID(recipient.Jid)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
recipients[i].Jid = validatedJid
@ -344,52 +343,52 @@ func main() {
switch {
case *flagOxGenPrivKeyX25519:
validatedOwnJid, err := MarshalJID(user)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
err = oxGenPrivKey(validatedOwnJid, client, iqc, *flagOxPassphrase, "x25519")
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
os.Exit(0)
case *flagOxGenPrivKeyRSA:
validatedOwnJid, err := MarshalJID(user)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
err = oxGenPrivKey(validatedOwnJid, client, iqc, *flagOxPassphrase, "rsa")
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
os.Exit(0)
case *flagOxImportPrivKey != "":
validatedOwnJid, err := MarshalJID(user)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
err = oxImportPrivKey(validatedOwnJid, *flagOxImportPrivKey,
client, iqc)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
os.Exit(0)
case *flagOxDeleteNodes:
validatedOwnJid, err := MarshalJID(user)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
err = oxDeleteNodes(validatedOwnJid, client, iqc)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
os.Exit(0)
case *flagOx:
validatedOwnJid, err := MarshalJID(user)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
oxPrivKey, err = oxGetPrivKey(validatedOwnJid, *flagOxPassphrase)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
}
@ -404,7 +403,7 @@ func main() {
message = validUTF8(*flagOOBFile)
// Check if the URI is valid.
uri, err := validURI(message)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
message = uri.String()
@ -427,7 +426,7 @@ func main() {
} else {
_, err = client.JoinMUCNoHistory(recipient.Jid, alias)
}
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
}
@ -439,7 +438,7 @@ func main() {
}
// Send raw XML
_, err = client.SendOrg(message)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
case *flagInteractive:
@ -458,7 +457,7 @@ func main() {
for {
message, err = reader.ReadString('\n')
message = strings.TrimSuffix(message, "\n")
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal("failed to read from stdin")
}
@ -475,13 +474,13 @@ func main() {
}
oxMessage, err := oxEncrypt(client, oxPrivKey,
recipient.Jid, recipient.OxKeyRing, message)
if errors.Unwrap(err) != nil {
if err != nil {
fmt.Println("Ox: couldn't encrypt to",
recipient.Jid)
continue
}
_, err = client.SendOrg(oxMessage)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
default:
@ -489,7 +488,7 @@ func main() {
Remote: recipient.Jid,
Type: msgType, Text: message,
})
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
}
@ -502,7 +501,7 @@ func main() {
switch {
case isOxMsg(v) && *flagOx:
msg, t, err := oxDecrypt(v, client, iqc, user, oxPrivKey)
if errors.Unwrap(err) != nil {
if err != nil {
log.Println(err)
continue
}
@ -575,7 +574,7 @@ func main() {
Remote: recipient.Jid,
Type: msgType, Ooburl: message, Text: message,
})
if errors.Unwrap(err) != nil {
if err != nil {
fmt.Println("Couldn't send message to",
recipient.Jid)
}
@ -585,7 +584,7 @@ func main() {
_, err = client.SendOrg("<message to='" + recipient.Jid + "' type='" +
msgType + "'><body>" + message + "</body><x xmlns='jabber:x:oob'><url>" +
message + "</url></x></message>")
if errors.Unwrap(err) != nil {
if err != nil {
fmt.Println("Couldn't send message to",
recipient.Jid)
}
@ -595,12 +594,12 @@ func main() {
}
oxMessage, err := oxEncrypt(client, oxPrivKey,
recipient.Jid, recipient.OxKeyRing, message)
if errors.Unwrap(err) != nil {
if err != nil {
fmt.Println("Ox: couldn't encrypt to", recipient.Jid)
continue
}
_, err = client.SendOrg(oxMessage)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
default:
@ -608,7 +607,7 @@ func main() {
Remote: recipient.Jid,
Type: msgType, Text: message,
})
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
}

160
ox.go

@ -25,16 +25,16 @@ func oxDeleteNodes(jid string, client *xmpp.Client, iqc chan xmpp.IQ) error {
query := nodeListRequest.CreateElement("query")
query.CreateAttr("xmlns", nsDiscoItems)
nlr, err := nodeListRequest.WriteToString()
if errors.Unwrap(err) != nil {
if err != nil {
return fmt.Errorf("oxDeleteNodes: failed to create node list request %w", err)
}
iqReply, err := sendIQ(client, iqc, jid, "get", nlr)
if errors.Unwrap(err) != nil {
if err != nil {
return fmt.Errorf("oxDeleteNodes: failure with node list request iq: %w", err)
}
nodeListReply := etree.NewDocument()
err = nodeListReply.ReadFromBytes(iqReply.Query)
if errors.Unwrap(err) != nil {
if err != nil {
return fmt.Errorf("oxDeleteNodes: failed to read node list reply iq: %w", err)
}
query = nodeListReply.SelectElement("query")
@ -60,11 +60,11 @@ func oxDeleteNodes(jid string, client *xmpp.Client, iqc chan xmpp.IQ) error {
del := pubsub.CreateElement("delete")
del.CreateAttr("node", node.Value)
dnr, err := deleteNodeRequest.WriteToString()
if errors.Unwrap(err) != nil {
if err != nil {
continue
}
_, err = sendIQ(client, iqc, jid, "set", dnr)
if errors.Unwrap(err) != nil {
if err != nil {
continue
}
}
@ -78,7 +78,7 @@ func oxDecrypt(m xmpp.Chat, client *xmpp.Client, iqc chan xmpp.IQ, user string,
for _, r := range m.OtherElem {
if r.XMLName.Space == nsOx {
cryptMsgByte, err = base64.StdEncoding.DecodeString(r.InnerXML)
if errors.Unwrap(err) != nil {
if err != nil {
return strError, time.Now(), err
}
break
@ -86,22 +86,22 @@ func oxDecrypt(m xmpp.Chat, client *xmpp.Client, iqc chan xmpp.IQ, user string,
}
oxMsg := crypto.NewPGPMessage(cryptMsgByte)
keyRing, err := crypto.NewKeyRing(oxPrivKey)
if errors.Unwrap(err) != nil {
if err != nil {
return strError, time.Now(), err
}
senderKeyRing, err := oxGetPublicKeyRing(client, iqc, sender)
if errors.Unwrap(err) != nil {
if err != nil {
return strError, time.Now(), err
}
decryptMsg, err := keyRing.Decrypt(oxMsg, senderKeyRing, crypto.GetUnixTime())
if errors.Unwrap(err) != nil {
if err != nil {
return strError, time.Now(), err
}
// Remove invalid code points.
message := validUTF8(string(decryptMsg.Data))
doc := etree.NewDocument()
err = doc.ReadFromString(message)
if errors.Unwrap(err) != nil {
if err != nil {
return strError, time.Now(), err
}
signcrypt := doc.SelectElement("signcrypt")
@ -128,7 +128,7 @@ func oxDecrypt(m xmpp.Chat, client *xmpp.Client, iqc chan xmpp.IQ, user string,
return strError, time.Now(), errors.New("ox: no stamp attribute")
}
msgStamp, err := time.Parse("2006-01-02T15:04:05Z0700", stamp.Value)
if errors.Unwrap(err) != nil {
if err != nil {
return strError, time.Now(), err
}
payload := signcrypt.SelectElement("payload")
@ -154,19 +154,19 @@ func isOxMsg(m xmpp.Chat) bool {
func oxImportPrivKey(jid string, privKeyLocation string, client *xmpp.Client, iqc chan xmpp.IQ) error {
xmppURI := "xmpp:" + jid
buffer, err := readFile(privKeyLocation)
if errors.Unwrap(err) != nil {
if err != nil {
return err
}
key, err := crypto.NewKey(buffer.Bytes())
if errors.Unwrap(err) != nil {
if err != nil {
key, err = crypto.NewKeyFromArmored(buffer.String())
if errors.Unwrap(err) != nil {
if err != nil {
keyDecoded, err := base64.StdEncoding.DecodeString(buffer.String())
if errors.Unwrap(err) != nil {
if err != nil {
return fmt.Errorf("oxImportPrivKey: failed to import private key: %w", err)
}
key, err = crypto.NewKey(keyDecoded)
if errors.Unwrap(err) != nil {
if err != nil {
return fmt.Errorf("oxImportPrivKey: failed to import private key: %w", err)
}
}
@ -176,36 +176,36 @@ func oxImportPrivKey(jid string, privKeyLocation string, client *xmpp.Client, iq
return errors.New("Key identity is not " + xmppURI)
}
pk, err := key.GetPublicKey()
if errors.Unwrap(err) != nil {
if err != nil {
return fmt.Errorf("oxImportPrivKey: failed to get public key associated to private key: %w", err)
}
pubKey, err := crypto.NewKey(pk)
if errors.Unwrap(err) != nil {
if err != nil {
return fmt.Errorf("oxImportPrivKey: failed to get public key associated to private key: %w", err)
}
fingerprint := strings.ToUpper(pubKey.GetFingerprint())
_, err = oxRecvPublicKeys(client, iqc, jid, fingerprint)
if errors.Unwrap(err) != nil {
if err != nil {
err = oxPublishPubKey(jid, client, iqc, pubKey)
if errors.Unwrap(err) != nil {
if err != nil {
return fmt.Errorf("oxImportPrivKey: failed to publish public key: %w", err)
}
}
location, err := oxGetPrivKeyLoc(jid)
if errors.Unwrap(err) != nil {
if err != nil {
return fmt.Errorf("oxImportPrivKey: failed to determine private key location: %w", err)
}
keySerialized, err := key.Serialize()
if errors.Unwrap(err) != nil {
if err != nil {
return fmt.Errorf("oxImportPrivKey: failed to serialize private key: %w", err)
}
err = oxStoreKey(location,
base64.StdEncoding.EncodeToString(keySerialized))
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
pubKeyRing, err := oxGetPublicKeyRing(client, iqc, jid)
if errors.Unwrap(err) == nil {
if err == nil {
pubKeys := pubKeyRing.GetKeys()
for _, r := range pubKeys {
if strings.ToUpper(r.GetFingerprint()) == fingerprint {
@ -214,7 +214,7 @@ func oxImportPrivKey(jid string, privKeyLocation string, client *xmpp.Client, iq
}
}
err = oxPublishPubKey(jid, client, iqc, pubKey)
if errors.Unwrap(err) != nil {
if err != nil {
return fmt.Errorf("oxImportPrivKey: failed to publish public key: %w", err)
}
return nil
@ -224,7 +224,7 @@ func oxPublishPubKey(jid string, client *xmpp.Client, iqc chan xmpp.IQ, pubKey *
keyCreated := time.Now().UTC().Format("2006-01-02T15:04:05Z")
fingerprint := strings.ToUpper(pubKey.GetFingerprint())
keySerialized, err := pubKey.Serialize()
if errors.Unwrap(err) != nil {
if err != nil {
return fmt.Errorf("oxPublishPubKey: failed to serialize pubkey: %w", err)
}
pubKeyBase64 := base64.StdEncoding.EncodeToString(keySerialized)
@ -254,23 +254,23 @@ func oxPublishPubKey(jid string, client *xmpp.Client, iqc chan xmpp.IQ, pubKey *
value = field.CreateElement("value")
value.CreateText("open")
xmlstring, err := root.WriteToString()
if errors.Unwrap(err) != nil {
if err != nil {
return fmt.Errorf("oxPublishPubKey: failed to create publish public key iq xml: %w", err)
}
iqReply, err := sendIQ(client, iqc, jid, "set", xmlstring)
if errors.Unwrap(err) != nil {
if err != nil {
return fmt.Errorf("oxPublishPubKey: iq failure publishing public key: %w", err)
}
if iqReply.Type != strResult {
return errors.New("error while publishing public key")
}
ownPubKeyRingFromPubsub, err := oxRecvPublicKeys(client, iqc, jid, fingerprint)
if errors.Unwrap(err) != nil {
if err != nil {
return errors.New("couldn't successfully verify public key upload")
}
ownPubKeyFromPubsub := ownPubKeyRingFromPubsub.GetKeys()[0]
ownPubKeyFromPubsubSerialized, err := ownPubKeyFromPubsub.Serialize()
if errors.Unwrap(err) != nil {
if err != nil {
return errors.New("couldn't successfully verify public key upload")
}
if pubKeyBase64 != base64.StdEncoding.EncodeToString(ownPubKeyFromPubsubSerialized) {
@ -302,11 +302,11 @@ func oxPublishPubKey(jid string, client *xmpp.Client, iqc chan xmpp.IQ, pubKey *
value = field.CreateElement("value")
value.CreateText("open")
xmlstring, err = root.WriteToString()
if errors.Unwrap(err) != nil {
if err != nil {
return fmt.Errorf("oxPublishPubKey: failed to create xml for iq to publish public key list: %w", err)
}
iqReply, err = sendIQ(client, iqc, jid, "set", xmlstring)
if errors.Unwrap(err) != nil {
if err != nil {
return fmt.Errorf("oxPublishPubKey: iq failure publishing public key list: %w", err)
}
if iqReply.Type != strResult {
@ -329,7 +329,7 @@ func oxGetPrivKeyLoc(jid string) (string, error) {
dataDir = homeDir + "/.local/share"
default:
homeDir, err = os.UserHomeDir()
if errors.Unwrap(err) != nil {
if err != nil {
return strError, fmt.Errorf("oxGetPrivKeyLoc: failed to determine user dir: %w", err)
}
if homeDir == "" {
@ -340,7 +340,7 @@ func oxGetPrivKeyLoc(jid string) (string, error) {
dataDir += "/go-sendxmpp/oxprivkeys/"
if _, err = os.Stat(dataDir); os.IsNotExist(err) {
err = os.MkdirAll(dataDir, defaultDirRights)
if errors.Unwrap(err) != nil {
if err != nil {
return strError, fmt.Errorf("oxGetPrivKeyLoc: could not create folder for private keys: %w", err)
}
}
@ -362,7 +362,7 @@ func oxGetPubKeyLoc(fingerprint string) (string, error) {
dataDir = homeDir + "/.local/share"
default:
homeDir, err = os.UserHomeDir()
if errors.Unwrap(err) != nil {
if err != nil {
return strError, fmt.Errorf("oxGetPubKeyLoc: failed to determine user dir: %w", err)
}
if homeDir == "" {
@ -373,7 +373,7 @@ func oxGetPubKeyLoc(fingerprint string) (string, error) {
dataDir += "/go-sendxmpp/oxpubkeys/"
if _, err = os.Stat(dataDir); os.IsNotExist(err) {
err = os.MkdirAll(dataDir, defaultDirRights)
if errors.Unwrap(err) != nil {
if err != nil {
return strError, fmt.Errorf("oxGetPubKeyLoc: could not create folder for public keys: %w", err)
}
}
@ -383,30 +383,30 @@ func oxGetPubKeyLoc(fingerprint string) (string, error) {
func oxGetPrivKey(jid string, passphrase string) (*crypto.Key, error) {
dataFile, err := oxGetPrivKeyLoc(jid)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
keyBuffer, err := readFile(dataFile)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
keyString := keyBuffer.String()
decodedPrivKey, err := base64.StdEncoding.DecodeString(keyString)
if errors.Unwrap(err) != nil {
if err != nil {
return nil, fmt.Errorf("oxGetPrivKey: failed to decode private key: %w", err)
}
key, err := crypto.NewKey(decodedPrivKey)
if errors.Unwrap(err) != nil {
if err != nil {
return nil, fmt.Errorf("oxGetPrivKey: failed to decode private key: %w", err)
}
if passphrase != "" {
key, err = key.Unlock([]byte(passphrase))
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal("Ox: couldn't unlock private key.")
}
}
isLocked, err := key.IsLocked()
if errors.Unwrap(err) != nil {
if err != nil {
return nil, fmt.Errorf("oxGetPrivKey: failed to check whether private key is locked: %w", err)
}
if isLocked {
@ -421,7 +421,7 @@ func oxGetPrivKey(jid string, passphrase string) (*crypto.Key, error) {
func oxStoreKey(location string, key string) error {
var file *os.File
file, err := os.Create(location)
if errors.Unwrap(err) != nil {
if err != nil {
return fmt.Errorf("oxStoreKey: failed to create key location: %w", err)
}
if runtime.GOOS != "windows" {
@ -430,11 +430,11 @@ func oxStoreKey(location string, key string) error {
_ = file.Chmod(os.FileMode(defaultFileRightsWin))
}
_, err = file.Write([]byte(key))
if errors.Unwrap(err) != nil {
if err != nil {
return fmt.Errorf("oxStoreKey: failed to write key to file: %w", err)
}
err = file.Close()
if errors.Unwrap(err) != nil {
if err != nil {
fmt.Println("error while closing file:", err)
}
return nil
@ -445,38 +445,38 @@ func oxGenPrivKey(jid string, client *xmpp.Client, iqc chan xmpp.IQ,
) error {
xmppURI := "xmpp:" + jid
key, err := crypto.GenerateKey(xmppURI, "", keyType, defaultRSABits)
if errors.Unwrap(err) != nil {
if err != nil {
return fmt.Errorf("oxGenPrivKey: failed to generate private key: %w", err)
}
if passphrase != "" {
key, err = key.Lock([]byte(passphrase))
if errors.Unwrap(err) != nil {
if err != nil {
return fmt.Errorf("oxGenPrivKey: failed to lock key with passphrase: %w", err)
}
}
keySerialized, err := key.Serialize()
if errors.Unwrap(err) != nil {
if err != nil {
return fmt.Errorf("oxGenPrivKey: failed to serialize private key: %w", err)
}
location, err := oxGetPrivKeyLoc(jid)
if errors.Unwrap(err) != nil {
if err != nil {
return fmt.Errorf("oxGenPrivKey: failed to get private key location: %w", err)
}
err = oxStoreKey(location,
base64.StdEncoding.EncodeToString(keySerialized))
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
decodedPubKey, err := key.GetPublicKey()
if errors.Unwrap(err) != nil {
if err != nil {
return fmt.Errorf("oxGenPrivKey: failed to decode public key: %w", err)
}
pubKey, err := crypto.NewKey(decodedPubKey)
if errors.Unwrap(err) != nil {
if err != nil {
return fmt.Errorf("oxGenPrivKey: failed to decode public key: %w", err)
}
err = oxPublishPubKey(jid, client, iqc, pubKey)
if errors.Unwrap(err) != nil {
if err != nil {
return fmt.Errorf("oxGenPrivKey: failed to publish public key: %w", err)
}
return nil
@ -491,11 +491,11 @@ func oxRecvPublicKeys(client *xmpp.Client, iqc chan xmpp.IQ, recipient string, f
opkrPsItems.CreateAttr("node", nsOxPubKeys+":"+fingerprint)
opkrPsItems.CreateAttr("max_items", "1")
opkrString, err := opkr.WriteToString()
if errors.Unwrap(err) != nil {
if err != nil {
return nil, fmt.Errorf("oxRecvPublicKeys: failed to generate xml for public key request: %w", err)
}
oxPublicKey, err := sendIQ(client, iqc, recipient, "get", opkrString)
if errors.Unwrap(err) != nil {
if err != nil {
return nil, fmt.Errorf("oxRecvPublicKeys: iq error requesting public keys: %w", err)
}
if oxPublicKey.Type != strResult {
@ -504,11 +504,11 @@ func oxRecvPublicKeys(client *xmpp.Client, iqc chan xmpp.IQ, recipient string, f
}
oxPublicKeyXML := etree.NewDocument()
err = oxPublicKeyXML.ReadFromBytes(oxPublicKey.Query)
if errors.Unwrap(err) != nil {
if err != nil {
return nil, fmt.Errorf("oxRecvPublicKeys: failed parsing iq reply to public key request: %w", err)
}
keyring, err := crypto.NewKeyRing(nil)
if errors.Unwrap(err) != nil {
if err != nil {
return nil, fmt.Errorf("oxRecvPublicKeys: failed reading public key: %w", err)
}
oxPublicKeyXMLPubsub := oxPublicKeyXML.SelectElement("pubsub")
@ -533,18 +533,18 @@ func oxRecvPublicKeys(client *xmpp.Client, iqc chan xmpp.IQ, recipient string, f
continue
}
decodedPubKey, err := base64.StdEncoding.DecodeString(data.Text())
if errors.Unwrap(err) != nil {
if err != nil {
return nil, fmt.Errorf("oxRecvPublicKeys: failed to decode public key: %w", err)
}
key, err := crypto.NewKey(decodedPubKey)
if errors.Unwrap(err) != nil {
if err != nil {
return nil, fmt.Errorf("oxRecvPublicKeys: failed to decode public key: %w", err)
}
if key.IsExpired() {
return nil, errors.New("Key is expired: " + fingerprint)
}
err = keyring.AddKey(key)
if errors.Unwrap(err) != nil {
if err != nil {
return nil, fmt.Errorf("oxRecvPublicKeys: failed adding public key to keyring: %w", err)
}
}
@ -553,7 +553,7 @@ func oxRecvPublicKeys(client *xmpp.Client, iqc chan xmpp.IQ, recipient string, f
func oxGetPublicKeyRing(client *xmpp.Client, iqc chan xmpp.IQ, recipient string) (*crypto.KeyRing, error) {
publicKeyRing, err := crypto.NewKeyRing(nil)
if errors.Unwrap(err) != nil {
if err != nil {
return nil, fmt.Errorf("oxGetPublicKeyRing: failed to create a new keyring: %w", err)
}
@ -565,11 +565,11 @@ func oxGetPublicKeyRing(client *xmpp.Client, iqc chan xmpp.IQ, recipient string)
oxPubKeyListReqPsItems.CreateAttr("node", nsOxPubKeys)
oxPubKeyListReqPsItems.CreateAttr("max_items", "1")
opkl, err := oxPubKeyListReq.WriteToString()
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
oxPublicKeyList, err := sendIQ(client, iqc, recipient, "get", opkl)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
if oxPublicKeyList.Type != strResult {
@ -578,13 +578,13 @@ func oxGetPublicKeyRing(client *xmpp.Client, iqc chan xmpp.IQ, recipient string)
}
oxPubKeyListXML := etree.NewDocument()
err = oxPubKeyListXML.ReadFromBytes(oxPublicKeyList.Query)
if errors.Unwrap(err) != nil {
if err != nil {
return nil, fmt.Errorf("oxGetPublicKeyRing: failed to parse answer to public key list request: %w", err)
}
pubKeyRingID := "none"
newestKey, err := time.Parse(time.RFC3339, "1900-01-01T00:00:00Z")
if errors.Unwrap(err) != nil {
if err != nil {
return nil, fmt.Errorf("oxGetPublicKeyRing: failed to set time for newest key to 1900-01-01: %w", err)
}
@ -615,7 +615,7 @@ func oxGetPublicKeyRing(client *xmpp.Client, iqc chan xmpp.IQ, recipient string)
continue
}
keyDate, err := time.Parse(time.RFC3339, date.Value)
if errors.Unwrap(err) != nil {
if err != nil {
return nil, fmt.Errorf("oxGetPublicKeyRing: failed to parse time stamp for key: %w", err)
}
if keyDate.After(newestKey) {
@ -628,17 +628,17 @@ func oxGetPublicKeyRing(client *xmpp.Client, iqc chan xmpp.IQ, recipient string)
}
pubKeyRingLocation, err := oxGetPubKeyLoc(pubKeyRingID)
if errors.Unwrap(err) != nil {
if err != nil {
return nil, fmt.Errorf("oxGetPublicKeyRing: failed to get public key ring location: %w", err)
}
pubKeyReadXML := etree.NewDocument()
err = pubKeyReadXML.ReadFromFile(pubKeyRingLocation)
if errors.Unwrap(err) == nil {
if err == nil {
date := pubKeyReadXML.SelectElement("date")
if date != nil {
savedKeysDate, err := time.Parse(time.RFC3339, date.Text())
if errors.Unwrap(err) != nil {
if err != nil {
return nil, fmt.Errorf("oxGetPublicKeyRing: failed to parse time for saved key: %w", err)
}
if !savedKeysDate.Before(newestKey) {
@ -648,16 +648,16 @@ func oxGetPublicKeyRing(client *xmpp.Client, iqc chan xmpp.IQ, recipient string)
}
for _, r := range pubKeys {
keyByte, err := base64.StdEncoding.DecodeString(r.Text())
if errors.Unwrap(err) != nil {
if err != nil {
return nil, fmt.Errorf("oxGetPublicKeyRing: failed to decode saved key: %w", err)
}
key, err := crypto.NewKey(keyByte)
if errors.Unwrap(err) != nil {
if err != nil {
return nil, fmt.Errorf("oxGetPublicKeyRing: failed to parse saved key: %w", err)
}
if !key.IsExpired() {
err = publicKeyRing.AddKey(key)
if errors.Unwrap(err) != nil {
if err != nil {
return nil, fmt.Errorf("oxGetPublicKeyRing: failed to add key to public keyring: %w", err)
}
}
@ -669,7 +669,7 @@ func oxGetPublicKeyRing(client *xmpp.Client, iqc chan xmpp.IQ, recipient string)
}
}
pubKeyRing, err := oxRecvPublicKeys(client, iqc, recipient, pubKeyRingID)
if errors.Unwrap(err) != nil {
if err != nil {
return nil, fmt.Errorf("oxGetPublicKeyRing: failed to get public keyring: %w", err)
}
pubKeySaveXML := etree.NewDocument()
@ -677,14 +677,14 @@ func oxGetPublicKeyRing(client *xmpp.Client, iqc chan xmpp.IQ, recipient string)
date.SetText(newestKey.Format(time.RFC3339))
for _, key := range pubKeyRing.GetKeys() {
keySerialized, err := key.Serialize()
if errors.Unwrap(err) != nil {
if err != nil {
return nil, fmt.Errorf("oxGetPublicKeyRing: failed to serialize key: %w", err)
}
saveKey := pubKeySaveXML.CreateElement("pubkey")
saveKey.SetText(base64.StdEncoding.EncodeToString(keySerialized))
}
err = pubKeySaveXML.WriteToFile(pubKeyRingLocation)
if errors.Unwrap(err) != nil {
if err != nil {
return nil, fmt.Errorf("oxGetPublicKeyRing: failed to create xml for saving public key: %w", err)
}
return pubKeyRing, nil
@ -695,13 +695,13 @@ func oxEncrypt(client *xmpp.Client, oxPrivKey *crypto.Key, recipient string, key
return "", nil
}
privKeyRing, err := crypto.NewKeyRing(oxPrivKey)
if errors.Unwrap(err) != nil {
if err != nil {
return strError, fmt.Errorf("oxEncrypt: failed to create private keyring: %w", err)
}
ownJid := strings.Split(client.JID(), "/")[0]
if recipient != ownJid {
opk, err := oxPrivKey.GetPublicKey()
if errors.Unwrap(err) == nil {
if err == nil {
ownKey, _ := crypto.NewKey(opk)
_ = keyRing.AddKey(ownKey)
}
@ -721,12 +721,12 @@ func oxEncrypt(client *xmpp.Client, oxPrivKey *crypto.Key, recipient string, key
oxCryptMessageScPayloadBody.CreateAttr("xmlns", nsJabberClient)
oxCryptMessageScPayloadBody.CreateText(message)
ocm, err := oxCryptMessage.WriteToString()
if errors.Unwrap(err) != nil {
if err != nil {
return strError, fmt.Errorf("oxEncrypt: failed to create xml for ox crypt message: %w", err)
}
plainMessage := crypto.NewPlainMessage([]byte(ocm))
pgpMessage, err := keyRing.Encrypt(plainMessage, privKeyRing)
if errors.Unwrap(err) != nil {
if err != nil {
return strError, fmt.Errorf("oxEncrypt: failed to create pgp message: %w", err)
}
om := etree.NewDocument()
@ -745,7 +745,7 @@ func oxEncrypt(client *xmpp.Client, oxPrivKey *crypto.Key, recipient string, key
omMessageBody := omMessage.CreateElement("body")
omMessageBody.CreateText(oxAltBody)
oms, err := om.WriteToString()
if errors.Unwrap(err) != nil {
if err != nil {
return strError, fmt.Errorf("oxEncrypt: failed to create xml for ox message: %w", err)
}

@ -20,7 +20,7 @@ import (
func findConfig() (string, error) {
// Get the current user.
curUser, err := user.Current()
if errors.Unwrap(err) != nil {
if err != nil {
return "", fmt.Errorf("findConfig: failed to get current user: %w", err)
}
// Get home directory.
@ -41,7 +41,7 @@ func findConfig() (string, error) {
for _, r := range configFiles {
// Check that the config file is existing.
_, err := os.Stat(r)
if errors.Unwrap(err) == nil {
if err == nil {
return r, nil
}
}
@ -62,7 +62,7 @@ func parseConfig(configPath string) (configuration, error) {
// Get systems user config path.
if configPath == "" {
configPath, err = findConfig()
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
}
@ -70,7 +70,7 @@ func parseConfig(configPath string) (configuration, error) {
// Only check file permissions if we are not running on windows.
if runtime.GOOS != "windows" {
info, err := os.Stat(configPath)
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
// Check for file permissions. Must be 600, 640, 440 or 400.
@ -84,7 +84,7 @@ func parseConfig(configPath string) (configuration, error) {
// Open config file.
file, err := os.Open(configPath)
if errors.Unwrap(err) != nil {
if err != nil {
return output, fmt.Errorf("parseConfig: failed to open config file: %w", err)
}
scanner := bufio.NewScanner(file)
@ -111,7 +111,7 @@ func parseConfig(configPath string) (configuration, error) {
shell = "/bin/sh"
}
out, err := exec.Command(shell, "-c", row[1]).Output()
if errors.Unwrap(err) != nil {
if err != nil {
log.Fatal(err)
}
output.password = string(out)
@ -144,19 +144,19 @@ func parseConfig(configPath string) (configuration, error) {
}
}
err = file.Close()
if errors.Unwrap(err) != nil {
if err != nil {
fmt.Println("error closing file:", err)
}
// Check if the username is a valid JID
output.username, err = MarshalJID(output.username)
if errors.Unwrap(err) != nil {
if err != nil {
// Check whether only the local part was used by appending an @ and the
// server part.
output.username = output.username + "@" + output.jserver
// Check if the username is a valid JID now
output.username, err = MarshalJID(output.username)
if errors.Unwrap(err) != nil {
if err != nil {
return output, errors.New("invalid username/JID: " + output.username)
}
}

@ -6,7 +6,6 @@ package main
import (
"context"
"errors"
"fmt"
"log"
@ -21,7 +20,7 @@ func sendIQ(client *xmpp.Client, iqc chan xmpp.IQ, target string, iQtype string,
go getIQ(id, c, iqc)
_, err := client.RawInformation(client.JID(), target, id,
iQtype, content)
if errors.Unwrap(err) != nil {
if err != nil {
return iq, fmt.Errorf("sendIQ: failed to send iq: %w", err)
}
iq = <-c
@ -48,7 +47,7 @@ func rcvStanzas(client *xmpp.Client, iqc chan xmpp.IQ, msgc chan xmpp.Chat, ctx
case <-ctx.Done():
return
default:
if errors.Unwrap(err) != nil {
if err != nil {
log.Println(err)
}
}
@ -61,7 +60,7 @@ func rcvStanzas(client *xmpp.Client, iqc chan xmpp.IQ, msgc chan xmpp.Chat, ctx
var xmlns *etree.Attr
iq := etree.NewDocument()
err = iq.ReadFromBytes(v.Query)
if errors.Unwrap(err) != nil {
if err != nil {
log.Println("Couldn't parse IQ:",
string(v.Query), err)
}
@ -87,9 +86,9 @@ func rcvStanzas(client *xmpp.Client, iqc chan xmpp.IQ, msgc chan xmpp.Chat, ctx
feat := replyQuery.CreateElement("feature")
feat.CreateAttr("var", nsDiscoInfo)
xmlString, err := root.WriteToString()
if errors.Unwrap(err) == nil {
if err == nil {
_, err = client.SendOrg(xmlString)
if errors.Unwrap(err) != nil {
if err != nil {
log.Println(err)
}
}
@ -106,9 +105,9 @@ func rcvStanzas(client *xmpp.Client, iqc chan xmpp.IQ, msgc chan xmpp.Chat, ctx
su := errorReply.CreateElement("service-unavailable")
su.CreateAttr("xmlns", nsXMPPStanzas)
xmlString, err := root.WriteToString()
if errors.Unwrap(err) == nil {
if err == nil {
_, err = client.SendOrg(xmlString)
if errors.Unwrap(err) != nil {
if err != nil {
log.Println(err)
}
}
@ -126,9 +125,9 @@ func rcvStanzas(client *xmpp.Client, iqc chan xmpp.IQ, msgc chan xmpp.Chat, ctx
su := errorReply.CreateElement("service-unavailable")
su.CreateAttr("xmlns", nsXMPPStanzas)
xmlString, err := root.WriteToString()
if errors.Unwrap(err) == nil {
if err == nil {
_, err = client.SendOrg(xmlString)
if errors.Unwrap(err) != nil {
if err != nil {
log.Println(err)
}
}

Loading…
Cancel
Save