Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions internal/netutil/doc.go
Original file line number Diff line number Diff line change
@@ -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
18 changes: 9 additions & 9 deletions pkg/coreerr/doc.go
Original file line number Diff line number Diff line change
@@ -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
16 changes: 8 additions & 8 deletions pkg/discovery/doc.go
Original file line number Diff line number Diff line change
@@ -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
6 changes: 3 additions & 3 deletions pkg/discovery/net.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@ 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
}
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 ""
Expand All @@ -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 ""
Expand Down
4 changes: 2 additions & 2 deletions pkg/discovery/os_posix.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 {
Expand Down
14 changes: 7 additions & 7 deletions pkg/discovery/os_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 ""
Expand All @@ -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,
Expand Down
16 changes: 8 additions & 8 deletions pkg/engine/doc.go
Original file line number Diff line number Diff line change
@@ -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
14 changes: 7 additions & 7 deletions pkg/exporter/doc.go
Original file line number Diff line number Diff line change
@@ -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
12 changes: 6 additions & 6 deletions pkg/fingerprint/doc.go
Original file line number Diff line number Diff line change
@@ -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
12 changes: 6 additions & 6 deletions pkg/ports/doc.go
Original file line number Diff line number Diff line change
@@ -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
6 changes: 3 additions & 3 deletions pkg/ports/scanner.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
14 changes: 7 additions & 7 deletions pkg/results/doc.go
Original file line number Diff line number Diff line change
@@ -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
4 changes: 2 additions & 2 deletions pkg/results/report.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand All @@ -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",
Expand Down
4 changes: 2 additions & 2 deletions pkg/topology/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down