Skip to content
Merged
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
9 changes: 5 additions & 4 deletions .github/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,12 @@ Found a security problem? Don't open a public issue. Follow the [security policy
}
```

6. **Write comment-based help** with `.SYNOPSIS`, `.DESCRIPTION`, every `.PARAMETER`, at least one `.EXAMPLE`, and a `HelpUri` pointing at the endpoint in Pi-hole's API docs.
7. **Export the function** in both places:
6. **Support `-WhatIf` and `-Confirm` on anything that changes the server.** Add `SupportsShouldProcess = $true` to `[CmdletBinding()]` and wrap the work in `if ($PSCmdlet.ShouldProcess(<target>, <action>)) { ... }`, with the API call inside it, so `-WhatIf` doesn't even log in. A wrapper around another state-changing function passes `-Confirm:$false` to it, so the user is asked only once (see `Add-PiHoleDnsRecord`).
7. **Write comment-based help** with `.SYNOPSIS`, `.DESCRIPTION`, every `.PARAMETER`, at least one `.EXAMPLE`, and a `HelpUri` pointing at the endpoint in Pi-hole's API docs.
8. **Export the function** in both places:
- the `Export-ModuleMember` list in `PiHoleShell/PiHoleShell.psm1`
- `FunctionsToExport` in `PiHoleShell/PiHoleShell.psd1`. This file is saved as UTF-16; keep that encoding when you edit it.
8. **Update the docs:**
9. **Update the docs:**
- Run `tools/Update-ReadmeCommandReference.ps1` to regenerate the README's command reference. A CI check fails if it's out of date.
- Add an entry to `tools/Update-ExampleOutput.ps1`, then run it to regenerate `docs/EXAMPLES.md`. This step needs a test server.

Expand Down Expand Up @@ -63,7 +64,7 @@ New functions should come with an integration test covering normal output, `-Raw

- **PSScriptAnalyzer** must report no issues. Run it locally with `Invoke-ScriptAnalyzer -Path .\PiHoleShell -Recurse`.
- **SonarCloud** must pass its quality gate. In practice that usually means not duplicating code.
- **README sync** must pass (see step 8 above).
- **README sync** must pass (see step 9 above).
- **Pester** integration tests run against the maintainer's own Pi-hole and can take up to an hour. If your PR comes from a fork, the maintainer may run them for you.

## Code of conduct
Expand Down
52 changes: 52 additions & 0 deletions PiHoleShell/Private/Get-PiHoleLogContent.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
function Get-PiHoleLogContent {
#INTERNAL FUNCTION
#
# Shared body of Get-PiHoleLogDnsmasq, Get-PiHoleLogFtl and Get-PiHoleLogWebserver: the three
# /logs/* endpoints take the same nextID parameter and return the same shape.
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "Password")]
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[System.URI]$PiHoleServer,
[Parameter(Mandatory = $true)]
[string]$Password,
[Parameter(Mandatory = $true)]
[string]$Endpoint,
[Nullable[int]]$NextID,
[bool]$IgnoreSsl = $false,
[bool]$RawOutput = $false
)
try {
if ($null -ne $NextID) {
$Endpoint += "?nextID=$NextID"
}

$Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint $Endpoint

if ($RawOutput) {
Write-Output $Response
}

else {
$Log = foreach ($Item in $Response.log) {
[PSCustomObject]@{
Timestamp = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.timestamp).LocalTime
Message = $Item.message
Priority = $Item.prio
}
}

$Object = [PSCustomObject]@{
Log = $Log
NextID = $Response.nextID
Pid = $Response.pid
File = $Response.file
}
Write-Output $Object
}
}

catch {
Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_)
}
}
41 changes: 41 additions & 0 deletions PiHoleShell/Private/Get-PiHoleNetworkInfo.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
function Get-PiHoleNetworkInfo {
#INTERNAL FUNCTION
#
# Shared body of Get-PiHoleNetworkGateway, Get-PiHoleNetworkInterface and
# Get-PiHoleNetworkRoute: each /network/* endpoint takes the same detailed parameter and
# returns its data under one property (Property), converted to PascalCase as-is.
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "Password")]
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[System.URI]$PiHoleServer,
[Parameter(Mandatory = $true)]
[string]$Password,
[Parameter(Mandatory = $true)]
[string]$Endpoint,
[Parameter(Mandatory = $true)]
[string]$Property,
[Nullable[bool]]$Detailed,
[bool]$IgnoreSsl = $false,
[bool]$RawOutput = $false
)
try {
if ($null -ne $Detailed) {
$Endpoint += "?detailed=$($Detailed.ToString().ToLower())"
}

$Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint $Endpoint

if ($RawOutput) {
Write-Output $Response
}
else {
$Object = ConvertTo-PiHolePascalCaseObject -InputObject $Response.$Property
Write-Output $Object
}
}

catch {
Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_)
}
}
40 changes: 40 additions & 0 deletions PiHoleShell/Private/Invoke-PiHoleAction.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
function Invoke-PiHoleAction {
#INTERNAL FUNCTION
#
# Shared body of the parameterless POST /action/* functions (Invoke-PiHoleFlushLogs,
# Invoke-PiHoleFlushNetwork, Restart-PiHoleDnsService), which differ only in their endpoint
# and the Status they report. Callers do their own ShouldProcess check first.
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "Password")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "", Justification = "Every caller checks ShouldProcess before calling this")]
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[System.URI]$PiHoleServer,
[Parameter(Mandatory = $true)]
[string]$Password,
[Parameter(Mandatory = $true)]
[string]$Endpoint,
[Parameter(Mandatory = $true)]
[string]$Status,
[bool]$IgnoreSsl = $false,
[bool]$RawOutput = $false
)

try {
$Response = Invoke-PiHoleApiRequest -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -Endpoint $Endpoint -Method Post

if ($RawOutput) {
Write-Output $Response
}
else {
$Object = [PSCustomObject]@{
Status = $Status
}
Write-Output $Object
}
}

catch {
Write-Error -Message (ConvertTo-PiHoleFriendlyErrorMessage -ErrorRecord $_)
}
}
27 changes: 25 additions & 2 deletions PiHoleShell/Private/Invoke-PiHoleApiRequest.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ function Invoke-PiHoleApiRequest {
# Logs in, calls one API endpoint and always logs out again - the request/session boilerplate
# every public function otherwise repeats. Errors are left to propagate, so callers keep their
# own catch block (and its ConvertTo-PiHoleFriendlyErrorMessage call) unchanged.
#
# Body is passed through as-is: callers serialize JSON bodies themselves (array bodies need
# ConvertTo-Json -InputObject or a leading comma to survive), and a hashtable Body on a Get
# becomes the query string. Form (multipart upload) and OutFile (binary download) are passed
# through the same way, and a Form request gets no ContentType so the multipart one is used.
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "Password")]
param (
[Parameter(Mandatory = $true)]
Expand All @@ -13,18 +18,36 @@ function Invoke-PiHoleApiRequest {
[Parameter(Mandatory = $true)]
[string]$Endpoint,
[string]$Method = "Get",
$Body,
[hashtable]$Form,
[string]$OutFile,
[bool]$IgnoreSsl = $false
)

try {
$Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl
# -ErrorAction Stop so a failed login (wrong password, server unreachable) ends here with
# its one error, instead of also sending the request without a session and reporting a
# second, less useful 401.
$Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -ErrorAction Stop

$Params = @{
Headers = @{sid = $($Sid) }
Uri = "$($PiHoleServer.OriginalString)/api/$($Endpoint.TrimStart('/'))"
Method = $Method
SkipCertificateCheck = $IgnoreSsl
ContentType = "application/json"
}

if ($PSBoundParameters.ContainsKey('Form')) {
$Params.Form = $Form
}
else {
$Params.ContentType = "application/json"
}
if ($PSBoundParameters.ContainsKey('Body')) {
$Params.Body = $Body
}
if ($OutFile) {
$Params.OutFile = $OutFile
}

Invoke-RestMethod @Params -ErrorAction Stop
Expand Down
101 changes: 101 additions & 0 deletions PiHoleShell/Private/ManagementHelpers.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
function Resolve-PiHoleGroupName {
#INTERNAL FUNCTION
#
# Maps group names to the group IDs the client/domain/list APIs expect, throwing on the first
# name that doesn't exist. AllGroups is the caller's Get-PiHoleGroup result, so a function
# resolving groups only fetches them once.
param (
[Parameter(Mandatory = $true)]
[System.URI]$PiHoleServer,
$AllGroups,
$Name
)

$Names = @()
$Ids = @()
foreach ($GroupItem in $Name) {
$FoundGroup = $AllGroups | Where-Object { $_.Name -eq $GroupItem }
if ($FoundGroup) {
$Names += $FoundGroup.Name
$Ids += $FoundGroup.Id
Write-Verbose -Message "Found Group $($FoundGroup.Name) with $($FoundGroup.Id)"
}
else {
throw "Cannot find $GroupItem on $PiHoleServer! Please use Get-PiHoleGroup to list all groups"
}
}

[PSCustomObject]@{
Names = $Names
Ids = $Ids
}
}

function ConvertTo-PiHoleClientObject {
#INTERNAL FUNCTION
#
# Formats the clients in a New-/Update-PiHoleClient response. Groups is passed in rather than
# read from the response, which only has group IDs.
param (
$Client,
$Groups
)

foreach ($Item in $Client) {
[PSCustomObject]@{
Client = $Item.client
Name = $Item.name
Comment = $Item.comment
Groups = $Groups
Id = $Item.id
DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime
DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime
}
}
}

function ConvertTo-PiHoleDomainObject {
#INTERNAL FUNCTION
#
# Formats the domains in a New-/Update-PiHoleDomain response. Groups is passed in rather than
# read from the response, which only has group IDs.
param (
$Domain,
$Groups
)

foreach ($Item in $Domain) {
[PSCustomObject]@{
Domain = $Item.domain
Unicode = $Item.unicode
Type = $Item.type.SubString(0, 1).ToUpper() + $Item.type.SubString(1).ToLower()
Kind = $Item.kind.SubString(0, 1).ToUpper() + $Item.kind.SubString(1).ToLower()
Comment = $Item.comment
Groups = $Groups
Enabled = $Item.enabled
Id = $Item.id
DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime
DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime
}
}
}

function ConvertTo-PiHoleGroupObject {
#INTERNAL FUNCTION
#
# Formats the groups in a New-/Update-PiHoleGroup response.
param (
$Group
)

foreach ($Item in $Group) {
[PSCustomObject]@{
Name = $Item.name
Comment = $Item.comment
Enabled = $Item.enabled
Id = $Item.id
DateAdded = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_added).LocalTime
DateModified = (Convert-PiHoleUnixTimeToLocalTime -UnixTime $Item.date_modified).LocalTime
}
}
}
37 changes: 3 additions & 34 deletions PiHoleShell/Public/Actions/Invoke-PiHoleFlushLogs.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@ This will dump the response instead of the formatted object
.EXAMPLE
Invoke-PiHoleFlushLogs -PiHoleServer "http://pihole.domain.com:8080" -Password "your-app-password"
#>
[CmdletBinding(HelpUri = 'https://ftl.pi-hole.net/master/docs/#post-/action/flush/logs')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Flushes PiHole logs')]
[CmdletBinding(SupportsShouldProcess = $true, HelpUri = 'https://ftl.pi-hole.net/master/docs/#post-/action/flush/logs')]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "Password")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Justification = "Logs matches the Pi-hole API's own endpoint name, /action/flush/logs")]
param (
Expand All @@ -35,37 +34,7 @@ Invoke-PiHoleFlushLogs -PiHoleServer "http://pihole.domain.com:8080" -Password "
[bool]$RawOutput = $false
)

try {
$Sid = Request-PiHoleAuth -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl

$Params = @{
Headers = @{sid = $($Sid) }
Uri = "$($PiHoleServer.OriginalString)/api/action/flush/logs"
Method = "Post"
ContentType = "application/json"
SkipCertificateCheck = $IgnoreSsl
}

$Response = Invoke-RestMethod @Params

if ($RawOutput) {
Write-Output $Response
}
else {
$Object = [PSCustomObject]@{
Status = "Flushed"
}
Write-Output $Object
}
}

catch {
Write-Error -Message $_.Exception.Message
}

finally {
if ($Sid) {
Remove-PiHoleCurrentAuthSession -PiHoleServer $PiHoleServer -Sid $Sid -IgnoreSsl $IgnoreSsl
}
if ($PSCmdlet.ShouldProcess("Pi-Hole server at $PiHoleServer", "Flush DNS logs")) {
Invoke-PiHoleAction -PiHoleServer $PiHoleServer -Password $Password -IgnoreSsl $IgnoreSsl -RawOutput $RawOutput -Endpoint 'action/flush/logs' -Status 'Flushed'
}
}
Loading
Loading