From 2f5c5e2c6d9318149a5e4f20e0fc5b2434356550 Mon Sep 17 00:00:00 2001 From: Tulir Asokan Date: Fri, 30 Jun 2023 14:48:50 +0300 Subject: [PATCH] Stop using stdlib log --- libgm/client.go | 9 ++++----- libgm/conversations.go | 5 ++--- libgm/crypto/generate.go | 5 ++--- libgm/event_handler.go | 6 ++---- libgm/media_processor.go | 8 +++----- libgm/message_builder.go | 2 -- libgm/misc.go | 3 +-- libgm/msg_handler.go | 4 ++-- libgm/opcode_handler.go | 9 ++++----- libgm/pair.go | 5 ++--- libgm/payload/getWebEncryptionKey.go | 3 --- libgm/response_handler.go | 5 ++--- libgm/rpc.go | 10 +++++----- libgm/session_handler.go | 15 +++++++-------- 14 files changed, 36 insertions(+), 53 deletions(-) diff --git a/libgm/client.go b/libgm/client.go index 11aadfc..019c53a 100644 --- a/libgm/client.go +++ b/libgm/client.go @@ -3,7 +3,6 @@ package libgm import ( "encoding/base64" "io" - "log" "net/http" "net/url" "time" @@ -91,7 +90,7 @@ func (c *Client) SetProxy(proxy string) error { func (c *Client) Connect(rpcKey string) error { rpcPayload, receiveMesageSessionId, err := payload.ReceiveMessages(rpcKey) if err != nil { - log.Fatal(err) + panic(err) return err } c.rpc.rpcSessionId = receiveMesageSessionId @@ -114,7 +113,7 @@ func (c *Client) Reconnect(rpcKey string) error { c.Logger.Debug().Any("rpcKey", rpcKey).Msg("Successfully reconnected to server") sendInitialDataErr := c.rpc.sendInitialData() if sendInitialDataErr != nil { - log.Fatal(sendInitialDataErr) + panic(sendInitialDataErr) } return nil } @@ -155,7 +154,7 @@ func (c *Client) decryptImages(messages *binary.FetchMessagesResponse) error { case *binary.MessageInfo_ImageContent: decryptedImageData, err := c.decryptImageData(data.ImageContent.ImageId, data.ImageContent.DecryptionKey) if err != nil { - log.Fatal(err) + panic(err) return err } data.ImageContent.ImageData = decryptedImageData @@ -213,7 +212,7 @@ func (c *Client) decryptImageData(imageId string, key []byte) ([]byte, error) { c.imageCryptor.UpdateDecryptionKey(key) decryptedImageBytes, decryptionErr := c.imageCryptor.DecryptData(encryptedBuffImg) if decryptionErr != nil { - log.Println("Error:", decryptionErr) + c.Logger.Err(err).Msg("Image decryption failed") return nil, decryptionErr } return decryptedImageBytes, nil diff --git a/libgm/conversations.go b/libgm/conversations.go index cda8551..3139ddd 100644 --- a/libgm/conversations.go +++ b/libgm/conversations.go @@ -2,7 +2,6 @@ package libgm import ( "fmt" - "log" "go.mau.fi/mautrix-gmessages/libgm/binary" ) @@ -45,7 +44,7 @@ func (c *Conversations) SendMessage(messageBuilder *MessageBuilder, selfParticip encryptedProtoPayload, failedToBuild := messageBuilder.Build() if failedToBuild != nil { - log.Fatal(failedToBuild) + panic(failedToBuild) } instruction, _ := c.client.instructions.GetInstruction(SEND_TEXT_MESSAGE) @@ -54,7 +53,7 @@ func (c *Conversations) SendMessage(messageBuilder *MessageBuilder, selfParticip responses, err := c.client.sessionHandler.WaitForResponse(sentRequestId, instruction.Opcode) if err != nil { - log.Fatal(err) + panic(err) return nil, err } diff --git a/libgm/crypto/generate.go b/libgm/crypto/generate.go index 2dbb16a..fcd5e80 100644 --- a/libgm/crypto/generate.go +++ b/libgm/crypto/generate.go @@ -2,7 +2,6 @@ package crypto import ( "crypto/rand" - "log" ) func GenerateKey(length int) ([]byte, error) { @@ -17,11 +16,11 @@ func GenerateKey(length int) ([]byte, error) { func GenerateKeys() ([]byte, []byte) { key, err := GenerateKey(32) if err != nil { - log.Fatal(err) + panic(err) } key2, err2 := GenerateKey(32) if err2 != nil { - log.Fatal(err2) + panic(err2) } return key, key2 } diff --git a/libgm/event_handler.go b/libgm/event_handler.go index 6f4e716..6c0c52c 100644 --- a/libgm/event_handler.go +++ b/libgm/event_handler.go @@ -1,17 +1,15 @@ package libgm import ( - "log" - "go.mau.fi/mautrix-gmessages/libgm/binary" ) func (c *Client) handleEventOpCode(response *Response) { - //c.Logger.Debug().Any("res", response).Msg("got event response") + c.Logger.Debug().Any("res", response).Msg("got event response?") eventData := &binary.Event{} decryptedErr := c.cryptor.DecryptAndDecodeData(response.Data.EncryptedData, eventData) if decryptedErr != nil { - log.Fatal(decryptedErr) + panic(decryptedErr) } switch evt := eventData.Event.(type) { case *binary.Event_MessageEvent: diff --git a/libgm/media_processor.go b/libgm/media_processor.go index d57f3c9..382451a 100644 --- a/libgm/media_processor.go +++ b/libgm/media_processor.go @@ -5,7 +5,6 @@ import ( "encoding/base64" "errors" "io" - "log" "net/http" "strconv" @@ -40,7 +39,6 @@ func (c *Client) FinalizeUploadMedia(upload *StartGoogleUpload) (*MediaUpload, e imageType := upload.Image.GetImageType() encryptedImageSize := strconv.Itoa(len(upload.EncryptedMediaBytes)) - log.Println("EncryptedImageSize:", encryptedImageSize) finalizeUploadHeaders := util.NewMediaUploadHeaders(encryptedImageSize, "upload, finalize", "0", imageType.Format, "") req, reqErr := http.NewRequest("POST", upload.UploadUrl, bytes.NewBuffer(upload.EncryptedMediaBytes)) if reqErr != nil { @@ -51,7 +49,7 @@ func (c *Client) FinalizeUploadMedia(upload *StartGoogleUpload) (*MediaUpload, e res, resErr := c.http.Do(req) if resErr != nil { - log.Fatal(resErr) + panic(resErr) } statusCode := res.StatusCode @@ -68,7 +66,7 @@ func (c *Client) FinalizeUploadMedia(upload *StartGoogleUpload) (*MediaUpload, e } uploadStatus := rHeaders.Get("x-goog-upload-status") - log.Println("Upload Status: ", uploadStatus) + c.Logger.Debug().Str("upload_status", uploadStatus).Msg("Upload status") mediaIds := &binary.UploadMediaResponse{} err3 = crypto.DecodeAndEncodeB64(string(googleResponse), mediaIds) @@ -106,7 +104,7 @@ func (c *Client) StartUploadMedia(image *Image) (*StartGoogleUpload, error) { res, resErr := c.http.Do(req) if resErr != nil { - log.Fatal(resErr) + panic(resErr) } statusCode := res.StatusCode diff --git a/libgm/message_builder.go b/libgm/message_builder.go index 9fe8ef3..03fd29d 100644 --- a/libgm/message_builder.go +++ b/libgm/message_builder.go @@ -2,7 +2,6 @@ package libgm import ( "errors" - "log" "go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/util" @@ -147,7 +146,6 @@ func (mb *MessageBuilder) newSendConversationMessage() *binary.SendMessagePayloa func (mb *MessageBuilder) appendImagesPayload(messageInfo *[]*binary.MessageInfo) { if len(mb.images) <= 0 { - log.Println("0 images to append, ignoring") return } diff --git a/libgm/misc.go b/libgm/misc.go index 446169d..5dc1096 100644 --- a/libgm/misc.go +++ b/libgm/misc.go @@ -1,7 +1,6 @@ package libgm import ( - "log" "os" "go.mau.fi/mautrix-gmessages/libgm/builders" @@ -19,7 +18,7 @@ func (m *Misc) TenorSearch(searchOpts *builders.TenorSearch) (interface{}, error } uri := util.TENOR_SEARCH_GIF + searchQuery - log.Println(uri) + m.client.Logger.Debug().Msg(uri) os.Exit(1) return nil, nil } diff --git a/libgm/msg_handler.go b/libgm/msg_handler.go index ada557d..3303d66 100644 --- a/libgm/msg_handler.go +++ b/libgm/msg_handler.go @@ -3,7 +3,6 @@ package libgm import ( "encoding/json" "fmt" - "log" "go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/pblite" @@ -26,6 +25,7 @@ func (r *RPC) HandleRPCMsg(msgArr []interface{}) { response := &binary.RPCResponse{} deserializeErr := pblite.Deserialize(msgArr, response.ProtoReflect()) if deserializeErr != nil { + r.client.Logger.Error().Err(deserializeErr).Msg("meow") r.client.Logger.Error().Err(fmt.Errorf("failed to deserialize response %s", msgArr)).Msg("rpc deserialize msg err") return } @@ -37,7 +37,7 @@ func (r *RPC) HandleRPCMsg(msgArr []interface{}) { if response.Data.RoutingOpCode == 19 { parsedResponse, failedParse := r.client.sessionHandler.NewResponse(response) if failedParse != nil { - log.Fatal(failedParse) + panic(failedParse) } //hasBody := parsedResponse.Data.EncryptedData == nil //r.client.Logger.Info().Any("msgData", parsedResponse).Msg("Got event!") diff --git a/libgm/opcode_handler.go b/libgm/opcode_handler.go index 178a0a9..2fed1ae 100644 --- a/libgm/opcode_handler.go +++ b/libgm/opcode_handler.go @@ -2,7 +2,6 @@ package libgm import ( "encoding/base64" - "log" "go.mau.fi/mautrix-gmessages/libgm/binary" ) @@ -10,14 +9,14 @@ import ( func (c *Client) handleSeperateOpCode(msgData *binary.MessageData) { decodedBytes, err := base64.StdEncoding.DecodeString(msgData.EncodedData) if err != nil { - log.Fatal(err) + panic(err) } switch msgData.RoutingOpCode { case 14: // paired successful decodedData := &binary.Container{} err = binary.DecodeProtoMessage(decodedBytes, decodedData) if err != nil { - log.Fatal(err) + panic(err) } c.Logger.Debug().Any("data", decodedData).Msg("Paired device decoded data") c.pairer.pairCallback(decodedData) @@ -25,13 +24,13 @@ func (c *Client) handleSeperateOpCode(msgData *binary.MessageData) { decodedData := &binary.EncodedResponse{} err = binary.DecodeProtoMessage(decodedBytes, decodedData) if err != nil { - log.Fatal(err) + panic(err) } if (decodedData.Sub && decodedData.Third != 0) && decodedData.EncryptedData != nil { bugleData := &binary.BugleBackendService{} err = c.cryptor.DecryptAndDecodeData(decodedData.EncryptedData, bugleData) if err != nil { - log.Fatal(err) + panic(err) } c.handleBugleOpCode(bugleData) } diff --git a/libgm/pair.go b/libgm/pair.go index e6721f2..b9999ba 100644 --- a/libgm/pair.go +++ b/libgm/pair.go @@ -3,7 +3,6 @@ package libgm import ( "encoding/base64" "io" - "log" "time" "go.mau.fi/mautrix-gmessages/libgm/binary" @@ -113,7 +112,7 @@ func (p *Pairer) RefreshPhoneRelay() { p.client.Logger.Debug().Any("res", res).Msg("RefreshPhoneRelayResponse") url, qrErr := p.GenerateQRCodeData() if qrErr != nil { - log.Fatal(qrErr) + panic(qrErr) } p.client.triggerEvent(&events.QRCODE_UPDATED{URL: url}) } @@ -145,7 +144,7 @@ func (p *Pairer) GetWebEncryptionKey() { p.ticker.Stop() reconnectErr := p.client.Reconnect(key) if reconnectErr != nil { - log.Fatal(reconnectErr) + panic(reconnectErr) } } diff --git a/libgm/payload/getWebEncryptionKey.go b/libgm/payload/getWebEncryptionKey.go index 59aed77..18cdb8e 100644 --- a/libgm/payload/getWebEncryptionKey.go +++ b/libgm/payload/getWebEncryptionKey.go @@ -1,14 +1,11 @@ package payload import ( - "log" - "go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/util" ) func GetWebEncryptionKey(WebPairKey []byte) ([]byte, *binary.Container, error) { - log.Println(WebPairKey) id := util.RandomUUIDv4() payload := &binary.Container{ PhoneRelay: &binary.PhoneRelayBody{ diff --git a/libgm/response_handler.go b/libgm/response_handler.go index 0d731b4..6c2328f 100644 --- a/libgm/response_handler.go +++ b/libgm/response_handler.go @@ -2,7 +2,6 @@ package libgm import ( "fmt" - "log" "sync" ) @@ -16,7 +15,7 @@ type ResponseChan struct { func (s *SessionHandler) addRequestToChannel(requestId string, opCode int64) { instruction, notOk := s.client.instructions.GetInstruction(opCode) if !notOk { - log.Fatal(notOk) + panic(notOk) } if msgMap, ok := s.requests[requestId]; ok { responseChan := &ResponseChan{ @@ -67,7 +66,7 @@ func (s *SessionHandler) respondToRequestChannel(res *Response) { opCodeResponseChan.receivedResponses++ opCodeResponseChan.wg.Done() if !ok3 { - log.Fatal(ok3) + panic(ok3) opCodeResponseChan.mu.Unlock() return } diff --git a/libgm/rpc.go b/libgm/rpc.go index dc019e1..0df0b0e 100644 --- a/libgm/rpc.go +++ b/libgm/rpc.go @@ -4,8 +4,8 @@ import ( "bufio" "bytes" "errors" + "fmt" "io" - "log" "net/http" "os" @@ -24,13 +24,13 @@ type RPC struct { func (r *RPC) ListenReceiveMessages(payload []byte) { req, err := http.NewRequest("POST", util.RECEIVE_MESSAGES, bytes.NewReader(payload)) if err != nil { - log.Fatalf("Error creating request: %v", err) + panic(fmt.Errorf("Error creating request: %v", err)) } util.BuildRelayHeaders(req, "application/json+protobuf", "*/*") resp, reqErr := r.http.Do(req) //r.client.Logger.Info().Any("bodyLength", len(payload)).Any("url", util.RECEIVE_MESSAGES).Any("headers", resp.Request.Header).Msg("RPC Request Headers") if reqErr != nil { - log.Fatalf("Error making request: %v", err) + panic(fmt.Errorf("Error making request: %v", err)) } r.conn = resp.Body go r.startReadingData(resp.Body) @@ -139,13 +139,13 @@ func (r *RPC) CloseConnection() { func (r *RPC) sendMessageRequest(url string, payload []byte) (*http.Response, error) { req, err := http.NewRequest("POST", url, bytes.NewReader(payload)) if err != nil { - log.Fatalf("Error creating request: %v", err) + panic(fmt.Errorf("Error creating request: %v", err)) } util.BuildRelayHeaders(req, "application/json+protobuf", "*/*") resp, reqErr := r.client.http.Do(req) //r.client.Logger.Info().Any("bodyLength", len(payload)).Any("url", url).Any("headers", resp.Request.Header).Msg("RPC Request Headers") if reqErr != nil { - log.Fatalf("Error making request: %v", err) + panic(fmt.Errorf("Error making request: %v", err)) } return resp, reqErr } diff --git a/libgm/session_handler.go b/libgm/session_handler.go index 4d2c89a..b975ad8 100644 --- a/libgm/session_handler.go +++ b/libgm/session_handler.go @@ -3,7 +3,6 @@ package libgm import ( "encoding/json" "fmt" - "log" "time" "golang.org/x/exp/slices" @@ -72,7 +71,7 @@ func (c *Client) createAndSendRequest(instructionId int64, ttl int64, newSession encodedData := payload.NewEncodedPayload(requestId, instruction.Opcode, encryptedData, c.sessionHandler.sessionId) encodedStr, encodeErr := crypto.EncodeProtoB64(encodedData) if encodeErr != nil { - log.Fatalf("Failed to encode data: %v", encodeErr) + panic(fmt.Errorf("Failed to encode data: %w", encodeErr)) } messageData := payload.NewMessageData(requestId, encodedStr, instruction.RoutingOpCode, instruction.MsgType) authMessage := payload.NewAuthData(requestId, c.rpcKey, &binary.Date{Year: 2023, Seq1: 6, Seq2: 8, Seq3: 4, Seq4: 6}) @@ -147,14 +146,14 @@ func (s *SessionHandler) sendAckRequest() { } dataArray, err := pblite.Serialize(ackMessagePayload.ProtoReflect()) if err != nil { - log.Fatal(err) + panic(err) } ackMessages := make([][]interface{}, 0) for _, reqId := range s.ackMap { ackMessageData := &binary.AckMessageData{RequestId: reqId, Device: s.client.devicePair.Browser} ackMessageDataArr, err := pblite.Serialize(ackMessageData.ProtoReflect()) if err != nil { - log.Fatal(err) + panic(err) } ackMessages = append(ackMessages, ackMessageDataArr) s.ackMap = util.RemoveFromSlice(s.ackMap, reqId) @@ -162,20 +161,20 @@ func (s *SessionHandler) sendAckRequest() { dataArray = append(dataArray, ackMessages) jsonData, jsonErr := json.Marshal(dataArray) if jsonErr != nil { - log.Fatal(err) + panic(err) } _, err = s.client.rpc.sendMessageRequest(util.ACK_MESSAGES, jsonData) if err != nil { - log.Fatal(err) + panic(err) } - log.Println("[ACK] Sent Request") + s.client.Logger.Debug().Msg("[ACK] Sent Request") } func (s *SessionHandler) NewResponse(response *binary.RPCResponse) (*Response, error) { //s.client.Logger.Debug().Any("rpcResponse", response).Msg("Raw rpc response") decodedData, err := crypto.DecodeEncodedResponse(response.Data.EncodedData) if err != nil { - log.Fatal(err) + panic(err) return nil, err } return &Response{