mirror of
https://github.com/taigrr/godns
synced 2025-01-18 04:03:25 -08:00
Compare commits
51 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
5ad83edfe8 | ||
|
069fd1dcb5 | ||
|
fa03a1b959 | ||
|
17c9b6fa17 | ||
|
6dfbb60dfd | ||
|
07e5d7f99e | ||
|
10c67fa23a | ||
|
afc6ba8241 | ||
|
7ac3eed730 | ||
|
ac7dc021eb | ||
|
2154fcc762 | ||
|
99af25e496 | ||
|
dd4805df92 | ||
|
cdf32c509d | ||
|
fd4c30eec7 | ||
|
212ce47ea7 | ||
|
cefae90569 | ||
|
c720f7bca1 | ||
|
7a60d3415f | ||
|
e33cd6e1cb | ||
|
f62c20a145 | ||
|
ad6e17dc06 | ||
|
f807baa3ce | ||
|
2d546702ff | ||
|
f6a27491f3 | ||
|
3ba95289e9 | ||
|
d7755ab15e | ||
|
e070900b3b | ||
|
21590d4c64 | ||
|
a7c2b0a56e | ||
|
1ddd1dfb8b | ||
|
e94d99e25c | ||
|
f70f3bc0a3 | ||
|
3eaed255d9 | ||
|
633e1187d0 | ||
|
0f670c66f9 | ||
|
0f9ea20f10 | ||
|
81ecf1d096 | ||
|
fa1432be99 | ||
|
045cb692a5 | ||
|
2021a2404c | ||
|
eec9e9a881 | ||
|
b1e94fda52 | ||
|
de42aa6073 | ||
|
31ebe517e5 | ||
|
3c2e9a805e | ||
|
cf0a80a729 | ||
|
49de482a53 | ||
|
20c2b96765 | ||
|
97195eccce | ||
|
9186772d50 |
4
.github/workflows/go.yml
vendored
4
.github/workflows/go.yml
vendored
@ -7,10 +7,10 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
- name: Set up Go 1.13.6
|
||||
- name: Set up Go 1.15.7
|
||||
uses: actions/setup-go@v1
|
||||
with:
|
||||
go-version: 1.13.6
|
||||
go-version: 1.15.7
|
||||
id: go
|
||||
|
||||
- name: Check out code into the Go module directory
|
||||
|
76
CODE_OF_CONDUCT.md
Normal file
76
CODE_OF_CONDUCT.md
Normal file
@ -0,0 +1,76 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
In the interest of fostering an open and welcoming environment, we as
|
||||
contributors and maintainers pledge to making participation in our project and
|
||||
our community a harassment-free experience for everyone, regardless of age, body
|
||||
size, disability, ethnicity, sex characteristics, gender identity and expression,
|
||||
level of experience, education, socio-economic status, nationality, personal
|
||||
appearance, race, religion, or sexual identity and orientation.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to creating a positive environment
|
||||
include:
|
||||
|
||||
* Using welcoming and inclusive language
|
||||
* Being respectful of differing viewpoints and experiences
|
||||
* Gracefully accepting constructive criticism
|
||||
* Focusing on what is best for the community
|
||||
* Showing empathy towards other community members
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
* The use of sexualized language or imagery and unwelcome sexual attention or
|
||||
advances
|
||||
* Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or electronic
|
||||
address, without explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Our Responsibilities
|
||||
|
||||
Project maintainers are responsible for clarifying the standards of acceptable
|
||||
behavior and are expected to take appropriate and fair corrective action in
|
||||
response to any instances of unacceptable behavior.
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or
|
||||
reject comments, commits, code, wiki edits, issues, and other contributions
|
||||
that are not aligned to this Code of Conduct, or to ban temporarily or
|
||||
permanently any contributor for other behaviors that they deem inappropriate,
|
||||
threatening, offensive, or harmful.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies both within project spaces and in public spaces
|
||||
when an individual is representing the project or its community. Examples of
|
||||
representing a project or community include using an official project e-mail
|
||||
address, posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event. Representation of a project may be
|
||||
further defined and clarified by project maintainers.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported by contacting the project team at i@xiaozhou.net. All
|
||||
complaints will be reviewed and investigated and will result in a response that
|
||||
is deemed necessary and appropriate to the circumstances. The project team is
|
||||
obligated to maintain confidentiality with regard to the reporter of an incident.
|
||||
Further details of specific enforcement policies may be posted separately.
|
||||
|
||||
Project maintainers who do not follow or enforce the Code of Conduct in good
|
||||
faith may face temporary or permanent repercussions as determined by other
|
||||
members of the project's leadership.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
|
||||
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
|
||||
For answers to common questions about this code of conduct, see
|
||||
https://www.contributor-covenant.org/faq
|
13
Dockerfile
13
Dockerfile
@ -2,13 +2,8 @@ FROM golang:alpine AS builder
|
||||
RUN mkdir /godns
|
||||
ADD . /godns/
|
||||
WORKDIR /godns
|
||||
RUN go build -o godns cmd/godns/godns.go
|
||||
RUN CGO_ENABLED=0 go build -o godns cmd/godns/godns.go
|
||||
|
||||
FROM alpine
|
||||
RUN apk add --update ca-certificates
|
||||
RUN mkdir /usr/local/godns
|
||||
COPY --from=builder /godns/godns /usr/local/godns
|
||||
RUN chmod +x /usr/local/godns/godns
|
||||
RUN rm -rf /var/cache/apk/*
|
||||
WORKDIR /usr/local/godns
|
||||
ENTRYPOINT ["./godns", "-c", "/usr/local/godns/config.json"]
|
||||
FROM gcr.io/distroless/base
|
||||
COPY --from=builder /godns/godns /godns
|
||||
ENTRYPOINT ["/godns"]
|
6
Makefile
6
Makefile
@ -2,15 +2,15 @@
|
||||
BINARY=godns
|
||||
# Builds the project
|
||||
build:
|
||||
GO111MODULE=on go build cmd/godns/godns.go -o ${BINARY} -ldflags "-X main.Version=${VERSION}"
|
||||
GO111MODULE=on go build -ldflags "-X main.Version=${VERSION}" -o ${BINARY} cmd/godns/godns.go
|
||||
# Installs our project: copies binaries
|
||||
install:
|
||||
GO111MODULE=on go install
|
||||
image:
|
||||
# Build docker image
|
||||
go clean
|
||||
docker buildx build --platform linux/amd64,linux/386,linux/arm64,linux/arm/v7 -t timothyye/godns:${VERSION} . --push
|
||||
docker buildx build --platform linux/amd64,linux/386,linux/arm64,linux/arm/v7 -t timothyye/godns:latest . --push
|
||||
docker buildx build --platform linux/amd64,linux/arm64,linux/arm/v7 -t timothyye/godns:${VERSION} . --push
|
||||
docker buildx build --platform linux/amd64,linux/arm64,linux/arm/v7 -t timothyye/godns:latest . --push
|
||||
release:
|
||||
# Clean
|
||||
go clean
|
||||
|
489
README.md
489
README.md
@ -7,7 +7,7 @@
|
||||
╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝
|
||||
```
|
||||
|
||||
[![MIT licensed][9]][10] [-blue.svg)](https://github.com/996icu/996.ICU/blob/master/LICENSE) [![Docker][3]][4] [![Go Report Card][11]][12] [![Cover.Run][15]][16] [![GoDoc][13]][14]
|
||||
[![Apache licensed][9]][10] [![Docker][3]][4] [![Go Report Card][11]][12] [![Cover.Run][15]][16] [![GoDoc][13]][14]
|
||||
|
||||
[3]: https://images.microbadger.com/badges/image/timothyye/godns.svg
|
||||
[4]: https://microbadger.com/images/timothyye/godns
|
||||
@ -20,69 +20,107 @@
|
||||
[15]: https://img.shields.io/badge/cover.run-88.2%25-green.svg
|
||||
[16]: https://cover.run/go/github.com/timothyye/godns
|
||||
|
||||
GoDNS is a dynamic DNS (DDNS) client tool, it is based on my early open source project: [DynDNS](https://github.com/TimothyYe/DynDNS).
|
||||
[GoDNS](https://github.com/TimothyYe/godns) is a dynamic DNS (DDNS) client tool. It is a rewrite in [Go](https://golang.org) of my early [DynDNS](https://github.com/TimothyYe/DynDNS) open source project.
|
||||
|
||||
Now I rewrite [DynDNS](https://github.com/TimothyYe/DynDNS) by Golang and call it [GoDNS](https://github.com/TimothyYe/godns).
|
||||
Currently supports updating A records for subdomains. Doesn't support updating of root domains.
|
||||
|
||||
---
|
||||
- [Supported DNS Providers](#supported-dns-providers)
|
||||
- [Supported Platforms](#supported-platforms)
|
||||
- [Pre-conditions](#pre-conditions)
|
||||
- [Installation](#installation)
|
||||
- [Usage](#usage)
|
||||
- [Configuration](#configuration)
|
||||
- [Overview](#overview)
|
||||
- [Configuration properties](#configuration-properties)
|
||||
- [Configuration examples](#configuration-examples)
|
||||
- [Cloudflare](#cloudflare)
|
||||
- [DNSPod](#dnspod)
|
||||
- [Dreamhost](#dreamhost)
|
||||
- [Google Domains](#google-domains)
|
||||
- [AliDNS](#alidns)
|
||||
- [DuckDNS](#duckdns)
|
||||
- [No-IP](#no-ip)
|
||||
- [HE.net](#henet)
|
||||
- [Notifications](#notifications)
|
||||
- [Email](#email)
|
||||
- [Telegram](#telegram)
|
||||
- [Slack](#slack)
|
||||
- [Miscellaneous topics](#miscellaneous-topics)
|
||||
- [IPv6 support](#ipv6-support)
|
||||
- [Network interface IP address](#network-interface-ip-address)
|
||||
- [SOCKS5 proxy support](#socks5-proxy-support)
|
||||
- [Running GoDNS](#running-godns)
|
||||
- [As a manual daemon](#as-a-manual-daemon)
|
||||
- [As a managed daemon (with upstart)](#as-a-managed-daemon-with-upstart)
|
||||
- [As a managed daemon (with systemd)](#as-a-managed-daemon-with-systemd)
|
||||
- [As a Docker container](#as-a-docker-container)
|
||||
- [As a Windows service](#as-a-windows-service)
|
||||
- [Special Thanks](#special-thanks)
|
||||
|
||||
---
|
||||
## Supported DNS Providers
|
||||
|
||||
* Cloudflare ([https://cloudflare.com](https://cloudflare.com))
|
||||
* Google Domains ([https://domains.google](https://domains.google))
|
||||
* DNSPod ([https://www.dnspod.cn/](https://www.dnspod.cn/))
|
||||
* HE.net (Hurricane Electric) ([https://dns.he.net/](https://dns.he.net/))
|
||||
* AliDNS ([https://help.aliyun.com/product/29697.html](https://help.aliyun.com/product/29697.html))
|
||||
* DuckDNS ([https://www.duckdns.org](https://www.duckdns.org))
|
||||
* Dreamhost ([https://www.dreamhost.com](https://www.dreamhost.com))
|
||||
| Provider | IPv4 support | IPv6 support | Root Domain | Subdomains |
|
||||
| ------------------------------------- | :----------------: | :----------------: | :----------------: | :----------------: |
|
||||
| [Cloudflare][cloudflare] | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: |
|
||||
| [Google Domains][google.domains] | :white_check_mark: | :white_check_mark: | :x: | :white_check_mark: |
|
||||
| [DNSPod][dnspod] | :white_check_mark: | :white_check_mark: | :x: | :white_check_mark: |
|
||||
| [HE.net (Hurricane Electric)][he.net] | :white_check_mark: | :white_check_mark: | :x: | :white_check_mark: |
|
||||
| [AliDNS][alidns] | :white_check_mark: | :x: | :x: | :white_check_mark: |
|
||||
| [DuckDNS][duckdns] | :white_check_mark: | :white_check_mark: | :x: | :white_check_mark: |
|
||||
| [Dreamhost][dreamhost] | :white_check_mark: | :white_check_mark: | :x: | :white_check_mark: |
|
||||
| [No-IP][no-ip] | :white_check_mark: | :white_check_mark: | :x: | :white_check_mark: |
|
||||
|
||||
[cloudflare]: https://cloudflare.com
|
||||
[google.domains]: https://domains.google
|
||||
[dnspod]: https://www.dnspod.cn
|
||||
[he.net]: https://dns.he.net
|
||||
[alidns]: https://help.aliyun.com/product/29697.html
|
||||
[duckdns]: https://www.duckdns.org
|
||||
[dreamhost]: https://www.dreamhost.com
|
||||
[no-ip]: https://www.noip.com
|
||||
|
||||
Tip: You can follow this [issue](https://github.com/TimothyYe/godns/issues/76) to view the current status of DDNS for root domains.
|
||||
|
||||
## Supported Platforms
|
||||
|
||||
* Linux
|
||||
* MacOS
|
||||
* ARM Linux (Raspberry Pi, etc...)
|
||||
* ARM Linux (Raspberry Pi, etc.)
|
||||
* Windows
|
||||
* MIPS32 platform
|
||||
|
||||
## MIPS32 platform
|
||||
To compile binaries for MIPS (mips or mipsle), run:
|
||||
|
||||
To compile binaries for MIPS (mips or mipsle):
|
||||
```bash
|
||||
GOOS=linux GOARCH=mips/mipsle GOMIPS=softfloat go build -a
|
||||
```
|
||||
|
||||
The binary can run on routers as well.
|
||||
|
||||
## Pre-conditions
|
||||
|
||||
To use GoDNS, it is assumed:
|
||||
* You registered (now own) a domain
|
||||
* Domain was delegated to a supported [DNS provider](#supported-dns-providers) (i.e. it has nameserver `NS` records pointing at a supported provider)
|
||||
|
||||
Alternatively, you can sign in to [DuckDNS](https://www.duckdns.org) (with a social account) and get a subdomain on the duckdns.org domain for free.
|
||||
|
||||
## Installation
|
||||
|
||||
Build GoDNS by running (from the root of the repository):
|
||||
|
||||
```bash
|
||||
GOOS=linux GOARCH=mips/mipsle GOMIPS=softfloat go build -a
|
||||
cd cmd/godns # go to the GoDNS directory
|
||||
go get -v # get dependencies
|
||||
go build # build
|
||||
```
|
||||
|
||||
And the binary can run well on routers.
|
||||
You can also download a compiled binary from the [releases](https://github.com/TimothyYe/godns/releases).
|
||||
## Usage
|
||||
|
||||
## Pre-condition
|
||||
|
||||
* Register and own a domain.
|
||||
|
||||
* Domain's nameserver points to [DNSPod](https://www.dnspod.cn/) or [HE.net](https://dns.he.net/) or [Cloudflare](https://www.cloudflare.com/) or [Google Domains](https://domains.google) or [AliDNS](https://dc.console.aliyun.com).
|
||||
|
||||
* Or just register an account from [DuckDNS](https://www.duckdns.org/).
|
||||
|
||||
## Get it
|
||||
|
||||
### Build it from source code
|
||||
|
||||
* Get source code from Github:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/timothyye/godns.git
|
||||
```
|
||||
|
||||
* Go into the godns directory, get related library and then build it:
|
||||
|
||||
```bash
|
||||
cd cmd/godns
|
||||
go get -v
|
||||
go build
|
||||
```
|
||||
|
||||
### Download from releases
|
||||
|
||||
Download compiled binaries from [releases](https://github.com/TimothyYe/godns/releases)
|
||||
|
||||
## Get help
|
||||
Print usage/help by running:
|
||||
|
||||
```bash
|
||||
$ ./godns -h
|
||||
@ -92,65 +130,37 @@ Usage of ./godns:
|
||||
-h Show help
|
||||
```
|
||||
|
||||
## Config it
|
||||
## Configuration
|
||||
|
||||
* Get [config_sample.json](https://github.com/timothyye/godns/blob/master/config_sample.json) from Github.
|
||||
* Rename it to **config.json**.
|
||||
* Configure your provider, domain/subdomain info, username and password, etc.
|
||||
* Configure the SMTP options if you want, a mail notification will sent to your mailbox once the IP is changed.
|
||||
* Save it in the same directory of GoDNS, or use -c=your_conf_path command.
|
||||
### Overview
|
||||
|
||||
## Config fields
|
||||
* Make a copy of [config_sample.json](./config_sample.json) and name it `config.json`
|
||||
* Configure your provider, domain/subdomain info, credentials, etc.
|
||||
* Configure a notification medium (e.g. SMTP to receive emails) to get notified when your IP address changes
|
||||
* Place the file in the same directory of GoDNS or use the `-c=path/to/your/file.json` option
|
||||
|
||||
* provider: The providers that GoDNS supports, available values are: `Cloudflare`, `Google`, `DNSPod`, `AliDNS`, `HE`, `DuckDNS`, `Dreamhost`.
|
||||
* email: Email or account name of your DNS provider.
|
||||
* password: Password of your account.
|
||||
* login_token: API token of your account.
|
||||
* domains: Domains list, with your sub domains.
|
||||
* ip_url: A site helps you to get your public IPv4 IP address.
|
||||
* ipv6_url: A site helps you to get your public IPv6 address.
|
||||
* ip_type: To configure GoDNS under IPv4 mode or IPv6 mode, available values are: `IPv4`, `IPv6`.
|
||||
* interval: The interval `seconds` that GoDNS check your public IP.
|
||||
* socks5_proxy: Socks5 proxy server.
|
||||
* resolver: The address of the public DNS server. For example, to run GoDNS in `IPv4` mode, you can set resolver as `8.8.8.8`, to GoDNS in `IPv6` mode, you can set resolver as `2001:4860:4860::8888`.
|
||||
### Configuration properties
|
||||
|
||||
## IPv6 support
|
||||
* `provider` — One of the [supported provider to use](#supported-dns-providers): `Cloudflare`, `Google`, `DNSPod`, `AliDNS`, `HE`, `DuckDNS` or `Dreamhost`.
|
||||
* `email` — Email or account name of the DNS provider.
|
||||
* `password` — Password of the DNS provider.
|
||||
* `login_token` — API token of the DNS provider.
|
||||
* `domains` — Domains list, with your sub domains.
|
||||
* `ip_url` — A URL for fetching one's public IPv4 address.
|
||||
* `ipv6_url` — A URL for fetching one's public IPv6 address.
|
||||
* `ip_type` — Switch deciding if IPv4 or IPv6 should be used (when [supported](#supported-dns-providers)). Available values: `IPv4` or `IPv6`.
|
||||
* `interval` — How often (in seconds) the public IP should be updated.
|
||||
* `socks5_proxy` — Socks5 proxy server.
|
||||
* `resolver` — Address of a public DNS server to use. For instance to use [Google's public DNS](https://developers.google.com/speed/public-dns/docs/using), you can set `8.8.8.8` when using GoDNS in IPv4 mode or `2001:4860:4860::8888` in IPv6 mode.
|
||||
|
||||
Supported provider(s):
|
||||
* Cloudflare
|
||||
* DNSPod
|
||||
* Dreamhost
|
||||
* DuckDNS
|
||||
* Google Domains
|
||||
* HE.net
|
||||
### Configuration examples
|
||||
|
||||
To enable the `IPv6` mode of GoDNS, you only need two steps:
|
||||
* Set the `ip_type` as `IPv6`, and make sure the `ipv6_url` is configured.
|
||||
* Add one `AAAA` record to your provider.
|
||||
|
||||
For example:
|
||||
|
||||
```json
|
||||
{
|
||||
"domains": [
|
||||
{
|
||||
"domain_name": "example.com",
|
||||
"sub_domains": [
|
||||
"ipv6"
|
||||
]
|
||||
}
|
||||
],
|
||||
"resolver": "2001:4860:4860::8888",
|
||||
"ipv6_url": "https://api-ipv6.ip.sb/ip",
|
||||
"ip_type": "IPv6"
|
||||
}
|
||||
```
|
||||
|
||||
### Config example for Cloudflare
|
||||
#### Cloudflare
|
||||
|
||||
For Cloudflare, you need to provide the email & Global API Key as password (or to use the API token) and config all the domains & subdomains.
|
||||
|
||||
* Using email & Global API Key
|
||||
<details>
|
||||
<summary>Using email & Global API Key</summary>
|
||||
|
||||
```json
|
||||
{
|
||||
@ -171,8 +181,10 @@ For Cloudflare, you need to provide the email & Global API Key as password (or t
|
||||
"socks5_proxy": ""
|
||||
}
|
||||
```
|
||||
</details>
|
||||
|
||||
* Using the API Token
|
||||
<details>
|
||||
<summary>Using the API Token</summary>
|
||||
|
||||
```json
|
||||
{
|
||||
@ -192,11 +204,15 @@ For Cloudflare, you need to provide the email & Global API Key as password (or t
|
||||
"socks5_proxy": ""
|
||||
}
|
||||
```
|
||||
</details>
|
||||
|
||||
### Config example for DNSPod
|
||||
#### DNSPod
|
||||
|
||||
For DNSPod, you need to provide your API Token(you can create it [here](https://www.dnspod.cn/console/user/security)), and config all the domains & subdomains.
|
||||
|
||||
<details>
|
||||
<summary>Example</summary>
|
||||
|
||||
```json
|
||||
{
|
||||
"provider": "DNSPod",
|
||||
@ -216,11 +232,15 @@ For DNSPod, you need to provide your API Token(you can create it [here](https://
|
||||
"socks5_proxy": ""
|
||||
}
|
||||
```
|
||||
</details>
|
||||
|
||||
### Config example for Dreamhost
|
||||
#### Dreamhost
|
||||
|
||||
For Dreamhost, you need to provide your API Token(you can create it [here](https://panel.dreamhost.com/?tree=home.api)), and config all the domains & subdomains.
|
||||
|
||||
<details>
|
||||
<summary>Example</summary>
|
||||
|
||||
```json
|
||||
{
|
||||
"provider": "Dreamhost",
|
||||
@ -241,11 +261,15 @@ For Dreamhost, you need to provide your API Token(you can create it [here](https
|
||||
"socks5_proxy": ""
|
||||
}
|
||||
```
|
||||
</details>
|
||||
|
||||
### Config example for Google Domains
|
||||
#### Google Domains
|
||||
|
||||
For Google Domains, you need to provide email & password, and config all the domains & subdomains.
|
||||
|
||||
<details>
|
||||
<summary>Example</summary>
|
||||
|
||||
```json
|
||||
{
|
||||
"provider": "Google",
|
||||
@ -265,11 +289,15 @@ For Google Domains, you need to provide email & password, and config all the dom
|
||||
"socks5_proxy": ""
|
||||
}
|
||||
```
|
||||
</details>
|
||||
|
||||
### Config example for AliDNS
|
||||
#### AliDNS
|
||||
|
||||
For AliDNS, you need to provide `AccessKeyID` & `AccessKeySecret` as `email` & `password`, and config all the domains & subdomains.
|
||||
|
||||
<details>
|
||||
<summary>Example</summary>
|
||||
|
||||
```json
|
||||
{
|
||||
"provider": "AliDNS",
|
||||
@ -290,11 +318,15 @@ For AliDNS, you need to provide `AccessKeyID` & `AccessKeySecret` as `email` & `
|
||||
"socks5_proxy": ""
|
||||
}
|
||||
```
|
||||
</details>
|
||||
|
||||
### Config example for DuckDNS
|
||||
#### DuckDNS
|
||||
|
||||
For DuckDNS, only need to provide the `token`, config 1 default domain & subdomains.
|
||||
|
||||
<details>
|
||||
<summary>Example</summary>
|
||||
|
||||
```json
|
||||
{
|
||||
"provider": "DuckDNS",
|
||||
@ -314,11 +346,40 @@ For DuckDNS, only need to provide the `token`, config 1 default domain & subdoma
|
||||
"socks5_proxy": ""
|
||||
}
|
||||
```
|
||||
</details>
|
||||
|
||||
### Config example for HE.net
|
||||
#### No-IP
|
||||
|
||||
<details>
|
||||
<summary>Example</summary>
|
||||
|
||||
```json
|
||||
{
|
||||
"provider": "NoIP",
|
||||
"email": "mail@example.com",
|
||||
"password": "YourPassword",
|
||||
"domains": [
|
||||
{
|
||||
"domain_name": "ddns.net",
|
||||
"sub_domains": ["timothyye6"]
|
||||
}
|
||||
],
|
||||
"ip_type": "IPv4",
|
||||
"ip_url": "https://myip.biturl.top",
|
||||
"resolver": "8.8.8.8",
|
||||
"interval": 300,
|
||||
"socks5_proxy": ""
|
||||
}
|
||||
```
|
||||
</details>
|
||||
|
||||
#### HE.net
|
||||
|
||||
For HE, email is not needed, just fill DDNS key to password, and config all the domains & subdomains.
|
||||
|
||||
<details>
|
||||
<summary>Example</summary>
|
||||
|
||||
```json
|
||||
{
|
||||
"provider": "HE",
|
||||
@ -338,38 +399,31 @@ For HE, email is not needed, just fill DDNS key to password, and config all the
|
||||
"socks5_proxy": ""
|
||||
}
|
||||
```
|
||||
</details>
|
||||
|
||||
### HE.net DDNS configuration
|
||||
<details>
|
||||
<summary>Provider configuration</summary>
|
||||
|
||||
Add a new "A record", make sure that "Enable entry for dynamic dns" is checked:
|
||||
Add a new "A record" and make sure that "Enable entry for dynamic dns" is checked:
|
||||
|
||||
<img src="https://github.com/TimothyYe/godns/blob/master/snapshots/he1.png?raw=true" width="640" />
|
||||
<img src="./snapshots/he1.png" width="640" />
|
||||
|
||||
Fill your own DDNS key or generate a random DDNS key for this new created "A record":
|
||||
Fill in your own DDNS key or generate a random DDNS key for this new created "A record":
|
||||
|
||||
<img src="https://github.com/TimothyYe/godns/blob/master/snapshots/he2.png?raw=true" width="640" />
|
||||
<img src="./snapshots/he2.png" width="640" />
|
||||
|
||||
Remember the DDNS key and fill it as password to the config.json.
|
||||
Remember the DDNS key and set it in the `password` property in the configuration file.
|
||||
|
||||
__NOTICE__: If you have multiple domains or subdomains, make sure their DDNS key are the same.
|
||||
</details>
|
||||
|
||||
### Get an IP address from the interface
|
||||
### Notifications
|
||||
|
||||
For some reasons if you want to get an IP directly from the interface, say `eth0` for Linux or `Local Area Connection` for Windows, update config file like this:
|
||||
GoDNS can send a notification each time the IP changes.
|
||||
|
||||
```json
|
||||
"ip_url": "",
|
||||
"ip_interface": "eth0",
|
||||
```
|
||||
#### Email
|
||||
|
||||
If you set both `ip_url` and `ip_interface`, it first tries to get an IP address online, and if not succeed, gets
|
||||
an IP address from the interface as a fallback.
|
||||
|
||||
Note that IPv6 address will be ignored currently.
|
||||
|
||||
### Email notification support
|
||||
|
||||
Update config file and provide your SMTP options, a notification mail will be sent to your mailbox once the IP is changed and updated.
|
||||
Emails are sent over [SMTP](https://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol). Update your configuration with the following snippet:
|
||||
|
||||
```json
|
||||
"notify": {
|
||||
@ -384,13 +438,13 @@ Update config file and provide your SMTP options, a notification mail will be se
|
||||
}
|
||||
```
|
||||
|
||||
Notification mail example:
|
||||
Each time the IP changes, you will receive an email like that:
|
||||
|
||||
<img src="https://github.com/TimothyYe/godns/blob/master/snapshots/mail.png?raw=true" />
|
||||
<img src="https://github.com/TimothyYe/godns/blob/master/snapshots/mail.png?raw=true" />
|
||||
|
||||
### Telegram notification support
|
||||
#### Telegram
|
||||
|
||||
Update config file and provide your Telegram options, a notification message will be sent to your telegram channel once the IP is changed and updated.
|
||||
To receive a [Telegram](https://telegram.org/) message each time the IP changes, update your configuration with the following snippet:
|
||||
|
||||
```json
|
||||
"notify": {
|
||||
@ -398,81 +452,168 @@ Update config file and provide your Telegram options, a notification message wil
|
||||
"enabled": true,
|
||||
"bot_api_key": "11111:aaaa-bbbb",
|
||||
"chat_id": "-123456",
|
||||
"message_template": "Domain *{{ .Domain }}* is updated to %0A{{ .CurrentIP }}"
|
||||
"message_template": "Domain *{{ .Domain }}* is updated to %0A{{ .CurrentIP }}",
|
||||
"use_proxy": false
|
||||
},
|
||||
}
|
||||
```
|
||||
Markdown is supported in message template, and use `%0A` for newline.
|
||||
|
||||
### SOCKS5 proxy support
|
||||
The `message_template` property supports [markdown](https://www.markdownguide.org). New lines needs to be escaped with `%0A`.
|
||||
|
||||
You can also use SOCKS5 proxy, just fill SOCKS5 address to the ```socks5_proxy``` item:
|
||||
#### Slack
|
||||
|
||||
To receive a [Slack](https://slack.com) message each time the IP changes, update your configuration with the following snippet:
|
||||
|
||||
```json
|
||||
"socks5_proxy": "127.0.0.1:7070"
|
||||
"notify": {
|
||||
"slack": {
|
||||
"enabled": true,
|
||||
"bot_api_token": "xoxb-xxx",
|
||||
"channel": "your_channel",
|
||||
"message_template": "Domain *{{ .Domain }}* is updated to \n{{ .CurrentIP }}",
|
||||
"use_proxy": false
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Now all the queries will go through the specified SOCKS5 proxy.
|
||||
The `message_template` property supports [markdown](https://www.markdownguide.org). New lines needs to be escaped with `\n`.
|
||||
|
||||
## Run it as a daemon manually
|
||||
### Miscellaneous topics
|
||||
|
||||
#### IPv6 support
|
||||
|
||||
Most of the [providers](#supported-dns-providers) support IPv6.
|
||||
|
||||
To enable the `IPv6` support of GoDNS, there are two solutions to choose from:
|
||||
|
||||
1. Use an online service to lookup the external IPv6
|
||||
|
||||
For that:
|
||||
|
||||
- Set the `ip_type` as `IPv6`, and make sure the `ipv6_url` is configured
|
||||
- Create an `AAAA` record instead of an `A` record in your DNS provider
|
||||
|
||||
<details>
|
||||
<summary>Configuration example</summary>
|
||||
|
||||
```json
|
||||
{
|
||||
"domains": [
|
||||
{
|
||||
"domain_name": "example.com",
|
||||
"sub_domains": [
|
||||
"ipv6"
|
||||
]
|
||||
}
|
||||
],
|
||||
"resolver": "2001:4860:4860::8888",
|
||||
"ipv6_url": "https://api-ipv6.ip.sb/ip",
|
||||
"ip_type": "IPv6"
|
||||
}
|
||||
```
|
||||
</details>
|
||||
|
||||
|
||||
2. Let GoDNS find the IPv6 of the network interface of the machine it is running on (more on that [later](#network-interface-ip-address)).
|
||||
|
||||
For this to happen, just leave `ip_url` and `ipv6_url` empty.
|
||||
|
||||
Note that the network interface must be configured with an IPv6 for this to work.
|
||||
|
||||
#### Network interface IP address
|
||||
|
||||
For some reasons if you want to get the IP address associated to a network interface (instead of performing an online lookup), you can specify it in the configuration file this way:
|
||||
|
||||
```json
|
||||
...
|
||||
"ip_url": "",
|
||||
"ip_interface": "interface-name",
|
||||
...
|
||||
```
|
||||
|
||||
With `interface-name` replaced by the name of the network interface, e.g. `eth0` on Linux or `Local Area Connection` on Windows.
|
||||
|
||||
Note: If `ip_url` is also specified, it will be used to perform an online lookup first and the network interface IP will be used as a fallback in case of failure.
|
||||
|
||||
#### SOCKS5 proxy support
|
||||
|
||||
You can make all remote calls go through a [SOCKS5 proxy](https://en.wikipedia.org/wiki/SOCKS#SOCKS5) by specifying it in the configuration file this way:
|
||||
|
||||
```json
|
||||
...
|
||||
"socks5_proxy": "127.0.0.1:7070"
|
||||
"use_proxy": true
|
||||
...
|
||||
```
|
||||
|
||||
## Running GoDNS
|
||||
|
||||
There are few ways to run GoDNS.
|
||||
|
||||
### As a manual daemon
|
||||
|
||||
```bash
|
||||
nohup ./godns &
|
||||
```
|
||||
|
||||
## Run it as a daemon, manage it via Upstart
|
||||
Note: when the program stops, it will not be restarted.
|
||||
|
||||
* Install `upstart` first
|
||||
* Copy `./upstart/godns.conf` to `/etc/init`
|
||||
* Start it as a system service:
|
||||
### As a managed daemon (with upstart)
|
||||
|
||||
1. Install `upstart` first (if not available already)
|
||||
2. Copy `./upstart/godns.conf` to `/etc/init` (and tweak it to your needs)
|
||||
3. Start the service:
|
||||
|
||||
```bash
|
||||
sudo start godns
|
||||
```
|
||||
|
||||
### As a managed daemon (with systemd)
|
||||
|
||||
1. Install `systemd` first (it not available already)
|
||||
2. Copy `./systemd/godns.service` to `/lib/systemd/system` (and tweak it to your needs)
|
||||
3. Start the service:
|
||||
|
||||
```bash
|
||||
sudo systemctl enable godns
|
||||
sudo systemctl start godns
|
||||
```
|
||||
|
||||
### As a Docker container
|
||||
|
||||
With `/path/to/config.json` your local configuration file, run:
|
||||
|
||||
```bash
|
||||
sudo start godns
|
||||
docker run \
|
||||
-d --name godns --restart=always \
|
||||
-v /path/to/config.json:/config.json \
|
||||
timothyye/godns:latest
|
||||
```
|
||||
|
||||
## Run it as a daemon, manage it via Systemd
|
||||
### As a Windows service
|
||||
|
||||
* Modify `./systemd/godns.service` and config it.
|
||||
* Copy `./systemd/godns.service` to `/lib/systemd/system`
|
||||
* Start it as a systemd service:
|
||||
1. Download the latest version of [NSSM](https://nssm.cc/download)
|
||||
|
||||
```bash
|
||||
sudo systemctl enable godns
|
||||
sudo systemctl start godns
|
||||
```
|
||||
2. In an administrative prompt, from the folder where NSSM was downloaded, e.g. `C:\Downloads\nssm\` **win64**, run:
|
||||
|
||||
## Run it with docker
|
||||
```
|
||||
nssm install YOURSERVICENAME
|
||||
```
|
||||
|
||||
Now godns supports to run in docker.
|
||||
3. Follow the interface to configure the service. In the "Application" tab just indicate where the `godns.exe` file is. Optionally you can also define a description on the "Details" tab and define a log file on the "I/O" tab. Finish by clicking on the "Install service" button.
|
||||
|
||||
* Get [config_sample.json](https://github.com/timothyye/godns/blob/master/config_sample.json) from Github.
|
||||
* Rename it to **config.json**.
|
||||
* Run GoDNS with docker:
|
||||
4. The service will now start along Windows.
|
||||
|
||||
```bash
|
||||
docker run -d --name godns --restart=always \
|
||||
-v /path/to/config.json:/usr/local/godns/config.json timothyye/godns:latest
|
||||
```
|
||||
|
||||
## Run it as a Windows service
|
||||
|
||||
After creating your config.json file:
|
||||
|
||||
* Get the latest [NSSM](https://nssm.cc/download) for create a windows service.
|
||||
* Open the command prompt (as administrator) in the folder where you downloaded NSSM (e.g. C:\Downloads\nssm\ **win64**) and run:
|
||||
|
||||
```
|
||||
nssm install YOURSERVICENAME
|
||||
```
|
||||
|
||||
You will have an interface to configure your service, it is very simple in the "Application" tab just indicate where your `godns.exe` file is. Optionally you can also define a description on the "Details" tab and define a log file on the "I/O" tab.
|
||||
|
||||
* Finish using the "Install service" button.
|
||||
* Done. Now whenever windows start your service will be loaded.
|
||||
* To uninstall:
|
||||
Note: you can uninstall the service by running:
|
||||
|
||||
```
|
||||
nssm remove YOURSERVICENAME
|
||||
```
|
||||
|
||||
## Enjoy it!
|
||||
## Special Thanks
|
||||
|
||||
<img src="https://i.imgur.com/xhe5RLZ.jpg" width="80px" align="right" />
|
||||
|
||||
Thanks JetBrains for sponsoring this project with [free open source license](https://www.jetbrains.com/community/opensource/).
|
||||
|
||||
> I like GoLand, it is an amazing and productive tool.
|
||||
|
@ -50,17 +50,17 @@ func dnsLoop() {
|
||||
panicChan := make(chan godns.Domain)
|
||||
|
||||
log.Println("Creating DNS handler with provider:", configuration.Provider)
|
||||
handler := handler.CreateHandler(configuration.Provider)
|
||||
handler.SetConfiguration(&configuration)
|
||||
h := handler.CreateHandler(configuration.Provider)
|
||||
h.SetConfiguration(&configuration)
|
||||
for i := range configuration.Domains {
|
||||
go handler.DomainLoop(&configuration.Domains[i], panicChan)
|
||||
go h.DomainLoop(&configuration.Domains[i], panicChan)
|
||||
}
|
||||
|
||||
panicCount := 0
|
||||
for {
|
||||
failDomain := <-panicChan
|
||||
log.Println("Got panic in goroutine, will start a new one... :", panicCount)
|
||||
go handler.DomainLoop(&failDomain, panicChan)
|
||||
go h.DomainLoop(&failDomain, panicChan)
|
||||
|
||||
panicCount++
|
||||
if panicCount >= godns.PanicMax {
|
||||
|
@ -26,12 +26,14 @@
|
||||
"user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36",
|
||||
"ip_interface": "eth0",
|
||||
"socks5_proxy": "",
|
||||
"use_proxy": false,
|
||||
"notify": {
|
||||
"telegram": {
|
||||
"enabled": false,
|
||||
"bot_api_key": "",
|
||||
"chat_id": "",
|
||||
"message_template": ""
|
||||
"message_template": "",
|
||||
"use_proxy": false
|
||||
},
|
||||
"mail": {
|
||||
"enabled": false,
|
||||
|
@ -74,7 +74,7 @@ func getHTTPBody(url string) ([]byte, error) {
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
return body, err
|
||||
}
|
||||
return nil, fmt.Errorf("Status %d, Error:%s", resp.StatusCode, body)
|
||||
return nil, fmt.Errorf("status %d, Error:%s", resp.StatusCode, body)
|
||||
}
|
||||
|
||||
// NewAliDNS function creates instance of AliDNS and return
|
||||
@ -92,9 +92,8 @@ func NewAliDNS(key, secret string) *AliDNS {
|
||||
func (d *AliDNS) GetDomainRecords(domain, rr string) []DomainRecord {
|
||||
resp := &domainRecordsResp{}
|
||||
parms := map[string]string{
|
||||
"Action": "DescribeDomainRecords",
|
||||
"DomainName": domain,
|
||||
"RRKeyWord": rr,
|
||||
"Action": "DescribeSubDomainRecords",
|
||||
"SubDomain": fmt.Sprintf("%s.%s", rr, domain),
|
||||
}
|
||||
urlPath := d.genRequestURL(parms)
|
||||
body, err := getHTTPBody(urlPath)
|
||||
@ -124,7 +123,7 @@ func (d *AliDNS) UpdateDomainRecord(r DomainRecord) error {
|
||||
|
||||
urlPath := d.genRequestURL(parms)
|
||||
if urlPath == "" {
|
||||
return errors.New("Failed to generate request URL")
|
||||
return errors.New("failed to generate request URL")
|
||||
}
|
||||
_, err := getHTTPBody(urlPath)
|
||||
if err != nil {
|
||||
@ -134,7 +133,7 @@ func (d *AliDNS) UpdateDomainRecord(r DomainRecord) error {
|
||||
}
|
||||
|
||||
func (d *AliDNS) genRequestURL(parms map[string]string) string {
|
||||
pArr := []string{}
|
||||
var pArr []string
|
||||
ps := map[string]string{}
|
||||
for k, v := range publicParm {
|
||||
ps[k] = v
|
||||
|
@ -28,9 +28,17 @@ func (handler *Handler) DomainLoop(domain *godns.Domain, panicChan chan<- godns.
|
||||
}
|
||||
}()
|
||||
|
||||
looping := false
|
||||
aliDNS := NewAliDNS(handler.Configuration.Email, handler.Configuration.Password)
|
||||
|
||||
for {
|
||||
if looping {
|
||||
// Sleep with interval
|
||||
log.Printf("Going to sleep, will start next checking in %d seconds...\r\n", handler.Configuration.Interval)
|
||||
time.Sleep(time.Second * time.Duration(handler.Configuration.Interval))
|
||||
}
|
||||
|
||||
looping = true
|
||||
currentIP, err := godns.GetCurrentIP(handler.Configuration)
|
||||
|
||||
if err != nil {
|
||||
@ -40,7 +48,11 @@ func (handler *Handler) DomainLoop(domain *godns.Domain, panicChan chan<- godns.
|
||||
log.Println("currentIP is:", currentIP)
|
||||
for _, subDomain := range domain.SubDomains {
|
||||
hostname := subDomain + "." + domain.DomainName
|
||||
lastIP := godns.ResolveDNS(hostname, handler.Configuration.Resolver, handler.Configuration.IPType)
|
||||
lastIP, err := godns.ResolveDNS(hostname, handler.Configuration.Resolver, handler.Configuration.IPType)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
continue
|
||||
}
|
||||
//check against currently known IP, if no change, skip update
|
||||
if currentIP == lastIP {
|
||||
log.Printf("IP is the same as cached one. Skip update.\n")
|
||||
@ -68,9 +80,6 @@ func (handler *Handler) DomainLoop(domain *godns.Domain, panicChan chan<- godns.
|
||||
}
|
||||
}
|
||||
}
|
||||
// Sleep with interval
|
||||
log.Printf("Going to sleep, will start next checking in %d seconds...\r\n", handler.Configuration.Interval)
|
||||
time.Sleep(time.Second * time.Duration(handler.Configuration.Interval))
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -77,7 +77,15 @@ func (handler *Handler) DomainLoop(domain *godns.Domain, panicChan chan<- godns.
|
||||
}()
|
||||
|
||||
var lastIP string
|
||||
looping := false
|
||||
for {
|
||||
if looping {
|
||||
// Sleep with interval
|
||||
log.Printf("Going to sleep, will start next checking in %d seconds...\r\n", handler.Configuration.Interval)
|
||||
time.Sleep(time.Second * time.Duration(handler.Configuration.Interval))
|
||||
}
|
||||
looping = true
|
||||
|
||||
currentIP, err := godns.GetCurrentIP(handler.Configuration)
|
||||
if err != nil {
|
||||
log.Println("Error in GetCurrentIP:", err)
|
||||
@ -88,8 +96,6 @@ func (handler *Handler) DomainLoop(domain *godns.Domain, panicChan chan<- godns.
|
||||
if currentIP == lastIP {
|
||||
log.Printf("IP is the same as cached one. Skip update.\n")
|
||||
} else {
|
||||
lastIP = currentIP
|
||||
|
||||
log.Println("Checking IP for domain", domain.DomainName)
|
||||
zoneID := handler.getZone(domain.DomainName)
|
||||
if zoneID != "" {
|
||||
@ -103,7 +109,7 @@ func (handler *Handler) DomainLoop(domain *godns.Domain, panicChan chan<- godns.
|
||||
}
|
||||
if rec.IP != currentIP {
|
||||
log.Printf("IP mismatch: Current(%+v) vs Cloudflare(%+v)\r\n", currentIP, rec.IP)
|
||||
handler.updateRecord(rec, currentIP)
|
||||
lastIP = handler.updateRecord(rec, currentIP)
|
||||
|
||||
// Send notification
|
||||
if err := godns.SendNotify(handler.Configuration, rec.Name, currentIP); err != nil {
|
||||
@ -117,14 +123,14 @@ func (handler *Handler) DomainLoop(domain *godns.Domain, panicChan chan<- godns.
|
||||
log.Println("Failed to find zone for domain:", domain.DomainName)
|
||||
}
|
||||
}
|
||||
// Sleep with interval
|
||||
log.Printf("Going to sleep, will start next checking in %d seconds...\r\n", handler.Configuration.Interval)
|
||||
time.Sleep(time.Second * time.Duration(handler.Configuration.Interval))
|
||||
}
|
||||
}
|
||||
|
||||
// Check if record is present in domain conf
|
||||
func recordTracked(domain *godns.Domain, record *DNSRecord) bool {
|
||||
if record.Name == domain.DomainName {
|
||||
return true
|
||||
}
|
||||
for _, subDomain := range domain.SubDomains {
|
||||
sd := fmt.Sprintf("%s.%s", subDomain, domain.DomainName)
|
||||
if record.Name == sd {
|
||||
@ -137,7 +143,7 @@ func recordTracked(domain *godns.Domain, record *DNSRecord) bool {
|
||||
|
||||
// Create a new request with auth in place and optional proxy
|
||||
func (handler *Handler) newRequest(method, url string, body io.Reader) (*http.Request, *http.Client) {
|
||||
client := godns.GetHttpClient(handler.Configuration)
|
||||
client := godns.GetHttpClient(handler.Configuration, handler.Configuration.UseProxy)
|
||||
if client == nil {
|
||||
log.Println("cannot create HTTP client")
|
||||
}
|
||||
@ -160,7 +166,7 @@ func (handler *Handler) getZone(domain string) string {
|
||||
|
||||
var z ZoneResponse
|
||||
|
||||
req, client := handler.newRequest("GET", "/zones", nil)
|
||||
req, client := handler.newRequest("GET", fmt.Sprintf("/zones?name=%s", domain), nil)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
log.Println("Request error:", err.Error())
|
||||
@ -201,7 +207,7 @@ func (handler *Handler) getDNSRecords(zoneID string) []DNSRecord {
|
||||
}
|
||||
|
||||
log.Println("Querying records with type:", recordType)
|
||||
req, client := handler.newRequest("GET", fmt.Sprintf("/zones/"+zoneID+"/dns_records?type=%s", recordType), nil)
|
||||
req, client := handler.newRequest("GET", fmt.Sprintf("/zones/"+zoneID+"/dns_records?type=%s&page=1&per_page=500", recordType), nil)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
log.Println("Request error:", err.Error())
|
||||
@ -225,10 +231,11 @@ func (handler *Handler) getDNSRecords(zoneID string) []DNSRecord {
|
||||
}
|
||||
|
||||
// Update DNS A Record with new IP
|
||||
func (handler *Handler) updateRecord(record DNSRecord, newIP string) {
|
||||
func (handler *Handler) updateRecord(record DNSRecord, newIP string) string {
|
||||
|
||||
var r DNSRecordUpdateResponse
|
||||
record.SetIP(newIP)
|
||||
var lastIP string
|
||||
|
||||
j, _ := json.Marshal(record)
|
||||
req, client := handler.newRequest("PUT",
|
||||
@ -238,7 +245,7 @@ func (handler *Handler) updateRecord(record DNSRecord, newIP string) {
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
log.Println("Request error:", err.Error())
|
||||
return
|
||||
return ""
|
||||
}
|
||||
|
||||
body, _ := ioutil.ReadAll(resp.Body)
|
||||
@ -246,12 +253,14 @@ func (handler *Handler) updateRecord(record DNSRecord, newIP string) {
|
||||
if err != nil {
|
||||
log.Printf("Decoder error: %+v\n", err)
|
||||
log.Printf("Response body: %+v\n", string(body))
|
||||
return
|
||||
return ""
|
||||
}
|
||||
if r.Success != true {
|
||||
body, _ := ioutil.ReadAll(resp.Body)
|
||||
log.Printf("Response failed: %+v\n", string(body))
|
||||
} else {
|
||||
log.Printf("Record updated: %+v - %+v", record.Name, record.IP)
|
||||
lastIP = record.IP
|
||||
}
|
||||
return lastIP
|
||||
}
|
||||
|
@ -14,7 +14,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/TimothyYe/godns"
|
||||
simplejson "github.com/bitly/go-simplejson"
|
||||
"github.com/bitly/go-simplejson"
|
||||
)
|
||||
|
||||
// Handler struct definition
|
||||
@ -36,7 +36,16 @@ func (handler *Handler) DomainLoop(domain *godns.Domain, panicChan chan<- godns.
|
||||
}
|
||||
}()
|
||||
|
||||
looping := false
|
||||
for {
|
||||
if looping {
|
||||
// Sleep with interval
|
||||
log.Printf("Going to sleep, will start next checking in %d seconds...\r\n", handler.Configuration.Interval)
|
||||
time.Sleep(time.Second * time.Duration(handler.Configuration.Interval))
|
||||
}
|
||||
|
||||
looping = true
|
||||
|
||||
log.Printf("Checking IP for domain %s \r\n", domain.DomainName)
|
||||
domainID := handler.GetDomain(domain.DomainName)
|
||||
|
||||
@ -54,7 +63,12 @@ func (handler *Handler) DomainLoop(domain *godns.Domain, panicChan chan<- godns.
|
||||
|
||||
for _, subDomain := range domain.SubDomains {
|
||||
hostname := subDomain + "." + domain.DomainName
|
||||
lastIP := godns.ResolveDNS(hostname, handler.Configuration.Resolver, handler.Configuration.IPType)
|
||||
lastIP, err := godns.ResolveDNS(hostname, handler.Configuration.Resolver, handler.Configuration.IPType)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
continue
|
||||
}
|
||||
|
||||
//check against currently known IP, if no change, skip update
|
||||
if currentIP == lastIP {
|
||||
log.Printf("IP is the same as cached one. Skip update.\n")
|
||||
@ -82,9 +96,6 @@ func (handler *Handler) DomainLoop(domain *godns.Domain, panicChan chan<- godns.
|
||||
}
|
||||
}
|
||||
}
|
||||
// Sleep with interval
|
||||
log.Printf("Going to sleep, will start next checking in %d seconds...\r\n", handler.Configuration.Interval)
|
||||
time.Sleep(time.Second * time.Duration(handler.Configuration.Interval))
|
||||
}
|
||||
}
|
||||
|
||||
@ -166,6 +177,15 @@ func (handler *Handler) GetSubDomain(domainID int64, name string) (string, strin
|
||||
value.Add("length", "1")
|
||||
value.Add("sub_domain", name)
|
||||
|
||||
if handler.Configuration.IPType == "" || strings.ToUpper(handler.Configuration.IPType) == godns.IPV4 {
|
||||
value.Add("record_type", "A")
|
||||
} else if strings.ToUpper(handler.Configuration.IPType) == godns.IPV6 {
|
||||
value.Add("record_type", "AAAA")
|
||||
} else {
|
||||
log.Println("Error: must specify \"ip_type\" in config for DNSPod.")
|
||||
return "", ""
|
||||
}
|
||||
|
||||
response, err := handler.PostData("/Record.List", value)
|
||||
|
||||
if err != nil {
|
||||
@ -245,7 +265,7 @@ func (handler *Handler) UpdateIP(domainID int64, subDomainID string, subDomainNa
|
||||
|
||||
// PostData post data and invoke DNSPod API
|
||||
func (handler *Handler) PostData(url string, content url.Values) (string, error) {
|
||||
client := godns.GetHttpClient(handler.Configuration)
|
||||
client := godns.GetHttpClient(handler.Configuration, handler.Configuration.UseProxy)
|
||||
|
||||
if client == nil {
|
||||
return "", errors.New("failed to create HTTP client")
|
||||
|
@ -38,7 +38,15 @@ func (handler *Handler) DomainLoop(domain *godns.Domain, panicChan chan<- godns.
|
||||
}
|
||||
}()
|
||||
|
||||
looping := false
|
||||
for {
|
||||
if looping {
|
||||
// Sleep with interval
|
||||
log.Printf("Going to sleep, will start next checking in %d seconds...\r\n", handler.Configuration.Interval)
|
||||
time.Sleep(time.Second * time.Duration(handler.Configuration.Interval))
|
||||
}
|
||||
looping = true
|
||||
|
||||
currentIP, err := godns.GetCurrentIP(handler.Configuration)
|
||||
|
||||
if err != nil {
|
||||
@ -49,7 +57,12 @@ func (handler *Handler) DomainLoop(domain *godns.Domain, panicChan chan<- godns.
|
||||
|
||||
for _, subDomain := range domain.SubDomains {
|
||||
hostname := subDomain + "." + domain.DomainName
|
||||
lastIP := godns.ResolveDNS(hostname, handler.Configuration.Resolver, handler.Configuration.IPType)
|
||||
lastIP, err := godns.ResolveDNS(hostname, handler.Configuration.Resolver, handler.Configuration.IPType)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
continue
|
||||
}
|
||||
|
||||
//check against currently known IP, if no change, skip update
|
||||
if currentIP == lastIP {
|
||||
log.Printf("IP is the same as cached one. Skip update.\n")
|
||||
@ -63,10 +76,6 @@ func (handler *Handler) DomainLoop(domain *godns.Domain, panicChan chan<- godns.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sleep with interval
|
||||
log.Printf("Going to sleep, will start next checking in %d seconds...\r\n", handler.Configuration.Interval)
|
||||
time.Sleep(time.Second * time.Duration(handler.Configuration.Interval))
|
||||
}
|
||||
|
||||
}
|
||||
@ -106,7 +115,7 @@ func (handler *Handler) updateDNS(dns, ip, hostname, action string) {
|
||||
log.Fatalf("Unknown action %s\n", action)
|
||||
}
|
||||
|
||||
client := godns.GetHttpClient(handler.Configuration)
|
||||
client := godns.GetHttpClient(handler.Configuration, handler.Configuration.UseProxy)
|
||||
req, _ := http.NewRequest("POST", DreamhostURL, strings.NewReader(values.Encode()))
|
||||
req.SetBasicAuth(handler.Configuration.Email, handler.Configuration.Password)
|
||||
|
||||
|
@ -35,18 +35,25 @@ func (handler *Handler) DomainLoop(domain *godns.Domain, panicChan chan<- godns.
|
||||
}
|
||||
}()
|
||||
|
||||
looping := false
|
||||
|
||||
for {
|
||||
if looping {
|
||||
// Sleep with interval
|
||||
log.Printf("Going to sleep, will start next checking in %d seconds...\r\n", handler.Configuration.Interval)
|
||||
time.Sleep(time.Second * time.Duration(handler.Configuration.Interval))
|
||||
}
|
||||
|
||||
looping = true
|
||||
currentIP, err := godns.GetCurrentIP(handler.Configuration)
|
||||
|
||||
if err != nil {
|
||||
log.Println("get_currentIP:", err)
|
||||
continue
|
||||
}
|
||||
|
||||
log.Println("currentIP is:", currentIP)
|
||||
|
||||
//check against locally cached IP, if no change, skip update
|
||||
|
||||
client := godns.GetHttpClient(handler.Configuration)
|
||||
client := godns.GetHttpClient(handler.Configuration, handler.Configuration.UseProxy)
|
||||
var ip string
|
||||
|
||||
if strings.ToUpper(handler.Configuration.IPType) == godns.IPV4 {
|
||||
@ -57,7 +64,12 @@ func (handler *Handler) DomainLoop(domain *godns.Domain, panicChan chan<- godns.
|
||||
|
||||
for _, subDomain := range domain.SubDomains {
|
||||
hostname := subDomain + "." + domain.DomainName
|
||||
lastIP := godns.ResolveDNS(hostname, handler.Configuration.Resolver, handler.Configuration.IPType)
|
||||
lastIP, err := godns.ResolveDNS(hostname, handler.Configuration.Resolver, handler.Configuration.IPType)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
continue
|
||||
}
|
||||
|
||||
//check against currently known IP, if no change, skip update
|
||||
if currentIP == lastIP {
|
||||
log.Printf("IP is the same as cached one. Skip update.\n")
|
||||
@ -86,9 +98,5 @@ func (handler *Handler) DomainLoop(domain *godns.Domain, panicChan chan<- godns.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sleep with interval
|
||||
log.Printf("Going to sleep, will start next checking in %d seconds...\r\n", handler.Configuration.Interval)
|
||||
time.Sleep(time.Second * time.Duration(handler.Configuration.Interval))
|
||||
}
|
||||
}
|
||||
|
@ -36,7 +36,16 @@ func (handler *Handler) DomainLoop(domain *godns.Domain, panicChan chan<- godns.
|
||||
}
|
||||
}()
|
||||
|
||||
looping := false
|
||||
|
||||
for {
|
||||
if looping {
|
||||
// Sleep with interval
|
||||
log.Printf("Going to sleep, will start next checking in %d seconds...\r\n", handler.Configuration.Interval)
|
||||
time.Sleep(time.Second * time.Duration(handler.Configuration.Interval))
|
||||
}
|
||||
|
||||
looping = true
|
||||
currentIP, err := godns.GetCurrentIP(handler.Configuration)
|
||||
if err != nil {
|
||||
log.Println("get_currentIP:", err)
|
||||
@ -45,7 +54,12 @@ func (handler *Handler) DomainLoop(domain *godns.Domain, panicChan chan<- godns.
|
||||
log.Println("currentIP is:", currentIP)
|
||||
for _, subDomain := range domain.SubDomains {
|
||||
hostname := subDomain + "." + domain.DomainName
|
||||
lastIP := godns.ResolveDNS(hostname, handler.Configuration.Resolver, handler.Configuration.IPType)
|
||||
lastIP, err := godns.ResolveDNS(hostname, handler.Configuration.Resolver, handler.Configuration.IPType)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
continue
|
||||
}
|
||||
|
||||
//check against currently known IP, if no change, skip update
|
||||
if currentIP == lastIP {
|
||||
log.Printf("IP is the same as cached one. Skip update.\n")
|
||||
@ -59,16 +73,13 @@ func (handler *Handler) DomainLoop(domain *godns.Domain, panicChan chan<- godns.
|
||||
}
|
||||
}
|
||||
}
|
||||
// Sleep with interval
|
||||
log.Printf("Going to sleep, will start next checking in %d seconds...\r\n", handler.Configuration.Interval)
|
||||
time.Sleep(time.Second * time.Duration(handler.Configuration.Interval))
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// UpdateIP update subdomain with current IP
|
||||
func (handler *Handler) UpdateIP(domain, subDomain, currentIP string) {
|
||||
client := godns.GetHttpClient(handler.Configuration)
|
||||
client := godns.GetHttpClient(handler.Configuration, handler.Configuration.UseProxy)
|
||||
resp, err := client.Get(fmt.Sprintf(GoogleURL,
|
||||
handler.Configuration.Email,
|
||||
handler.Configuration.Password,
|
||||
@ -79,6 +90,7 @@ func (handler *Handler) UpdateIP(domain, subDomain, currentIP string) {
|
||||
if err != nil {
|
||||
// handle error
|
||||
log.Print("Failed to update sub domain:", subDomain)
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
@ -9,6 +9,7 @@ import (
|
||||
"github.com/TimothyYe/godns/handler/duck"
|
||||
"github.com/TimothyYe/godns/handler/google"
|
||||
"github.com/TimothyYe/godns/handler/he"
|
||||
"github.com/TimothyYe/godns/handler/noip"
|
||||
)
|
||||
|
||||
// IHandler is the interface for all DNS handlers
|
||||
@ -36,6 +37,8 @@ func CreateHandler(provider string) IHandler {
|
||||
handler = IHandler(&google.Handler{})
|
||||
case godns.DUCK:
|
||||
handler = IHandler(&duck.Handler{})
|
||||
case godns.NOIP:
|
||||
handler = IHandler(&noip.Handler{})
|
||||
}
|
||||
|
||||
return handler
|
||||
|
@ -37,7 +37,15 @@ func (handler *Handler) DomainLoop(domain *godns.Domain, panicChan chan<- godns.
|
||||
}
|
||||
}()
|
||||
|
||||
looping := false
|
||||
for {
|
||||
if looping {
|
||||
// Sleep with interval
|
||||
log.Printf("Going to sleep, will start next checking in %d seconds...\r\n", handler.Configuration.Interval)
|
||||
time.Sleep(time.Second * time.Duration(handler.Configuration.Interval))
|
||||
}
|
||||
looping = true
|
||||
|
||||
currentIP, err := godns.GetCurrentIP(handler.Configuration)
|
||||
|
||||
if err != nil {
|
||||
@ -50,7 +58,12 @@ func (handler *Handler) DomainLoop(domain *godns.Domain, panicChan chan<- godns.
|
||||
|
||||
for _, subDomain := range domain.SubDomains {
|
||||
hostname := subDomain + "." + domain.DomainName
|
||||
lastIP := godns.ResolveDNS(hostname, handler.Configuration.Resolver, handler.Configuration.IPType)
|
||||
lastIP, err := godns.ResolveDNS(hostname, handler.Configuration.Resolver, handler.Configuration.IPType)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
continue
|
||||
}
|
||||
|
||||
//check against currently known IP, if no change, skip update
|
||||
if currentIP == lastIP {
|
||||
log.Printf("IP is the same as cached one. Skip update.\n")
|
||||
@ -64,10 +77,6 @@ func (handler *Handler) DomainLoop(domain *godns.Domain, panicChan chan<- godns.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sleep with interval
|
||||
log.Printf("Going to sleep, will start next checking in %d seconds...\r\n", handler.Configuration.Interval)
|
||||
time.Sleep(time.Second * time.Duration(handler.Configuration.Interval))
|
||||
}
|
||||
|
||||
}
|
||||
@ -79,7 +88,7 @@ func (handler *Handler) UpdateIP(domain, subDomain, currentIP string) {
|
||||
values.Add("password", handler.Configuration.Password)
|
||||
values.Add("myip", currentIP)
|
||||
|
||||
client := godns.GetHttpClient(handler.Configuration)
|
||||
client := godns.GetHttpClient(handler.Configuration, handler.Configuration.UseProxy)
|
||||
|
||||
req, _ := http.NewRequest("POST", HEUrl, strings.NewReader(values.Encode()))
|
||||
resp, err := client.Do(req)
|
||||
|
114
handler/noip/noip_handler.go
Normal file
114
handler/noip/noip_handler.go
Normal file
@ -0,0 +1,114 @@
|
||||
package noip
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/TimothyYe/godns"
|
||||
)
|
||||
|
||||
var (
|
||||
// NoIPUrl the API address for NoIP
|
||||
NoIPUrl = "https://%s:%s@dynupdate.no-ip.com/nic/update?hostname=%s&%s"
|
||||
)
|
||||
|
||||
// Handler struct
|
||||
type Handler struct {
|
||||
Configuration *godns.Settings
|
||||
}
|
||||
|
||||
// SetConfiguration pass dns settings and store it to handler instance
|
||||
func (handler *Handler) SetConfiguration(conf *godns.Settings) {
|
||||
handler.Configuration = conf
|
||||
}
|
||||
|
||||
// DomainLoop the main logic loop
|
||||
func (handler *Handler) DomainLoop(domain *godns.Domain, panicChan chan<- godns.Domain) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
log.Printf("Recovered in %v: %v\n", err, debug.Stack())
|
||||
panicChan <- *domain
|
||||
}
|
||||
}()
|
||||
|
||||
looping := false
|
||||
|
||||
for {
|
||||
if looping {
|
||||
// Sleep with interval
|
||||
log.Printf("Going to sleep, will start next checking in %d seconds...\r\n", handler.Configuration.Interval)
|
||||
time.Sleep(time.Second * time.Duration(handler.Configuration.Interval))
|
||||
}
|
||||
|
||||
looping = true
|
||||
currentIP, err := godns.GetCurrentIP(handler.Configuration)
|
||||
|
||||
if err != nil {
|
||||
log.Println("get_currentIP:", err)
|
||||
continue
|
||||
}
|
||||
|
||||
log.Println("currentIP is:", currentIP)
|
||||
client := godns.GetHttpClient(handler.Configuration, handler.Configuration.UseProxy)
|
||||
|
||||
var ip string
|
||||
if strings.ToUpper(handler.Configuration.IPType) == godns.IPV4 {
|
||||
ip = fmt.Sprintf("myip=%s", currentIP)
|
||||
} else if strings.ToUpper(handler.Configuration.IPType) == godns.IPV6 {
|
||||
ip = fmt.Sprintf("myipv6=%s", currentIP)
|
||||
}
|
||||
|
||||
for _, subDomain := range domain.SubDomains {
|
||||
hostname := subDomain + "." + domain.DomainName
|
||||
lastIP, err := godns.ResolveDNS(hostname, handler.Configuration.Resolver, handler.Configuration.IPType)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
continue
|
||||
}
|
||||
|
||||
//check against currently known IP, if no change, skip update
|
||||
if currentIP == lastIP {
|
||||
log.Printf("IP is the same as cached one. Skip update.\n")
|
||||
} else {
|
||||
req, _ := http.NewRequest("GET", fmt.Sprintf(
|
||||
NoIPUrl,
|
||||
handler.Configuration.Email,
|
||||
handler.Configuration.Password,
|
||||
hostname,
|
||||
ip), nil)
|
||||
|
||||
if handler.Configuration.UserAgent != "" {
|
||||
req.Header.Add("User-Agent", handler.Configuration.UserAgent)
|
||||
}
|
||||
|
||||
// update IP with HTTP GET request
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
// handle error
|
||||
log.Print("Failed to update sub domain:", subDomain)
|
||||
continue
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil || !strings.Contains(string(body), "good") {
|
||||
log.Println("Failed to update the IP")
|
||||
continue
|
||||
} else {
|
||||
log.Print("IP updated to:", currentIP)
|
||||
}
|
||||
|
||||
// Send notification
|
||||
if err := godns.SendNotify(handler.Configuration, fmt.Sprintf("%s.%s", subDomain, domain.DomainName), currentIP); err != nil {
|
||||
log.Println("Failed to send notification")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,6 +1,6 @@
|
||||
// Package dns_resolver is a simple dns resolver
|
||||
// Package resolver is a simple dns resolver
|
||||
// based on miekg/dns
|
||||
package dns_resolver
|
||||
package resolver
|
||||
|
||||
import (
|
||||
"errors"
|
||||
@ -13,42 +13,47 @@ import (
|
||||
"github.com/miekg/dns"
|
||||
)
|
||||
|
||||
// DnsResolver represents a dns resolver
|
||||
type DnsResolver struct {
|
||||
// DNSResolver represents a dns resolver
|
||||
type DNSResolver struct {
|
||||
Servers []string
|
||||
RetryTimes int
|
||||
r *rand.Rand
|
||||
}
|
||||
|
||||
// New initializes DnsResolver.
|
||||
func New(servers []string) *DnsResolver {
|
||||
func New(servers []string) *DNSResolver {
|
||||
for i := range servers {
|
||||
servers[i] = net.JoinHostPort(servers[i], "53")
|
||||
}
|
||||
|
||||
return &DnsResolver{servers, len(servers) * 2, rand.New(rand.NewSource(time.Now().UnixNano()))}
|
||||
return &DNSResolver{servers, len(servers) * 2, rand.New(rand.NewSource(time.Now().UnixNano()))}
|
||||
}
|
||||
|
||||
// NewFromResolvConf initializes DnsResolver from resolv.conf like file.
|
||||
func NewFromResolvConf(path string) (*DnsResolver, error) {
|
||||
func NewFromResolvConf(path string) (*DNSResolver, error) {
|
||||
if _, err := os.Stat(path); os.IsNotExist(err) {
|
||||
return &DnsResolver{}, errors.New("no such file or directory: " + path)
|
||||
return &DNSResolver{}, errors.New("no such file or directory: " + path)
|
||||
}
|
||||
|
||||
config, err := dns.ClientConfigFromFile(path)
|
||||
servers := []string{}
|
||||
if err != nil {
|
||||
return &DNSResolver{}, err
|
||||
}
|
||||
|
||||
var servers []string
|
||||
for _, ipAddress := range config.Servers {
|
||||
servers = append(servers, net.JoinHostPort(ipAddress, "53"))
|
||||
}
|
||||
return &DnsResolver{servers, len(servers) * 2, rand.New(rand.NewSource(time.Now().UnixNano()))}, err
|
||||
return &DNSResolver{servers, len(servers) * 2, rand.New(rand.NewSource(time.Now().UnixNano()))}, err
|
||||
}
|
||||
|
||||
// LookupHost returns IP addresses of provied host.
|
||||
// In case of timeout retries query RetryTimes times.
|
||||
func (r *DnsResolver) LookupHost(host string, dnsType uint16) ([]net.IP, error) {
|
||||
func (r *DNSResolver) LookupHost(host string, dnsType uint16) ([]net.IP, error) {
|
||||
return r.lookupHost(host, dnsType, r.RetryTimes)
|
||||
}
|
||||
|
||||
func (r *DnsResolver) lookupHost(host string, dnsType uint16, triesLeft int) ([]net.IP, error) {
|
||||
func (r *DNSResolver) lookupHost(host string, dnsType uint16, triesLeft int) ([]net.IP, error) {
|
||||
m1 := new(dns.Msg)
|
||||
m1.Id = dns.Id()
|
||||
m1.RecursionDesired = true
|
||||
@ -56,14 +61,14 @@ func (r *DnsResolver) lookupHost(host string, dnsType uint16, triesLeft int) ([]
|
||||
|
||||
switch dnsType {
|
||||
case dns.TypeA:
|
||||
m1.Question[0] = dns.Question{dns.Fqdn(host), dns.TypeA, dns.ClassINET}
|
||||
m1.Question[0] = dns.Question{Name: dns.Fqdn(host), Qtype: dns.TypeA, Qclass: dns.ClassINET}
|
||||
case dns.TypeAAAA:
|
||||
m1.Question[0] = dns.Question{dns.Fqdn(host), dns.TypeAAAA, dns.ClassINET}
|
||||
m1.Question[0] = dns.Question{Name: dns.Fqdn(host), Qtype: dns.TypeAAAA, Qclass: dns.ClassINET}
|
||||
}
|
||||
|
||||
in, err := dns.Exchange(m1, r.Servers[r.r.Intn(len(r.Servers))])
|
||||
|
||||
result := []net.IP{}
|
||||
var result []net.IP
|
||||
|
||||
if err != nil {
|
||||
if strings.HasSuffix(err.Error(), "i/o timeout") && triesLeft > 0 {
|
||||
@ -78,18 +83,26 @@ func (r *DnsResolver) lookupHost(host string, dnsType uint16, triesLeft int) ([]
|
||||
}
|
||||
|
||||
if dnsType == dns.TypeA {
|
||||
for _, record := range in.Answer {
|
||||
if t, ok := record.(*dns.A); ok {
|
||||
result = append(result, t.A)
|
||||
if len(in.Answer) > 0 {
|
||||
for _, record := range in.Answer {
|
||||
if t, ok := record.(*dns.A); ok {
|
||||
result = append(result, t.A)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return result, errors.New("empty result")
|
||||
}
|
||||
}
|
||||
|
||||
if dnsType == dns.TypeAAAA {
|
||||
for _, record := range in.Answer {
|
||||
if t, ok := record.(*dns.AAAA); ok {
|
||||
result = append(result, t.AAAA)
|
||||
if len(in.Answer) > 0 {
|
||||
for _, record := range in.Answer {
|
||||
if t, ok := record.(*dns.AAAA); ok {
|
||||
result = append(result, t.AAAA)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return result, errors.New("Cannot resolve this domain, please make sure the IP type is right")
|
||||
}
|
||||
}
|
||||
|
@ -1,4 +1,4 @@
|
||||
package dns_resolver
|
||||
package resolver
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@ -40,6 +40,6 @@ func TestLookupHostIPv6_ValidServer(t *testing.T) {
|
||||
}
|
||||
|
||||
if result[0].String() != "2001:4860:4860::8888" {
|
||||
t.Error("result shoudl be: 2001:4860:4860::8888")
|
||||
t.Error("result should be: 2001:4860:4860::8888")
|
||||
}
|
||||
}
|
12
settings.go
12
settings.go
@ -12,12 +12,22 @@ type Domain struct {
|
||||
SubDomains []string `json:"sub_domains"`
|
||||
}
|
||||
|
||||
// Notify struct for slack notification
|
||||
type SlackNotify struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
BotApiToken string `json:"bot_api_token"`
|
||||
Channel string `json:"channel"`
|
||||
MsgTemplate string `json:"message_template"`
|
||||
UseProxy bool `json:"use_proxy"`
|
||||
}
|
||||
|
||||
// Notify struct for telegram notification
|
||||
type TelegramNotify struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
BotApiKey string `json:"bot_api_key"`
|
||||
ChatId string `json:"chat_id"`
|
||||
MsgTemplate string `json:"message_template"`
|
||||
UseProxy bool `json:"use_proxy"`
|
||||
}
|
||||
|
||||
// Notify struct for SMTP notification
|
||||
@ -34,6 +44,7 @@ type MailNotify struct {
|
||||
type Notify struct {
|
||||
Telegram TelegramNotify `json:"telegram"`
|
||||
Mail MailNotify `json:"mail"`
|
||||
Slack SlackNotify `json:"slack"`
|
||||
}
|
||||
|
||||
// Settings struct
|
||||
@ -53,6 +64,7 @@ type Settings struct {
|
||||
IPInterface string `json:"ip_interface"`
|
||||
IPType string `json:"ip_type"`
|
||||
Resolver string `json:"resolver"`
|
||||
UseProxy bool `json:"use_proxy"`
|
||||
}
|
||||
|
||||
// LoadSettings -- Load settings from config file
|
||||
|
115
utils.go
115
utils.go
@ -10,12 +10,14 @@ import (
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/TimothyYe/godns/dns_resolver"
|
||||
dnsResolver "github.com/TimothyYe/godns/resolver"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
"golang.org/x/net/proxy"
|
||||
gomail "gopkg.in/gomail.v2"
|
||||
"gopkg.in/gomail.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
@ -52,6 +54,8 @@ const (
|
||||
DUCK = "DuckDNS"
|
||||
// DREAMHOST for Dreamhost
|
||||
DREAMHOST = "Dreamhost"
|
||||
// NOIP for NoIP
|
||||
NOIP = "NoIP"
|
||||
// IPV4 for IPV4 mode
|
||||
IPV4 = "IPV4"
|
||||
// IPV6 for IPV6 mode
|
||||
@ -95,7 +99,7 @@ func GetIPFromInterface(configuration *Settings) (string, error) {
|
||||
}
|
||||
|
||||
if isIPv4(ip.String()) {
|
||||
if strings.ToUpper(configuration.IPType) == IPV4 {
|
||||
if strings.ToUpper(configuration.IPType) != IPV4 {
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
@ -116,10 +120,10 @@ func isIPv4(ip string) bool {
|
||||
}
|
||||
|
||||
// GetHttpClient creates the HTTP client and return it
|
||||
func GetHttpClient(configuration *Settings) *http.Client {
|
||||
func GetHttpClient(configuration *Settings, useProxy bool) *http.Client {
|
||||
client := &http.Client{}
|
||||
|
||||
if configuration.Socks5Proxy != "" {
|
||||
if useProxy && configuration.Socks5Proxy != "" {
|
||||
log.Println("use socks5 proxy:" + configuration.Socks5Proxy)
|
||||
dialer, err := proxy.SOCKS5("tcp", configuration.Socks5Proxy, nil, proxy.Direct)
|
||||
if err != nil {
|
||||
@ -216,6 +220,8 @@ func CheckSettings(config *Settings) error {
|
||||
return errors.New("login token cannot be empty")
|
||||
}
|
||||
case GOOGLE:
|
||||
fallthrough
|
||||
case NOIP:
|
||||
if config.Email == "" {
|
||||
return errors.New("email cannot be empty")
|
||||
}
|
||||
@ -249,21 +255,21 @@ func SendTelegramNotify(configuration *Settings, domain, currentIP string) error
|
||||
return errors.New("chat id cannot be empty")
|
||||
}
|
||||
|
||||
client := GetHttpClient(configuration)
|
||||
client := GetHttpClient(configuration, configuration.Notify.Telegram.UseProxy)
|
||||
tpl := configuration.Notify.Telegram.MsgTemplate
|
||||
if tpl == "" {
|
||||
tpl = "_Your IP address is changed to_%0A%0A*{{ .CurrentIP }}*%0A%0ADomain *{{ .Domain }}* is updated"
|
||||
}
|
||||
|
||||
msg := buildTemplate(currentIP, domain, tpl)
|
||||
url := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage?chat_id=%s&parse_mode=Markdown&text=%s",
|
||||
reqURL := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage?chat_id=%s&parse_mode=Markdown&text=%s",
|
||||
configuration.Notify.Telegram.BotApiKey,
|
||||
configuration.Notify.Telegram.ChatId,
|
||||
msg)
|
||||
var response *http.Response
|
||||
var err error
|
||||
|
||||
response, err = client.Get(url)
|
||||
response, err = client.Get(reqURL)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
@ -284,10 +290,10 @@ func SendTelegramNotify(configuration *Settings, domain, currentIP string) error
|
||||
Parameters *ResponseParameters `json:"parameters"`
|
||||
}
|
||||
var resp APIResponse
|
||||
err = json.Unmarshal([]byte(body), &resp)
|
||||
err = json.Unmarshal(body, &resp)
|
||||
if err != nil {
|
||||
fmt.Println("error:", err)
|
||||
return errors.New("Failed to parse response")
|
||||
return errors.New("failed to parse response")
|
||||
}
|
||||
if !resp.Ok {
|
||||
return errors.New(resp.Description)
|
||||
@ -311,7 +317,7 @@ func SendMailNotify(configuration *Settings, domain, currentIP string) error {
|
||||
log.Println("domain:", domain)
|
||||
m.SetBody("text/html", buildTemplate(currentIP, domain, mailTemplate))
|
||||
|
||||
d := gomail.NewPlainDialer(configuration.Notify.Mail.SMTPServer, configuration.Notify.Mail.SMTPPort, configuration.Notify.Mail.SMTPUsername, configuration.Notify.Mail.SMTPPassword)
|
||||
d := gomail.NewDialer(configuration.Notify.Mail.SMTPServer, configuration.Notify.Mail.SMTPPort, configuration.Notify.Mail.SMTPUsername, configuration.Notify.Mail.SMTPPassword)
|
||||
|
||||
// Send the email config by sendlist .
|
||||
if err := d.DialAndSend(m); err != nil {
|
||||
@ -320,6 +326,69 @@ func SendMailNotify(configuration *Settings, domain, currentIP string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// SendSlack sends slack if IP is changed
|
||||
func SendSlackNotify(configuration *Settings, domain, currentIP string) error {
|
||||
if !configuration.Notify.Slack.Enabled {
|
||||
return nil
|
||||
}
|
||||
|
||||
if configuration.Notify.Slack.BotApiToken == "" {
|
||||
return errors.New("bot api token cannot be empty")
|
||||
}
|
||||
|
||||
if configuration.Notify.Slack.Channel == "" {
|
||||
return errors.New("channel cannot be empty")
|
||||
}
|
||||
client := GetHttpClient(configuration, configuration.Notify.Slack.UseProxy)
|
||||
tpl := configuration.Notify.Slack.MsgTemplate
|
||||
if tpl == "" {
|
||||
tpl = "_Your IP address is changed to_\n\n*{{ .CurrentIP }}*\n\nDomain *{{ .Domain }}* is updated"
|
||||
}
|
||||
|
||||
msg := buildTemplate(currentIP, domain, tpl)
|
||||
|
||||
var response *http.Response
|
||||
var err error
|
||||
|
||||
formData := url.Values{
|
||||
"token": {configuration.Notify.Slack.BotApiToken},
|
||||
"channel": {configuration.Notify.Slack.Channel},
|
||||
"text": {msg},
|
||||
}
|
||||
|
||||
response, err = client.PostForm("https://slack.com/api/chat.postMessage", formData)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer response.Body.Close()
|
||||
|
||||
body, _ := ioutil.ReadAll(response.Body)
|
||||
type ResponseParameters struct {
|
||||
MigrateToChatID int64 `json:"migrate_to_chat_id"` // optional
|
||||
RetryAfter int `json:"retry_after"` // optional
|
||||
}
|
||||
type APIResponse struct {
|
||||
Ok bool `json:"ok"`
|
||||
Result json.RawMessage `json:"result"`
|
||||
ErrorCode int `json:"error_code"`
|
||||
Description string `json:"description"`
|
||||
Parameters *ResponseParameters `json:"parameters"`
|
||||
}
|
||||
var resp APIResponse
|
||||
err = json.Unmarshal(body, &resp)
|
||||
if err != nil {
|
||||
fmt.Println("error:", err)
|
||||
return errors.New("failed to parse response")
|
||||
}
|
||||
if !resp.Ok {
|
||||
return errors.New(resp.Description)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SendNotify sends notify if IP is changed
|
||||
func SendNotify(configuration *Settings, domain, currentIP string) error {
|
||||
err := SendTelegramNotify(configuration, domain, currentIP)
|
||||
@ -330,6 +399,10 @@ func SendNotify(configuration *Settings, domain, currentIP string) error {
|
||||
if err != nil {
|
||||
log.Println("Send email notification with error:", err.Error())
|
||||
}
|
||||
err = SendSlackNotify(configuration, domain, currentIP)
|
||||
if err != nil {
|
||||
log.Println("Send slack notification with error:", err.Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@ -358,7 +431,7 @@ func buildTemplate(currentIP, domain string, tplsrc string) string {
|
||||
}
|
||||
|
||||
// ResolveDNS will query DNS for a given hostname.
|
||||
func ResolveDNS(hostname, resolver, ipType string) string {
|
||||
func ResolveDNS(hostname, resolver, ipType string) (string, error) {
|
||||
var dnsType uint16
|
||||
if ipType == "" || strings.ToUpper(ipType) == IPV4 {
|
||||
dnsType = dns.TypeA
|
||||
@ -370,24 +443,20 @@ func ResolveDNS(hostname, resolver, ipType string) string {
|
||||
if resolver == "" {
|
||||
dnsAdress, err := net.LookupHost(hostname)
|
||||
if err != nil {
|
||||
if strings.HasSuffix(err.Error(), "no such host") {
|
||||
return "<nil>"
|
||||
}
|
||||
log.Fatalf(err.Error())
|
||||
return "<nil>", err
|
||||
}
|
||||
return dnsAdress[0]
|
||||
|
||||
return dnsAdress[0], nil
|
||||
}
|
||||
res := dns_resolver.New([]string{resolver})
|
||||
res := dnsResolver.New([]string{resolver})
|
||||
// In case of i/o timeout
|
||||
res.RetryTimes = 5
|
||||
|
||||
ip, err := res.LookupHost(hostname, dnsType)
|
||||
if err != nil {
|
||||
if strings.HasSuffix(err.Error(), "NXDOMAIN") {
|
||||
return "<nil>"
|
||||
}
|
||||
log.Fatalf(err.Error())
|
||||
return "<nil>", err
|
||||
}
|
||||
return ip[0].String()
|
||||
|
||||
return ip[0].String(), nil
|
||||
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user