Guest User

Untitled

a guest
Apr 24th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.37 KB | None | 0 0
  1. import ubinascii
  2. import utime
  3. import socket
  4. import select
  5.  
  6.  
  7. html = """<!DOCTYPE html>
  8. <html>
  9. <head> <title>Ouroboros IoT Login</title> </head>
  10. <body>
  11. <form action="configure.html" method="POST">
  12. Username : <input type="text" name="username"></br>
  13. Password: <input type="password" name="password" ></br>
  14. <input type="submit" value="submit" name="submit">
  15. </form>
  16. </body>
  17. </html>
  18. """
  19.  
  20. # Find out the post parameters in a dictionary
  21. def get_post_params(req):
  22. print("Inside POST PARAMS : req = " + req)
  23. post_params = req.split('rn')[-1:][0]
  24. # Check if the post body contains the necessary fields
  25. # Split the post_params by &
  26. # params : ['username=', 'password=', 'method=POST', 'url=http%3A%2F%2Ftwig-me.com%2Fv1%2Fusergroups%2FWKMUYXELA9LCC', 'jsondata=', 'submit=submit']
  27. print("post_params : " + post_params)
  28. params = post_params.split('&')
  29. print("Params")
  30. print(params)
  31. # Initialize the key value pair dict
  32. post_dict = {}
  33. # Iterate on each param
  34. for param in params:
  35. # Each param would be like 'method=POST', etc
  36. key_val = param.split('=')
  37. print("Key Val :")
  38. print(key_val)
  39. key = key_val[0]
  40. val = key_val[1]
  41. # Update post_dict
  42. post_dict[key] = val
  43. return post_dict
  44.  
  45. # This web server takes care of the WiFi configuration
  46. # max_run_sec
  47. def web_server(max_run_sec = None):
  48. # Create server socket
  49. addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
  50. s = socket.socket()
  51. # TODO : If both the wifi and sta are operating simultaneously, then bind only to WiFi
  52. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  53. s.bind(addr)
  54. s.listen(1)
  55. poller = select.poll()
  56. poller.register(s, select.POLLIN)
  57. startTimeEpoch = utime.time()
  58.  
  59. while True:
  60. all_events = poller.poll(200) # time in milliseconds
  61. if len(all_events) > 0:
  62. try:
  63. print("Just after GC Collect!")
  64. gc.collect()
  65. #print("Just before accepting")
  66. res = s.accept()
  67. client_s = res[0]
  68. client_addr = res[1]
  69. req = ''
  70. req = client_s.recv(4096)
  71. req = req.decode()
  72. req = str(req)
  73. # Came here means that there has been some connection!
  74. # Reset the start time epoch in such a case:
  75. startTimeEpoch = utime.time()
  76. # Check route now
  77. if req.find('configure.html') != -1:
  78. print("Got configure request!rn")
  79. # Check if the username and password are correct, if not, configure:
  80. login_config = get_login_config()
  81. username = login_config['user']
  82. pwd = login_config['password']
  83. print("Username : " + username + ", pwd : " + pwd)
  84. # Find the POST PARAMETERS sent
  85. # There would be just one entry in the array, so get the 0th index directly
  86. # post_params : 'username=&password=&method=POST&url=http%3A%2F%2Fjam-me.com%2Fv1%2Fusergroups%2FWKMUYXELA9LCC&jsondata=&submit=submit'
  87. post_dict = get_post_params(req)
  88. # Now check if the post_dict has the key and value for username and password as needed?
  89. username_post = post_dict['username']
  90. password_post = post_dict['password']
  91. # Check if the password is same as expected
  92. if (username_post == username) and (password_post == pwd):
  93. hidden_input = '<input type="hidden" name="username" value="' + username + '"><input type="hidden" name="passphrase" value="' + pwd + '">'
  94. # Send the login username and password inside the hidden input field
  95. configure_html = "<!DOCTYPE html><html><head> <title>Ouroboros IoT WiFi Configuration Page</title> </head><body><form action="configure_wifi.html" method="POST">WiFi SSID : <input type="text" name="essid"></br>WiFi Password: <input type="password" name="passphrase" ></br>" + hidden_input + "<input type="submit" value="submit" name="submit"></form></body></html>"
  96. # TODO : Also show link to webpage, where from we can change the login credentials
  97. client_s.send(configure_html)
  98. else:
  99. client_s.send(login_fail_html)
  100. elif req.find('configure_wifi.html') != -1:
  101. # Check if the username and password are correct, if not, configure:
  102. login_config = get_login_config()
  103. username = login_config['user']
  104. pwd = login_config['password']
  105. # Get post parameters
  106. post_dict = get_post_params(req)
  107. # Now check if the post_dict has the key and value for username and password as needed?
  108. username_post = post_dict['username']
  109. password_post = post_dict['password']
  110.  
  111. # Check if the password is same as expected
  112. if (username_post == username) and (password_post == pwd):
  113. # Do some sanity check for handling the new wifi ssid and password
  114. new_wifi_ssid = post_dict['essid']
  115. new_wifi_passphrase = post_dict['passphrase']
  116. # Set the wifi credentials
  117. save_wifi_config(new_wifi_ssid, new_wifi_passphrase)
  118. client_s.send('<!DOCTYPE html><html><head> <title>Ouroboros IoT WiFi Configuration Success</title> </head><body>Configuration successful!<br>Device would go into reboot now!</body></html>')
  119. # Reboot device now
  120. machine.reset()
  121. else:
  122. client_s.send(login_fail_html)
  123. elif req.find('index.html') != -1:
  124. print("Got index.html request!rn")
  125. client_s.send(html)
  126. else :
  127. # Do nothing
  128. print("Invalid request received! Show the login page again!rn")
  129. client_s.send(html)
  130.  
  131. except OSError:
  132. # Got no request and it timedout!
  133. print("Timed-out, no request received!rn")
  134. except Exception as e:
  135. print("Got some exceptionrn")
  136. print(str(e))
  137. finally:
  138. client_s.close()
  139. if max_run_sec is not None:
  140. elapsedTime = utime.time() - startTimeEpoch
  141. if elapsedTime > max_run_sec:
  142. # Max run time of web server has elapsed, time to exit this mode!
  143. break
  144. # Unregister poller
  145. poller.unregister(s)
  146. # When while loop ends!
  147.  
  148. Inside POST PARAMS : req = GET /configure.html HTTP/1.1
  149. Host: 192.168.0.1
  150. Connection: keep-alive
  151. Cache-Control: max-age=0
  152. Upgrade-Insecure-Requests: 1
  153. User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/65.0.3325.181 Chrome/65.0.3325.181 Safari/537.36
  154. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
  155. Accept-Encoding: gzip, deflate
  156. Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
Add Comment
Please, Sign In to add comment