Fix ignoring gateway parameter (#34)

* Add custom exceptions and fix logging

* Fix "done" message

* Fix gateway stuff

* Fix `P:`

* Fix cscook's `--reg-notify` code
This commit is contained in:
Kasherpete 2023-10-23 18:28:36 -05:00 committed by GitHub
parent b4a288171b
commit 9a0f55ab18
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 90 additions and 22 deletions

24
demo.py
View file

@ -16,6 +16,8 @@ import imessage
import trio
import argparse
from exceptions import *
logging.basicConfig(
level=logging.NOTSET, format="%(message)s", datefmt="[%X]", handlers=[RichHandler()]
)
@ -107,10 +109,9 @@ async def main(args: argparse.Namespace):
print("Would you like to register a phone number? (y/n)")
if input("> ").lower() == "y":
import sms_registration
if args.gateway is not None:
sms_registration.GATEWAY = args.gateway
if args.phone is not None:
sms_registration.PHONE_IP = args.phone
if args.phone is None:
raise GatewayConnectionError("You did not supply an IP address.")
if "phone" in CONFIG:
phone_sig = b64decode(CONFIG["phone"].get("sig"))
@ -119,7 +120,9 @@ async def main(args: argparse.Namespace):
phone_number, phone_sig = sms_registration.parse_pdu(args.pdu, None)
else:
import sms_registration
phone_number, phone_sig = sms_registration.register(conn.credentials.token, args.trigger_pdu)
phone_number, phone_sig = sms_registration.register(push_token=conn.credentials.token,
no_parse=args.trigger_pdu, gateway=args.gateway,
phone_ip=args.phone)
CONFIG["phone"] = {
"number": phone_number,
"sig": b64encode(phone_sig).decode(),
@ -152,7 +155,7 @@ async def main(args: argparse.Namespace):
if args.reregister:
print("Re-registering...")
users = register(conn, users)
register(conn, users)
CONFIG["users"] = []
for user in users:
@ -165,10 +168,11 @@ async def main(args: argparse.Namespace):
"id_cert": user.id_cert,
"handles": user.handles,
})
if "P:" in str(user.user_id):
expiration = get_not_valid_after_timestamp(user.id_cert)
expiration = str(expiration) + " UTC"
print("Number registration is valid until "+ expiration)
print(f"Number registration is valid until {expiration}. (YYYY/MM/DD)")
else:
email_user = user
for n in range(len(user.handles)):
@ -178,9 +182,10 @@ async def main(args: argparse.Namespace):
safe_config()
if args.reg_notify:
im = imessage.iMessageUser(conn, email_user)
im.current_handle = email_addr
await im.send(imessage.iMessage.create(im, "Number registration is valid until " + expiration, [email_addr]))
print(f"Done?")
print("Done!")
if args.alive:
logging.getLogger("apns").setLevel(logging.DEBUG)
@ -313,7 +318,6 @@ if __name__ == "__main__":
args = parser.parse_args()
if args.pdu is not None and not args.pdu.startswith("REG-RESP"):
print("Invalid REG-RESP PDU")
exit(1)
raise InvalidResponseError("Received invalid REG-RESP PDU from Gateway Client.")
trio.run(main, args)

31
exceptions.py Normal file
View file

@ -0,0 +1,31 @@
class GatewayError(Exception):
def __init__(self, reason):
self.reason = reason
def __str__(self):
return self.reason
class GatewayConnectionError(Exception):
def __init__(self, reason):
self.reason = reason
def __str__(self):
return self.reason
class DecodeError(Exception):
def __init__(self, reason):
self.reason = reason
def __str__(self):
return self.reason
class InvalidResponseError(Exception):
def __init__(self, reason):
self.reason = reason
def __str__(self):
return self.reason

View file

@ -1,37 +1,70 @@
import requests
from requests.exceptions import ConnectionError
import random
import apns
import trio
import gateway_fetch
from base64 import b64decode, b64encode
from exceptions import *
import urllib3
urllib3.disable_warnings()
PHONE_IP = "192.168.5.120"
API_PORT = 8080
GATEWAY = "22223333"
def register(push_token: bytes, no_parse = False, gateway = None) -> tuple[str, bytes]:
def register(push_token: bytes, no_parse, gateway: str | None, phone_ip: str) -> tuple[str, bytes]:
"""Forwards a registration request to the phone and returns the phone number, signature for the provided push token"""
if gateway is None:
print("Requesting device MCC+MNC for gateway detection...")
mccmnc = requests.get(f"http://{PHONE_IP}:{API_PORT}/info", timeout=30).text
try:
mccmnc = requests.get(f"http://{phone_ip}:{API_PORT}/info", timeout=30).text
except ConnectionError:
raise GatewayConnectionError("Could not connect to device! Please open the Pypush SMS Helper App.")
except Exception as e:
raise GatewayError(f"ERROR: An unknown error occurred: '{e}'")
print("MCC+MNC received! " + mccmnc)
print("Determining gateway...")
print(mccmnc)
gateway = gateway_fetch.getGatewayMCCMNC(mccmnc)
if gateway is not None:
print("Gateway found! " + str(gateway))
else:
print("No gateway was provided, and automatic gateway detection failed. Please run again with the --gateway flag.")
# gateway = GATEWAY
raise
if gateway is not None:
print("Gateway found! " + str(gateway))
else:
raise GatewayError(f"No gateway was provided, and automatic gateway detection failed. Please run again with the --gateway flag.")
token = push_token.hex().upper()
req_id = random.randint(0, 2**32)
sms = f"REG-REQ?v=3;t={token};r={req_id};"
print("Sending message and waiting for response...")
r = requests.get(f"http://{PHONE_IP}:{API_PORT}/register", params={"sms": sms, "gateway": gateway}, timeout=30)
print("Received response from device!")
try:
r = requests.get(f"http://{phone_ip}:{API_PORT}/register", params={"sms": sms, "gateway": gateway}, timeout=30)
except Exception as e:
raise GatewayError(f"ERROR: An unknown error occurred: '{e}'")
if 'error' in r.text.lower():
if 'permission.SEND_SMS' in r.text.lower():
raise GatewayError(f"Please allow the SMS permission!")
raise GatewayError(f"An error was thrown from PNRgateway Client: '{r.text}'")
# POSSIBLE ERRORS FROM APP:
# Error: timeout waiting for response from gateway (unlikely, timeout is implemented here too)
# Error sending SMS
# Error: sms parameter not found
# Error: gateway parameter not found
print('\033[92m', "Received response from device!", '\033[0m')
if no_parse:
print("Now do the next part and rerun with --pdu")
exit()