initial commit

netiawifi
selfisekai 2020-08-30 16:26:29 +02:00
commit 42a45807dd
13 changed files with 537 additions and 0 deletions

325
.gitignore vendored Normal file
View File

@ -0,0 +1,325 @@
# Created by https://www.toptal.com/developers/gitignore/api/python,linux,windows,macos,jetbrains,visualstudiocode
# Edit at https://www.toptal.com/developers/gitignore?templates=python,linux,windows,macos,jetbrains,visualstudiocode
### JetBrains ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### JetBrains Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr
# Sonarlint plugin
# https://plugins.jetbrains.com/plugin/7973-sonarlint
.idea/**/sonarlint/
# SonarQube Plugin
# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin
.idea/**/sonarIssues.xml
# Markdown Navigator plugin
# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced
.idea/**/markdown-navigator.xml
.idea/**/markdown-navigator-enh.xml
.idea/**/markdown-navigator/
# Cache file creation bug
# See https://youtrack.jetbrains.com/issue/JBR-2257
.idea/$CACHE_FILE$
# CodeStream plugin
# https://plugins.jetbrains.com/plugin/12206-codestream
.idea/codestream.xml
### Linux ###
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
### macOS ###
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
pytestdebug.log
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
doc/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
### VisualStudioCode ###
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
### VisualStudioCode Patch ###
# Ignore all local history of files
.history
### Windows ###
# Windows thumbnail cache files
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
# End of https://www.toptal.com/developers/gitignore/api/python,linux,windows,macos,jetbrains,visualstudiocode

6
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,6 @@
{
"python.linting.pylintEnabled": false,
"python.linting.flake8Enabled": true,
"python.linting.enabled": true,
"python.pythonPath": "/usr/bin/python"
}

4
librefi/__main__.py Normal file
View File

@ -0,0 +1,4 @@
from .librefi import LibreFi
librefi = LibreFi()
librefi._periodical_check()

View File

@ -0,0 +1,7 @@
import sys
def get_connector():
if sys.platform == "linux":
from .networkmanager import NetworkManagerConnector
return NetworkManagerConnector

View File

@ -0,0 +1,61 @@
import subprocess
import pipes
import re
class NetworkManagerConnector:
NMCLI_BASE = ["nmcli", "--mode", "tabular", "--terse", "--colors", "no"]
def _call_nmcli(self, args, parse=True):
subp = subprocess.run(self.NMCLI_BASE + args,
capture_output=True, text=True)
if parse:
return [
[field.replace("\\:", ":")
for field in re.split(r"(?<!\\):", line)]
for line in subp.stdout.strip().split("\n")]
return subp.stdout
def status(self):
infs = self._call_nmcli(["--fields", "TYPE,NAME",
"connection", "show",
"--active"])
for inf in infs:
if inf[0] == "802-3-ethernet":
return {
"connected": True,
"connection_type": "wired",
"connection_name": inf[1],
}
for inf in infs:
if inf[0] == "802-11-wireless":
return {
"connected": True,
"connection_type": "wifi",
"connection_name": inf[1],
}
return {
"connected": False,
}
def list(self):
infs = self._call_nmcli(["--fields", "SSID,SIGNAL,SECURITY,IN-USE",
"device", "wifi", "list"])
networks = []
for inf in infs:
networks.append({
"ssid": inf[0],
"signal": int(inf[1]),
"is_open": inf[2] == "", # does it require password?
"currently_connected": inf[3] == "*",
})
return networks
def rescan(self):
self._call_nmcli(["device", "wifi", "rescan"], parse=False)
def connect(self, network):
self._call_nmcli(["device", "wifi", "connect",
pipes.quote(network["ssid"])], parse=False)

View File

@ -0,0 +1,21 @@
import requests
from http.cookiejar import CookieJar
from ..utils import get_user_agent
class BaseFxcker:
def __init__(self):
self.cookie_jar = CookieJar()
@property
def FXCKER_KEY(self):
return self.__class__.__name__[:-6]
def request(self, method, url, **kwargs):
kwargs["cookies"] = self.cookie_jar
if not kwargs["headers"]:
kwargs["headers"] = {}
if not kwargs["headers"]["User-Agent"]:
kwargs["headers"]["User-Agent"] = get_user_agent()
return requests.request(method, url, **kwargs)

View File

@ -0,0 +1,7 @@
from ._common import BaseFxcker
# for just plain free wi-fi
class DummyFxcker(BaseFxcker):
def unfxck(self):
return True

9
librefi/fxckers/_map.py Normal file
View File

@ -0,0 +1,9 @@
from ._dummy import DummyFxcker
from .umwarszawa import UMWarszawaFxcker
from .ledatel import LedatelFxcker
fxckers_map = [
([r"re:MZK Opole \d{3}(?: (?:2.4|5)GHz)?"], DummyFxcker),
(["UM-Warszawa"], UMWarszawaFxcker),
(["Pendolino_WiFi"], LedatelFxcker),
]

View File

@ -0,0 +1,6 @@
from ._common import BaseFxcker
class LedatelFxcker(BaseFxcker):
def unfxck(self):
return False

View File

@ -0,0 +1,18 @@
from ._common import BaseFxcker
from ..utils import regex_search_string, dump_qs
class UMWarszawaFxcker(BaseFxcker):
_BASE_URL = "https://hotspotsystem.um.warszawa.pl"
def unfxck(self):
start_page = self.request(
"GET", self._BASE_URL + "/free/index.php").text
id = regex_search_string(
r'<input type="hidden" name="id" value="(\d+)"/>', start_page)
self.request("POST", self._BASE_URL +
"/free/login.php", data=dump_qs({
"id": id,
"register": "I accept - Connect me",
}))
return True

42
librefi/librefi.py Normal file
View File

@ -0,0 +1,42 @@
#!/usr/bin/env python3
from .connectors import get_connector
from .fxckers._map import fxckers_map
import re
import requests
class LibreFi:
def __init__(self):
self.connector = get_connector()()
self.current_fxcker = None
def _periodical_check(self):
status = self.connector.status()
print(status)
if not status["connected"]:
networks = self.connector.list()
chosen_network = None
for network in networks:
for fxck_element in fxckers_map:
for fxck_net_name in fxck_element[0]:
if fxck_net_name[:3] == "re:":
if re.fullmatch(fxck_net_name,
"re:" + network["ssid"]):
chosen_network = network
self.current_fxcker = fxck_element[1]
break
elif fxck_net_name == network["ssid"]:
chosen_network = network
self.current_fxcker = fxck_element[1]
break
if chosen_network is not None:
self.connector.connect(chosen_network)
status = self.connector.status()
if status["connected"]:
check_req = requests.get(
"http://detectportal.firefox.com/success.txt",
allow_redirects=False)
if check_req.text.strip() != "success":
self.current_fxcker.unfxck()

1
librefi/requirements.txt Normal file
View File

@ -0,0 +1 @@
requests===2.24.0

30
librefi/utils.py Normal file
View File

@ -0,0 +1,30 @@
# flake8: noqa: E501
import re
from urllib.parse import parse_qs, quote
def get_user_agent():
# TODO: randomize it
return "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"
def regex_search_string(regexes, string, default=None):
if not isinstance(regexes, list):
regexes = [regexes]
for regex in regexes:
match = re.match(regex, string)
if match:
return match
return default
def dump_qs(obj):
qs = ""
for key in obj:
if isinstance(obj[key], (str, int, float)):
qs += quote(key) + "=" + quote(str(obj[key]))
else:
# TODO: support nested dicts and lists
raise TypeError("unknown types in dump_qs")
return qs