diff --git a/internal/netutil/doc.go b/internal/netutil/doc.go index 5de0271..6ef7981 100644 --- a/internal/netutil/doc.go +++ b/internal/netutil/doc.go @@ -1,5 +1,5 @@ -// Package netutil contém utilitários internos para operações de rede. +// Package netutil contains internal utilities for network operations. // -// Provê verificações que não fazem parte da API pública do catnet-core, -// incluindo a validação rígida de formato de IPs (ex: ValidateIPv4). +// Provides checks that are not part of the public API of catnet-core, +// including strict format validation of IPs (e.g. ValidateIPv4). package netutil diff --git a/pkg/coreerr/doc.go b/pkg/coreerr/doc.go index 1fba70a..2eef298 100644 --- a/pkg/coreerr/doc.go +++ b/pkg/coreerr/doc.go @@ -1,12 +1,12 @@ -// Package coreerr define os erros sentinelas da biblioteca. +// Package coreerr defines the sentinel errors of the library. // -// Centraliza todas as definições de erros conhecidos (timeout, input inválido, -// cancelamento, erros de exportação) para que consumidores da API -// possam realizar comparações via errors.Is() com segurança. +// Centralizes all definitions of known errors (timeout, invalid input, +// cancellation, export errors) so that API consumers +// can safely perform comparisons via errors.Is(). // -// Principais exportações: -// - ErrInvalidInput: Erros de formato em IP ou configurações. -// - ErrTimeout: Erros indicando que uma operação expirou o tempo. -// - ErrCancelled: Indica que o contexto da varredura foi cancelado. -// - ErrExport: Erros durante a serialização de dados. +// Main exports: +// - ErrInvalidInput: Format errors in IP or configurations. +// - ErrTimeout: Errors indicating that an operation timed out. +// - ErrCancelled: Indicates that the scan context was cancelled. +// - ErrExport: Errors during data serialization. package coreerr diff --git a/pkg/discovery/doc.go b/pkg/discovery/doc.go index e1e7120..d70cd01 100644 --- a/pkg/discovery/doc.go +++ b/pkg/discovery/doc.go @@ -1,11 +1,11 @@ -// Package discovery implementa a detecção de atributos de hosts na rede. +// Package discovery implements the detection of host attributes on the network. // -// Oferece abstrações multiplataforma para detecção de liveness via ICMP (Ping), -// resolução reversa de DNS e obtenção de endereços MAC através da tabela ARP local. -// Implementações específicas para Windows e POSIX estão disponíveis internamente. +// Offers cross-platform abstractions for liveness detection via ICMP (Ping), +// reverse DNS resolution and MAC address retrieval through the local ARP table. +// Specific implementations for Windows and POSIX are available internally. // -// Principais exportações: -// - Ping: Envia uma requisição ICMP Echo para verificar se um host está ativo. -// - ReverseDNS: Obtém o hostname associado a um endereço IP. -// - GetMAC: Obtém o endereço MAC correspondente a um IP. +// Main exports: +// - Ping: Sends an ICMP Echo request to check if a host is active. +// - ReverseDNS: Obtains the hostname associated with an IP address. +// - GetMAC: Obtains the MAC address corresponding to an IP. package discovery diff --git a/pkg/discovery/net.go b/pkg/discovery/net.go index d48d845..2965abe 100644 --- a/pkg/discovery/net.go +++ b/pkg/discovery/net.go @@ -8,7 +8,7 @@ import ( "github.com/catnet-io/engine/internal/netutil" ) -// Ping realiza um ping ICMP na máquina com timeout em milissegundos. +// Ping performs an ICMP ping on the machine with a timeout in milliseconds. func Ping(ctx context.Context, ip string, timeoutMs int) bool { if err := netutil.ValidateIPv4(ip); err != nil { return false @@ -16,7 +16,7 @@ func Ping(ctx context.Context, ip string, timeoutMs int) bool { return osPing(ctx, ip, timeoutMs) } -// ReverseDNS resolve o nome do host do endereço IP dado. +// ReverseDNS resolves the hostname of the given IP address. func ReverseDNS(ctx context.Context, ip string) string { if err := netutil.ValidateIPv4(ip); err != nil { return "" @@ -28,7 +28,7 @@ func ReverseDNS(ctx context.Context, ip string) string { return "" } -// GetMAC tenta obter o endereço MAC da máquina alvo. +// GetMAC attempts to obtain the MAC address of the target machine. func GetMAC(ctx context.Context, ip string) string { if err := netutil.ValidateIPv4(ip); err != nil { return "" diff --git a/pkg/discovery/os_posix.go b/pkg/discovery/os_posix.go index 99540f2..3019c9b 100644 --- a/pkg/discovery/os_posix.go +++ b/pkg/discovery/os_posix.go @@ -13,7 +13,7 @@ import ( "strings" ) -// osPing faz ping em sistemas POSIX +// osPing performs a ping on POSIX systems func osPing(ctx context.Context, ip string, timeoutMs int) bool { if net.ParseIP(ip) == nil { return false @@ -40,7 +40,7 @@ func osPing(ctx context.Context, ip string, timeoutMs int) bool { return cmd.Run() == nil } -// osGetMAC obtém o MAC em sistemas POSIX +// osGetMAC obtains the MAC on POSIX systems // ⚡ Bolt Optimization: Read directly from /proc/net/arp on Linux before falling back to `arp -an` exec. // This avoids expensive fork/exec overhead for a 100x+ speedup during concurrent scans. func osGetMAC(ctx context.Context, ip string) string { diff --git a/pkg/discovery/os_windows.go b/pkg/discovery/os_windows.go index e1afb32..777183e 100644 --- a/pkg/discovery/os_windows.go +++ b/pkg/discovery/os_windows.go @@ -18,7 +18,7 @@ var ( sendARP = iphlpapi.NewProc("SendARP") ) -// osPing faz ping no Windows +// osPing performs a ping on Windows // ⚡ Bolt Optimization: Use native IcmpSendEcho from iphlpapi.dll instead of spawning ping.exe. // This avoids process-creation overhead on Windows for massive concurrent scans. func osPing(ctx context.Context, ip string, timeoutMs int) bool { @@ -87,7 +87,7 @@ func osPing(ctx context.Context, ip string, timeoutMs int) bool { } } -// osGetMAC obtém o MAC usando SendARP no Windows +// osGetMAC obtains the MAC using SendARP on Windows func osGetMAC(ctx context.Context, ip string) string { if ctx.Err() != nil { return "" @@ -105,11 +105,11 @@ func osGetMAC(ctx context.Context, ip string) string { go func() { var mac [6]byte macLen := uint32(len(mac)) - // Segurança: mac é um array de tamanho fixo [6]byte alocado na stack. - // macLen é inicializado com len(mac) == 6 antes da chamada. - // O acesso via unsafe.Pointer é seguro porque o array não escapa do - // escopo e seu tamanho é conhecido em tempo de compilação. - // A validação `macLen == 6` após o retorno garante dados não corrompidos. + // Security: mac is a fixed size array [6]byte allocated on the stack. + // macLen is initialized with len(mac) == 6 before the call. + // Access via unsafe.Pointer is safe because the array does not escape the + // scope and its size is known at compile time. + // The validation `macLen == 6` after the return guarantees uncorrupted data. ret, _, _ := sendARP.Call( uintptr(destIPUint32), 0, diff --git a/pkg/engine/doc.go b/pkg/engine/doc.go index 6160042..d6fe1a2 100644 --- a/pkg/engine/doc.go +++ b/pkg/engine/doc.go @@ -1,11 +1,11 @@ -// Package engine orquestra a execução concorrente de varreduras na rede. +// Package engine orchestrates concurrent network scans. // -// O pacote é o ponto de entrada principal do catnet-core, fornecendo a -// função StartScan para gerenciar pools de goroutines, timeouts de -// execução e a emissão de eventos assíncronos durante a varredura. +// The package is the main entry point for catnet-core, providing the +// StartScan function to manage goroutine pools, timeouts, +// and the emission of asynchronous events during the scan. // -// Principais exportações: -// - StartScan: Inicia uma varredura de rede. -// - ScanConfig: Configurações como limites de concorrência e timeouts. -// - EventCallback: Tipo para recebimento de eventos de progresso e resultados. +// Main exports: +// - StartScan: Starts a network scan. +// - ScanConfig: Configuration such as concurrency limits and timeouts. +// - EventCallback: Type for receiving progress and result events. package engine diff --git a/pkg/exporter/doc.go b/pkg/exporter/doc.go index 962513b..21d944a 100644 --- a/pkg/exporter/doc.go +++ b/pkg/exporter/doc.go @@ -1,10 +1,10 @@ -// Package exporter lida com a formatação e serialização de relatórios. +// Package exporter handles the formatting and serialization of reports. // -// Suporta a conversão de ScanReport em formatos padronizados (JSON, XML, CSV) -// garantindo que as exportações evitem problemas de segurança como CSV Injection. +// Supports the conversion of ScanReport into standardized formats (JSON, XML, CSV) +// ensuring that exports avoid security issues like CSV Injection. // -// Principais exportações: -// - ExportJSON: Exporta relatórios como JSON indentado. -// - ExportXML: Exporta relatórios como XML válido. -// - ExportCSV: Exporta relatórios para CSV, tratando injeção de fórmulas. +// Main exports: +// - ExportJSON: Exports reports as indented JSON. +// - ExportXML: Exports reports as valid XML. +// - ExportCSV: Exports reports to CSV, handling formula injection. package exporter diff --git a/pkg/fingerprint/doc.go b/pkg/fingerprint/doc.go index e267dc4..44b1733 100644 --- a/pkg/fingerprint/doc.go +++ b/pkg/fingerprint/doc.go @@ -1,10 +1,10 @@ // Package fingerprint provides heuristic and banner-based operating system // and device type detection mechanisms. // -// Principais exportações: -// - Fingerprint: Orquestra detecção de SO, tipo de dispositivo e vendor. -// - GrabBanners: Coleta banners de portas abertas via conexão TCP. -// - GuessOSFromTTL: Detecta família de SO a partir do valor TTL. -// - VendorFromMAC: Identifica fabricante a partir do prefixo OUI do MAC. -// - OsFromBanners: Infere SO e tipo de dispositivo a partir de banners coletados. +// Main exports: +// - Fingerprint: Orchestrates OS, device type, and vendor detection. +// - GrabBanners: Collects banners of open ports via TCP connection. +// - GuessOSFromTTL: Detects OS family from TTL value. +// - VendorFromMAC: Identifies the manufacturer from the MAC OUI prefix. +// - OsFromBanners: Infers OS and device type from collected banners. package fingerprint diff --git a/pkg/ports/doc.go b/pkg/ports/doc.go index 95b61c5..0cb597a 100644 --- a/pkg/ports/doc.go +++ b/pkg/ports/doc.go @@ -1,9 +1,9 @@ -// Package ports implementa varredura concorrente de portas TCP. +// Package ports implements concurrent TCP port scanning. // -// Utiliza tentativas de conexão com controle de simultaneidade interno -// via semáforos para evitar exaustão de descritores de arquivo, -// retornando de forma determinística portas que aceitam conexões ativas. +// Uses connection attempts with internal concurrency control +// via semaphores to prevent file descriptor exhaustion, +// deterministically returning ports that accept active connections. // -// Principais exportações: -// - ScanPorts: Varre uma lista de portas de um host de modo concorrente. +// Main exports: +// - ScanPorts: Concurrently scans a list of ports on a host. package ports diff --git a/pkg/ports/scanner.go b/pkg/ports/scanner.go index 52208bd..1ea867c 100644 --- a/pkg/ports/scanner.go +++ b/pkg/ports/scanner.go @@ -11,11 +11,11 @@ import ( "github.com/catnet-io/engine/internal/netutil" ) -// ScanConcurrency define o número máximo de conexões TCP simultâneas por IP. +// ScanConcurrency defines the maximum number of simultaneous TCP connections per IP. const ScanConcurrency = 10 -// ScanPorts varre uma lista de portas em um IP concorrentemente e retorna os resultados via canal. -// O canal é fechado automaticamente quando todas as portas foram testadas. +// ScanPorts scans a list of ports on an IP concurrently and returns the results via channel. +// The channel is automatically closed when all ports have been tested. func ScanPorts(ctx context.Context, ip string, ports []int, timeoutMs int) <-chan int { out := make(chan int, len(ports)) if err := netutil.ValidateIPv4(ip); err != nil { diff --git a/pkg/results/doc.go b/pkg/results/doc.go index e97c211..2af7abe 100644 --- a/pkg/results/doc.go +++ b/pkg/results/doc.go @@ -1,10 +1,10 @@ -// Package results define os modelos de dados para os resultados de varredura. +// Package results defines the data models for the scan results. // -// Este pacote contém as estruturas de dados fundamentais para representar -// hosts, portas abertas, status de atividade e relatórios consolidados, -// mantendo consistência na representação dos dados exportados. +// This package contains the fundamental data structures to represent +// hosts, open ports, activity status, and consolidated reports, +// maintaining consistency in the representation of exported data. // -// Principais exportações: -// - ScanReport: Representa o relatório final e sumarizado de uma varredura. -// - DeviceInfo: Representa os detalhes descobertos de um host individual. +// Main exports: +// - ScanReport: Represents the final and summarized report of a scan. +// - DeviceInfo: Represents the discovered details of an individual host. package results diff --git a/pkg/results/report.go b/pkg/results/report.go index 81b8625..72b3cea 100644 --- a/pkg/results/report.go +++ b/pkg/results/report.go @@ -2,7 +2,7 @@ package results import "time" -// ScanReport encapsula o resultado completo de uma varredura. +// ScanReport encapsulates the complete result of a scan. type ScanReport struct { SchemaVersion string `json:"schemaVersion"` StartTime time.Time `json:"startTime"` @@ -12,7 +12,7 @@ type ScanReport struct { Devices []DeviceInfo `json:"devices"` } -// NewScanReport cria um novo relatório de varredura. +// NewScanReport creates a new scan report. func NewScanReport() *ScanReport { return &ScanReport{ SchemaVersion: "2.0.0", diff --git a/pkg/topology/builder.go b/pkg/topology/builder.go index ad91d9b..32ac84b 100644 --- a/pkg/topology/builder.go +++ b/pkg/topology/builder.go @@ -72,7 +72,7 @@ func BuildGraph(report *results.ScanReport) *TopologyGraph { } // Find /24 subnet - // âš¡ Bolt Optimization: Use zero-allocation counting and slicing + // ⚡ Bolt Optimization: Use zero-allocation counting and slicing // Avoids massive allocation overhead and ensures exactly 3 dots (valid IPv4) dots := 0 thirdDotIdx := -1 @@ -126,7 +126,7 @@ func BuildGraph(report *results.ScanReport) *TopologyGraph { if src > dst { src, dst = dst, src } - // âš¡ Bolt Optimization: Use zero-allocation struct key instead of string concatenation. + // ⚡ Bolt Optimization: Use zero-allocation struct key instead of string concatenation. // This prevents massive memory allocation and GC overhead in dense O(N^2) graphs. key := edgeKey{src, dst} if _, exists := addedHostEdges[key]; !exists {