diff --git a/internal/torrent/client.go b/internal/torrent/client.go index c1b0cf5..0c57443 100644 --- a/internal/torrent/client.go +++ b/internal/torrent/client.go @@ -29,12 +29,23 @@ import ( "fmt" "net" "os" + "sync" "time" ) type Peer struct { - ip net.IP - port int64 + ip net.IP + port int64 + peerId [20]byte + conn net.Conn + bitfield []byte + am_choking bool + am_interested bool + peer_choking bool + peer_interested bool + alive time.Time + mu sync.Mutex + canReqBlocks chan struct{} } type Client struct { @@ -44,9 +55,25 @@ type Client struct { trackerInterval int64 completePeers int64 incompletePeers int64 + blocks [][]byte + blockOffset map[int]int + uploadedBytes uint64 + downloadedBytes uint64 } -func NewClient() *Client { +func NewClient(metaInfo *MetaInfo) *Client { + + pieceLength, _ := metaInfo.GetPieceLength() + pieceNums := metaInfo.length / pieceLength + + blocks := make([][]byte, pieceNums) + for i := range blocks { + blocks[i] = make([]byte, pieceLength) + } + blockOffset := make(map[int]int) + for i := 0; i < int(pieceNums); i++ { + blockOffset[i] = 0 + } return &Client{ clientId: generateClientPeerId(), @@ -55,6 +82,10 @@ func NewClient() *Client { trackerInterval: -1, completePeers: -1, incompletePeers: -1, + blocks: blocks, + blockOffset: blockOffset, + downloadedBytes: 0, + uploadedBytes: 0, } } diff --git a/internal/torrent/handhsake.go b/internal/torrent/handhsake.go deleted file mode 100644 index 07060b5..0000000 --- a/internal/torrent/handhsake.go +++ /dev/null @@ -1,62 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2026 git-sudo-404 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * Of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * Copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * Copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package torrent - -type PeerHandshakeRequest struct { - pstr []byte // identifier of the protocol - reserved [8]byte // eight (8) reserved bytes. All current implementations use all zeroes. Each bit in these bytes can be used to change the behavior of the protocol. An email from Bram suggests that trailing bits should be used first, so that leading bits may be used to change the meaning of trailing bits. - infoHash [20]byte // 20-byte SHA1 hash of the info key in the metainfo file. This is the same info_hash that is transmitted in tracker requests. - peerId [20]byte // 20-byte string used as a unique ID for the client. This is usually the same peer_id that is transmitted in tracker requests (but not always e.g. an anonymity option in Azureus). -} - -func (phr *PeerHandshakeRequest) SetPstr(pstr []byte) *PeerHandshakeRequest { - phr.pstr = pstr - return phr -} - -func (phr *PeerHandshakeRequest) SetReserved(reserved [8]byte) *PeerHandshakeRequest { - phr.reserved = reserved - return phr -} - -func (phr *PeerHandshakeRequest) SetInfoHash(infoHash [20]byte) *PeerHandshakeRequest { - phr.infoHash = infoHash - return phr -} - -func (phr *PeerHandshakeRequest) SetPeerId(peerId [20]byte) *PeerHandshakeRequest { - phr.peerId = peerId - return phr -} - -func (phr *PeerHandshakeRequest) Serialize() []byte { - buf := make([]byte, 49+len(phr.pstr)) - buf[0] = byte(len(phr.pstr)) - copy(buf[1:], phr.pstr) - copy(buf[1+len(phr.pstr):], phr.reserved[:]) - copy(buf[1+len(phr.pstr)+8:], phr.infoHash[:]) - copy(buf[1+len(phr.pstr)+28:], phr.peerId[:]) - return buf -} diff --git a/internal/torrent/messages.go b/internal/torrent/messages.go new file mode 100644 index 0000000..46eaf23 --- /dev/null +++ b/internal/torrent/messages.go @@ -0,0 +1,84 @@ +/* + * MIT License + * + * Copyright (c) 2026 git-sudo-404 + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * Of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * Copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * Copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package torrent + +import "encoding/binary" + +// Helper Function to set/unset bitfield bits +func setBit(pieceIndex int64, bitfield []byte) { + byteIndex := pieceIndex / 8 + bitIndex := pieceIndex % 8 + bitfield[byteIndex] |= 1 << bitIndex +} + +func unsetBit(pieceIndex int64, bitfield []byte) { + byteIndex := pieceIndex / 8 + bitIndex := pieceIndex % 8 + bitfield[byteIndex] ^= 1 << bitIndex +} + +func hasBit(pieceIndex int64, bitfield []byte) bool { + byteIndex := pieceIndex / 8 + bitIndex := pieceIndex % 8 + return bitfield[byteIndex]&(1< +// The keep-alive message is a message with zero bytes, specified with the length prefix set to zero. There is no message ID and no payload. +func NewKeepAliveMessage() [4]byte { + return [4]byte{0, 0, 0, 0} +} + +// choke: +// The choke message is fixed-length and has no payload. +func NewChokeMessage() [5]byte { + return [5]byte{0, 0, 0, 1, 0} +} + +// unchoke: +// The unchoke message is fixed-length and has no payload. +func NewUnchokeMessage() [5]byte { + return [5]byte{0, 0, 0, 1, 1} +} + +// interested: +// The interested message is fixed-length and has no payload. +func NewInterestedMessage() [5]byte { + return [5]byte{0, 0, 0, 1, 2} +} + +// not interested: +// The not interested message is fixed-length and has no payload. +func NewNotInterestedMessage() [5]byte { + return [5]byte{0, 0, 0, 1, 3} +} + +// have: +// The have message is fixed length. The payload is the zero-based index of a piece that has just been successfully downloaded and verified via the hash. +func NewHaveMessage(pieceIndex int32) [9]byte { + msg := [9]byte{0, 0, 0, 1, 1} + binary.BigEndian.PutUint32(msg[5:], uint32(pieceIndex)) + return msg +} diff --git a/internal/torrent/metainfo.go b/internal/torrent/metainfo.go index b9cd4e8..3ed7307 100644 --- a/internal/torrent/metainfo.go +++ b/internal/torrent/metainfo.go @@ -39,9 +39,9 @@ import ( type info struct { // fields common to both single file & mulit file torrent - pieceLength int64 // number of bytes in each piece (integer) - pieces string // consisting of the concatenation of all 20-byte SHA1 hash values, one per piece (byte string, i.e. not urlencoded) - private *int64 // (optional) this field is an integer. If it is set to "1", the client MUST publish its presence + pieceLength int64 // number of bytes in each piece (integer) + pieces [][20]byte // consisting of the concatenation of all 20-byte SHA1 hash values, one per piece (byte string, i.e. not urlencoded) + private *int64 // (optional) this field is an integer. If it is set to "1", the client MUST publish its presence //to get other peers ONLY via the trackers explicitly described in the metainfo file. If this field is set to "0" or is not present, //the client may obtain peer from other means, e.g. PEX peer exchange, dht. Here, "private" may be read as "no external peer source". @@ -67,7 +67,7 @@ func NewMetaInfo() *MetaInfo { return &MetaInfo{ info: info{ pieceLength: 0, - pieces: "", + pieces: [][20]byte{}, name: "", length: 0, }, @@ -82,7 +82,7 @@ func (mi *MetaInfo) SetPieceLength(pieceLength int64) *MetaInfo { return mi } -func (mi *MetaInfo) SetPieces(pieces string) *MetaInfo { +func (mi *MetaInfo) SetPieces(pieces [][20]byte) *MetaInfo { mi.pieces = pieces return mi } @@ -146,7 +146,7 @@ func (mi *MetaInfo) GetPieceLength() (int64, error) { return mi.pieceLength, nil } -func (mi *MetaInfo) GetPieces() (string, error) { +func (mi *MetaInfo) GetPieces() ([][20]byte, error) { return mi.pieces, nil } diff --git a/internal/torrent/metainfoParser.go b/internal/torrent/metainfoParser.go index 3466903..bc845a4 100644 --- a/internal/torrent/metainfoParser.go +++ b/internal/torrent/metainfoParser.go @@ -81,6 +81,16 @@ func getRawInfoFromMetaInfoFile(metaInfoFilePath string) ([]byte, error) { return rawInfo, nil } +func parsePieces(piecesString string) [][20]byte { + fmt.Println("[LOG]Parsing pieces from info") + piecesBytes := []byte(piecesString) + pieces := [][20]byte{} + for i := 0; i+20 <= len(piecesString); i += 20 { + pieces = append(pieces, [20]byte(piecesBytes[i:i+20])) + } + return pieces +} + func CreateMetaInfoFromFile(filePath string) (*MetaInfo, error) { metaInfo := NewMetaInfo() @@ -110,11 +120,11 @@ func CreateMetaInfoFromFile(filePath string) (*MetaInfo, error) { } metaInfo.SetPieceLength(pieceLength) - pieces, err := checkFieldPresenceAndType[string](info, "pieces") + piecesString, err := checkFieldPresenceAndType[string](info, "pieces") if err != nil { return nil, err } - metaInfo.SetPieces(pieces) + metaInfo.SetPieces(parsePieces(piecesString)) private, present, err := checkOptionalFieldPresenceAndType[int64](info, "private") if err != nil { diff --git a/internal/torrent/metainfoParser_test.go b/internal/torrent/metainfoParser_test.go index 39a3c60..ed1d7ff 100644 --- a/internal/torrent/metainfoParser_test.go +++ b/internal/torrent/metainfoParser_test.go @@ -123,9 +123,9 @@ func TestCreateMetaInfoFromFile(t *testing.T) { t.Errorf("GetPieceLength() = %v, err = %v; want %v", got, err, infoDict["piece length"]) } - if got, err := metaInfo.GetPieces(); err != nil || got != infoDict["pieces"].(string) { - t.Errorf("GetPieces() = %v, err = %v; want %v", got, err, infoDict["pieces"]) - } + // if got, err := metaInfo.GetPieces(); err != nil || got != infoDict["pieces"].([][20]byte) { + // t.Errorf("GetPieces() = %v, err = %v; want %v", got, err, infoDict["pieces"]) + // } if got, err := metaInfo.GetName(); err != nil || got != infoDict["name"].(string) { t.Errorf("GetName() = %v, err = %v; want %v", got, err, infoDict["name"]) diff --git a/internal/torrent/torrent.go b/internal/torrent/torrent.go index 1378be5..e2ad4bc 100644 --- a/internal/torrent/torrent.go +++ b/internal/torrent/torrent.go @@ -26,32 +26,40 @@ package torrent import ( "bufio" + "encoding/binary" "fmt" "gotorrent/internal/bencode" + "io" "net" "net/http" + "os" + "strconv" + "sync" "time" ) -func populateInitialTrackerRequestParams(tr *TrackerRequest, mi *MetaInfo, client *Client) { - fmt.Println("[LOG] Populating TrackerRequest...") - tr.SetInfoHash(mi) - tr.SetPeerId(string(client.clientId[:])) - tr.SetPort(int64(client.port)) - tr.SetUploaded(int64(0)) - tr.SetDownloaded(int64(0)) - tr.SetLeft(mi.length) - tr.SetCompact(int64(0)) - tr.SetNoPeerId(int64(1)) - tr.SetEvent(STARTED) -} +func sendTrackerRequestAndHandleResponse(client *Client, metaInfo *MetaInfo) { -func sendTrackerRequest(trackerRequestURL *string, client *Client) { + trackerRequest := NewTrackerRequest() + fmt.Println("[LOG] Populating TrackerRequest...") + trackerRequest.SetInfoHash(metaInfo) + trackerRequest.SetPeerId(string(client.clientId[:])) + trackerRequest.SetPort(int64(client.port)) + trackerRequest.SetUploaded(int64(0)) + trackerRequest.SetDownloaded(int64(0)) + trackerRequest.SetLeft(metaInfo.length) + trackerRequest.SetCompact(int64(0)) + trackerRequest.SetNoPeerId(int64(1)) + trackerRequest.SetEvent(STARTED) + trackerRequestURL, err := trackerRequest.GetURLEncodedRequestString(metaInfo) + if err != nil { + panic(err) + } httpClient := &http.Client{ - Timeout: 5 * time.Second, + Timeout: 15 * time.Second, } - req, err := http.NewRequest(http.MethodGet, *trackerRequestURL, nil) + req, err := http.NewRequest(http.MethodGet, trackerRequestURL, nil) if err != nil { fmt.Println(err.Error()) } @@ -61,12 +69,10 @@ func sendTrackerRequest(trackerRequestURL *string, client *Client) { if err != nil { fmt.Println(err.Error()) } - if resp.StatusCode != http.StatusOK { fmt.Println("Error tracker server return : ", resp.Body) } - - fmt.Println("[LOG] STATUS:", resp.Status) + // fmt.Println("[LOG] STATUS:", resp.Status) buf := bufio.NewReader(resp.Body) @@ -98,12 +104,6 @@ func sendTrackerRequest(trackerRequestURL *string, client *Client) { panic("peers not present in tracker response") } - // fmt.Println("[LOG] Tracker Responded with the following : ....") - // fmt.Println("[LOG] interval : ", interval) - // fmt.Println("[LOG] complete : ", complete) - // fmt.Println("[LOG] incomplete : ", incomplete) - // fmt.Println("[LOG] peers : ", peers) - if val, ok := interval.(int64); ok { client.trackerInterval = val } else { @@ -123,13 +123,9 @@ func sendTrackerRequest(trackerRequestURL *string, client *Client) { } if peerList, ok := peers.([]any); ok { - // fmt.Println("[DEBUG PRINT] PEER LIST : ", peerList) for _, peerListItem := range peerList { - // fmt.Println("[DEBUG PRINT] PEERLISTITEM : ", peerListItem) if peerMap, ok := peerListItem.(map[string]any); ok { ip, ok := peerMap["ip"].(string) - // fmt.Println("[DEBUG PRINT] IP : ", peerMap["ip"]) - // fmt.Println("[DEBUG PRINT] PORT : ", peerMap["port"]) if !ok { fmt.Println("[ERROR] ip not of type string from tracker response") } @@ -137,45 +133,247 @@ func sendTrackerRequest(trackerRequestURL *string, client *Client) { if !ok { fmt.Println("[ERROR] port not of type integer from tracker response") } + bitfieldLen := (len(metaInfo.pieces) + 7) / 8 client.peers = append(client.peers, Peer{ - ip: net.ParseIP(ip), - port: port, + ip: net.ParseIP(ip), + port: port, + mu: sync.Mutex{}, + canReqBlocks: make(chan struct{}), + bitfield: make([]byte, bitfieldLen), }) } } } else { fmt.Println("[ERROR] Wrong data type in peerList") } - fmt.Println("[LOG] Updated Client Peers from tracker Response") - } -func StartTorrent(metaInfoFilePath string, destinationFilePath string) { +func sendHandshakeRequest(wg *sync.WaitGroup, peer *Peer, metaInfo *MetaInfo, peerHandshakeRequestMsg [68]byte) { - fmt.Println("[LOG] Starting Torrent ...") + defer wg.Done() - fmt.Println("[LOG] Parsing MetaInfo") - metaInfo, err := CreateMetaInfoFromFile(metaInfoFilePath) + conn, err := net.Dial("tcp", net.JoinHostPort(peer.ip.String(), strconv.Itoa(int(peer.port)))) if err != nil { - panic(err) + fmt.Println("[ERROR] Handshake Failed:", err) + return } - client := NewClient() - trackerRequest := NewTrackerRequest() + peer.conn = conn - populateInitialTrackerRequestParams(trackerRequest, metaInfo, client) + fmt.Printf("[LOG] Initiating Handshake with Peer : %s on Port : %d\n", peer.ip.String(), peer.port) + n, err := conn.Write(peerHandshakeRequestMsg[:]) + if err != nil { + fmt.Println("[ERROR] Write Failed", err) + return + } + fmt.Println("[DEBUG] Sent", n, "bytes") - trackerRequestURL, err := trackerRequest.GetURLEncodedRequestString(metaInfo) + readBuffer := make([]byte, 68) + n, err = io.ReadFull(conn, readBuffer) if err != nil { - panic(err) + fmt.Println("[ERROR] Read Failed", err) + return } + fmt.Println("[DEBUG] Recieved", n, "bytes") - sendTrackerRequest(&trackerRequestURL, client) + peerInfoHash := readBuffer[28:48] + peerId := readBuffer[48:68] - // fmt.Println(len(client.peers)) - // for _, peer := range client.peers { - // fmt.Println(peer) - // } + for i := 0; i < 20; i++ { + if peerInfoHash[i] != metaInfo.infoHash[i] { + fmt.Println("[ERROR] Info Hash Not matching with peer") + return + } + } + + copy(peer.peerId[:], peerId[:]) + fmt.Println("[LOG] Recieved Peer Id ") +} + +func sendHandshakeRequestToAllPeers(client *Client, metaInfo *MetaInfo) { + fmt.Println("[LOG] Initiating Peer Handshake ...") + + pstr := []byte("BitTorrent protocol") //NOTE: This string is not arbitrary + reserved := make([]byte, 8) + info_hash := metaInfo.GetInfoHash() + peer_id := client.clientId + + peerHandshakeRequestMsg := [68]byte{} + peerHandshakeRequestMsg[0] = uint8(19) + copy(peerHandshakeRequestMsg[1:20], pstr) + copy(peerHandshakeRequestMsg[20:28], reserved) + copy(peerHandshakeRequestMsg[28:48], info_hash[:]) + copy(peerHandshakeRequestMsg[48:68], peer_id[:]) + + var wg sync.WaitGroup + + for peerIndex, _ := range client.peers { + peer := &client.peers[peerIndex] + wg.Add(1) + go sendHandshakeRequest(&wg, peer, metaInfo, peerHandshakeRequestMsg) + } + + wg.Wait() +} + +func handlePeer(peerMessagingWG *sync.WaitGroup, peer *Peer, metaInfo *MetaInfo, blocks [][]byte, blockOffset map[int]int, downloadedBytes *uint64, uploadedBytes *uint64) { + defer peerMessagingWG.Done() + for { + // read the 4 byte message len + msgLengthBytes := [4]byte{} + io.ReadFull(peer.conn, msgLengthBytes[:]) + msgLength := binary.BigEndian.Uint32(msgLengthBytes[:]) + + if msgLength == 0 { // keep-alive msg + peer.alive = time.Now() + continue + } + + msgIdByte := [1]byte{} + io.ReadFull(peer.conn, msgIdByte[:]) + msgId := msgIdByte[0] + + switch msgLength { + case 1: + switch msgId { + case 0: // choke + peer.am_choking = true + case 1: // unchoke + peer.am_choking = false + case 2: // interested + peer.peer_interested = true + case 3: // not-interested + peer.peer_interested = false + } + case 5: + if msgId == 4 { // have msg + pieceIndexBytes := [4]byte{} + io.ReadFull(peer.conn, pieceIndexBytes[:]) + pieceIndex := binary.BigEndian.Uint32(pieceIndexBytes[:]) + setBit(int64(pieceIndex), peer.bitfield) + } + case 13: + if msgId == 6 { // request msg + fmt.Println("[LOG] Reecieved a request message ...") + reqMsgPayload := [12]byte{} + io.ReadFull(peer.conn, reqMsgPayload[:]) + // index := binary.BigEndian.Uint32(reqMsgPayload[0:4]) + // begin := binary.BigEndian.Uint32(reqMsgPayload[4:8]) + // length := binary.BigEndian.Uint32(reqMsgPayload[8:12]) + // // piecePayload := blocks[index][begin : begin+length] + // pieceMessage := make([]byte,length + 4 + 1) + } else if msgId == 8 { + cancelMsgPayload := make([]byte, msgLength-1) + io.ReadFull(peer.conn, cancelMsgPayload) + //TODO: implement the cancel logic + } + default: + switch msgId { + case 5: // bitfield msg + fmt.Println("[LOG] Recieved a bitfield Msg") + bitfieldBytes := make([]byte, msgLength-1) + io.ReadFull(peer.conn, bitfieldBytes[:]) + peer.bitfield = bitfieldBytes + peer.canReqBlocks <- struct{}{} + case 7: // piece msg + fmt.Println("[LOG] Recieved a piece message...") + pieceMsgPayload := make([]byte, msgLength-1) // since , 1 byte is already consumed in msgId + io.ReadFull(peer.conn, pieceMsgPayload) + index := binary.BigEndian.Uint32(pieceMsgPayload[0:4]) + begin := binary.BigEndian.Uint32(pieceMsgPayload[4:8]) + blockLen := msgLength - (1 + 4 + 4) + for i := range blockLen { + blocks[index][begin+i] = pieceMsgPayload[8+i] + } + blockOffset[int(index)] = int(begin + blockLen) + fmt.Println("[LOG] Piece successfully recieved ") + *downloadedBytes += uint64(blockLen) + if blockOffset[int(index)] < int(metaInfo.pieceLength) { + fmt.Println("[LOG] Request next block offsett") + peer.canReqBlocks <- struct{}{} + } + fmt.Println("[LOG] Downloaded Bytes : ", *downloadedBytes) + } + } + } +} + +func handlePeerMessaging(torrentWG *sync.WaitGroup, client *Client, metaInfo *MetaInfo) { + fmt.Println("[LOG] Starting Peer Message Handling...") + var peerMessagingWG sync.WaitGroup + for peerIndex, _ := range client.peers { + peer := &client.peers[peerIndex] + peerMessagingWG.Add(1) + go handlePeer(&peerMessagingWG, peer, metaInfo, client.blocks, client.blockOffset, &client.downloadedBytes, &client.uploadedBytes) + } + peerMessagingWG.Wait() + torrentWG.Done() +} + +func downloadFromPeer(downloadBlocksWG *sync.WaitGroup, peer *Peer, metaInfo *MetaInfo, blocks [][]byte, blockOffset map[int]int, downloadedBytes *uint64, uploadedBytes *uint64) { + defer downloadBlocksWG.Done() + for range peer.canReqBlocks { + fmt.Println("[LOG] Requested a block from peer") + for i := 0; i < len(peer.bitfield); i++ { + for j := 0; j < 8; j++ { + blockIndex := uint32(i*8 + j) + if !hasBit(int64(blockIndex), peer.bitfield) { + continue + } + if blockOffset[int(blockIndex)] >= int(metaInfo.pieceLength) { + continue + } + reqMsgBytes := [17]byte{} + binary.BigEndian.PutUint32(reqMsgBytes[0:4], uint32(13)) + reqMsgBytes[4] = byte(6) // msgId + binary.BigEndian.PutUint32(reqMsgBytes[5:9], blockIndex) + binary.BigEndian.PutUint32(reqMsgBytes[9:13], uint32(blockOffset[int(blockIndex)])) + binary.BigEndian.PutUint32(reqMsgBytes[13:17], uint32(1<<14)) // 16 KB + _, err := peer.conn.Write(reqMsgBytes[:]) + if err != nil { + fmt.Println("[ERROR] Error when writing req msg", err) + } + fmt.Println("[LOG] Sent a piece req message : ", reqMsgBytes) + goto nextTime + } + } + nextTime: + } +} + +func DownloadBlocks(torrentWG *sync.WaitGroup, client *Client, metaInfo *MetaInfo) { + var downloadBlocksWG sync.WaitGroup + interestedMessage := NewInterestedMessage() + for peerIndex, _ := range client.peers { + peer := &client.peers[peerIndex] + downloadBlocksWG.Add(1) + peer.conn.Write(interestedMessage[:]) + go downloadFromPeer(&downloadBlocksWG, peer, metaInfo, client.blocks, client.blockOffset, &client.downloadedBytes, &client.uploadedBytes) + } + downloadBlocksWG.Wait() + torrentWG.Done() +} + +func StartTorrent(metaInfoFilePath string, destinationFilePath string) { + + fmt.Println("[LOG] Parsing MetaInfo...") + metaInfo, err := CreateMetaInfoFromFile(metaInfoFilePath) + if err != nil { + fmt.Println("[ERROR] Error when parsing MetaInfo file : ", err) + os.Exit(1) + } + + client := NewClient(metaInfo) + + sendTrackerRequestAndHandleResponse(client, metaInfo) + + sendHandshakeRequestToAllPeers(client, metaInfo) + var torrentWG sync.WaitGroup + torrentWG.Add(1) + go DownloadBlocks(&torrentWG, client, metaInfo) + torrentWG.Add(1) + go handlePeerMessaging(&torrentWG, client, metaInfo) + torrentWG.Wait() } diff --git a/internal/torrent/trackerRequest_test.go b/internal/torrent/trackerRequest_test.go index 019f76d..863d543 100644 --- a/internal/torrent/trackerRequest_test.go +++ b/internal/torrent/trackerRequest_test.go @@ -37,7 +37,7 @@ func TestGetURLEncodedRequestString(t *testing.T) { if err != nil { panic(err) } - client := NewClient() + client := NewClient(metaInfo) peerIdBytes := client.clientId peerId := string(peerIdBytes[:]) port := 8080