modwebrepl.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2016 Paul Sokolovsky
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. */
  26. #include <stdio.h>
  27. #include <stdint.h>
  28. #include <string.h>
  29. #include "py/runtime.h"
  30. #include "py/stream.h"
  31. #include "py/builtin.h"
  32. #ifdef MICROPY_PY_WEBREPL_DELAY
  33. #include "py/mphal.h"
  34. #endif
  35. #include "extmod/modwebsocket.h"
  36. #if MICROPY_PY_WEBREPL
  37. #if 0 // print debugging info
  38. #define DEBUG_printf DEBUG_printf
  39. #else // don't print debugging info
  40. #define DEBUG_printf(...) (void)0
  41. #endif
  42. struct webrepl_file {
  43. char sig[2];
  44. char type;
  45. char flags;
  46. uint64_t offset;
  47. uint32_t size;
  48. uint16_t fname_len;
  49. char fname[64];
  50. } __attribute__((packed));
  51. enum { PUT_FILE = 1, GET_FILE, GET_VER };
  52. enum { STATE_PASSWD, STATE_NORMAL };
  53. typedef struct _mp_obj_webrepl_t {
  54. mp_obj_base_t base;
  55. mp_obj_t sock;
  56. byte state;
  57. byte hdr_to_recv;
  58. uint32_t data_to_recv;
  59. struct webrepl_file hdr;
  60. mp_obj_t cur_file;
  61. } mp_obj_webrepl_t;
  62. // These get passed to functions which aren't force-l32, so can't be const
  63. STATIC char passwd_prompt[] = "Password: ";
  64. STATIC char connected_prompt[] = "\r\nWebREPL connected\r\n>>> ";
  65. STATIC char denied_prompt[] = "\r\nAccess denied\r\n";
  66. STATIC char webrepl_passwd[10];
  67. STATIC void write_webrepl(mp_obj_t websock, const void *buf, size_t len) {
  68. const mp_stream_p_t *sock_stream = mp_get_stream(websock);
  69. int err;
  70. int old_opts = sock_stream->ioctl(websock, MP_STREAM_SET_DATA_OPTS, FRAME_BIN, &err);
  71. sock_stream->write(websock, buf, len, &err);
  72. sock_stream->ioctl(websock, MP_STREAM_SET_DATA_OPTS, old_opts, &err);
  73. }
  74. #define SSTR(s) s, sizeof(s) - 1
  75. STATIC void write_webrepl_str(mp_obj_t websock, const char *str, int sz) {
  76. int err;
  77. const mp_stream_p_t *sock_stream = mp_get_stream(websock);
  78. sock_stream->write(websock, str, sz, &err);
  79. }
  80. STATIC void write_webrepl_resp(mp_obj_t websock, uint16_t code) {
  81. char buf[4] = {'W', 'B', code & 0xff, code >> 8};
  82. write_webrepl(websock, buf, sizeof(buf));
  83. }
  84. STATIC mp_obj_t webrepl_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
  85. mp_arg_check_num(n_args, n_kw, 1, 2, false);
  86. mp_get_stream_raise(args[0], MP_STREAM_OP_READ | MP_STREAM_OP_WRITE | MP_STREAM_OP_IOCTL);
  87. DEBUG_printf("sizeof(struct webrepl_file) = %lu\n", sizeof(struct webrepl_file));
  88. mp_obj_webrepl_t *o = m_new_obj(mp_obj_webrepl_t);
  89. o->base.type = type;
  90. o->sock = args[0];
  91. o->hdr_to_recv = sizeof(struct webrepl_file);
  92. o->data_to_recv = 0;
  93. o->state = STATE_PASSWD;
  94. write_webrepl_str(args[0], SSTR(passwd_prompt));
  95. return o;
  96. }
  97. STATIC int write_file_chunk(mp_obj_webrepl_t *self) {
  98. const mp_stream_p_t *file_stream = mp_get_stream(self->cur_file);
  99. byte readbuf[2 + 256];
  100. int err;
  101. mp_uint_t out_sz = file_stream->read(self->cur_file, readbuf + 2, sizeof(readbuf) - 2, &err);
  102. if (out_sz == MP_STREAM_ERROR) {
  103. return out_sz;
  104. }
  105. readbuf[0] = out_sz;
  106. readbuf[1] = out_sz >> 8;
  107. DEBUG_printf("webrepl: Sending %d bytes of file\n", out_sz);
  108. write_webrepl(self->sock, readbuf, 2 + out_sz);
  109. return out_sz;
  110. }
  111. STATIC void handle_op(mp_obj_webrepl_t *self) {
  112. // Handle operations not requiring opened file
  113. switch (self->hdr.type) {
  114. case GET_VER: {
  115. static char ver[] = {MICROPY_VERSION_MAJOR, MICROPY_VERSION_MINOR, MICROPY_VERSION_MICRO};
  116. write_webrepl(self->sock, ver, sizeof(ver));
  117. self->hdr_to_recv = sizeof(struct webrepl_file);
  118. return;
  119. }
  120. }
  121. // Handle operations requiring opened file
  122. mp_obj_t open_args[2] = {
  123. mp_obj_new_str(self->hdr.fname, strlen(self->hdr.fname)),
  124. MP_OBJ_NEW_QSTR(MP_QSTR_rb)
  125. };
  126. if (self->hdr.type == PUT_FILE) {
  127. open_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_wb);
  128. }
  129. self->cur_file = mp_builtin_open(2, open_args, (mp_map_t*)&mp_const_empty_map);
  130. #if 0
  131. struct mp_stream_seek_t seek = { .offset = self->hdr.offset, .whence = 0 };
  132. int err;
  133. mp_uint_t res = file_stream->ioctl(self->cur_file, MP_STREAM_SEEK, (uintptr_t)&seek, &err);
  134. assert(res != MP_STREAM_ERROR);
  135. #endif
  136. write_webrepl_resp(self->sock, 0);
  137. if (self->hdr.type == PUT_FILE) {
  138. self->data_to_recv = self->hdr.size;
  139. } else if (self->hdr.type == GET_FILE) {
  140. self->data_to_recv = 1;
  141. }
  142. }
  143. STATIC mp_uint_t _webrepl_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode);
  144. STATIC mp_uint_t webrepl_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) {
  145. mp_uint_t out_sz;
  146. do {
  147. out_sz = _webrepl_read(self_in, buf, size, errcode);
  148. } while (out_sz == -2);
  149. return out_sz;
  150. }
  151. STATIC mp_uint_t _webrepl_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) {
  152. // We know that os.dupterm always calls with size = 1
  153. assert(size == 1);
  154. mp_obj_webrepl_t *self = self_in;
  155. const mp_stream_p_t *sock_stream = mp_get_stream(self->sock);
  156. mp_uint_t out_sz = sock_stream->read(self->sock, buf, size, errcode);
  157. //DEBUG_printf("webrepl: Read %d initial bytes from websocket\n", out_sz);
  158. if (out_sz == 0 || out_sz == MP_STREAM_ERROR) {
  159. return out_sz;
  160. }
  161. if (self->state == STATE_PASSWD) {
  162. char c = *(char*)buf;
  163. if (c == '\r' || c == '\n') {
  164. self->hdr.fname[self->data_to_recv] = 0;
  165. DEBUG_printf("webrepl: entered password: %s\n", self->hdr.fname);
  166. if (strcmp(self->hdr.fname, webrepl_passwd) != 0) {
  167. write_webrepl_str(self->sock, SSTR(denied_prompt));
  168. return 0;
  169. }
  170. self->state = STATE_NORMAL;
  171. self->data_to_recv = 0;
  172. write_webrepl_str(self->sock, SSTR(connected_prompt));
  173. } else if (self->data_to_recv < 10) {
  174. self->hdr.fname[self->data_to_recv++] = c;
  175. }
  176. return -2;
  177. }
  178. // If last read data belonged to text record (== REPL)
  179. int err;
  180. if (sock_stream->ioctl(self->sock, MP_STREAM_GET_DATA_OPTS, 0, &err) == 1) {
  181. return out_sz;
  182. }
  183. DEBUG_printf("webrepl: received bin data, hdr_to_recv: %d, data_to_recv=%d\n", self->hdr_to_recv, self->data_to_recv);
  184. if (self->hdr_to_recv != 0) {
  185. char *p = (char*)&self->hdr + sizeof(self->hdr) - self->hdr_to_recv;
  186. *p++ = *(char*)buf;
  187. if (--self->hdr_to_recv != 0) {
  188. mp_uint_t hdr_sz = sock_stream->read(self->sock, p, self->hdr_to_recv, errcode);
  189. if (hdr_sz == MP_STREAM_ERROR) {
  190. return hdr_sz;
  191. }
  192. self->hdr_to_recv -= hdr_sz;
  193. if (self->hdr_to_recv != 0) {
  194. return -2;
  195. }
  196. }
  197. DEBUG_printf("webrepl: op: %d, file: %s, chunk @%x, sz=%d\n", self->hdr.type, self->hdr.fname, (uint32_t)self->hdr.offset, self->hdr.size);
  198. handle_op(self);
  199. return -2;
  200. }
  201. if (self->data_to_recv != 0) {
  202. static byte filebuf[512];
  203. filebuf[0] = *(byte*)buf;
  204. mp_uint_t buf_sz = 1;
  205. if (--self->data_to_recv != 0) {
  206. size_t to_read = MIN(sizeof(filebuf) - 1, self->data_to_recv);
  207. mp_uint_t sz = sock_stream->read(self->sock, filebuf + 1, to_read, errcode);
  208. if (sz == MP_STREAM_ERROR) {
  209. return sz;
  210. }
  211. self->data_to_recv -= sz;
  212. buf_sz += sz;
  213. }
  214. if (self->hdr.type == PUT_FILE) {
  215. DEBUG_printf("webrepl: Writing %lu bytes to file\n", buf_sz);
  216. int err;
  217. mp_uint_t res = mp_stream_write_exactly(self->cur_file, filebuf, buf_sz, &err);
  218. if (err != 0 || res != buf_sz) {
  219. assert(0);
  220. }
  221. } else if (self->hdr.type == GET_FILE) {
  222. assert(buf_sz == 1);
  223. assert(self->data_to_recv == 0);
  224. assert(filebuf[0] == 0);
  225. mp_uint_t out_sz = write_file_chunk(self);
  226. if (out_sz != 0) {
  227. self->data_to_recv = 1;
  228. }
  229. }
  230. if (self->data_to_recv == 0) {
  231. mp_stream_close(self->cur_file);
  232. self->hdr_to_recv = sizeof(struct webrepl_file);
  233. DEBUG_printf("webrepl: Finished file operation %d\n", self->hdr.type);
  234. write_webrepl_resp(self->sock, 0);
  235. }
  236. #ifdef MICROPY_PY_WEBREPL_DELAY
  237. // Some platforms may have broken drivers and easily gets
  238. // overloaded with modest traffic WebREPL file transfers
  239. // generate. The basic workaround is a crude rate control
  240. // done in such way.
  241. mp_hal_delay_ms(MICROPY_PY_WEBREPL_DELAY);
  242. #endif
  243. }
  244. return -2;
  245. }
  246. STATIC mp_uint_t webrepl_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode) {
  247. mp_obj_webrepl_t *self = self_in;
  248. if (self->state == STATE_PASSWD) {
  249. // Don't forward output until passwd is entered
  250. return size;
  251. }
  252. const mp_stream_p_t *stream_p = mp_get_stream(self->sock);
  253. return stream_p->write(self->sock, buf, size, errcode);
  254. }
  255. STATIC mp_uint_t webrepl_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, int *errcode) {
  256. mp_obj_webrepl_t *self = MP_OBJ_TO_PTR(o_in);
  257. (void)arg;
  258. switch (request) {
  259. case MP_STREAM_CLOSE:
  260. // TODO: This is a place to do cleanup
  261. mp_stream_close(self->sock);
  262. return 0;
  263. default:
  264. *errcode = MP_EINVAL;
  265. return MP_STREAM_ERROR;
  266. }
  267. }
  268. STATIC mp_obj_t webrepl_set_password(mp_obj_t passwd_in) {
  269. size_t len;
  270. const char *passwd = mp_obj_str_get_data(passwd_in, &len);
  271. if (len > sizeof(webrepl_passwd) - 1) {
  272. mp_raise_ValueError(NULL);
  273. }
  274. strcpy(webrepl_passwd, passwd);
  275. return mp_const_none;
  276. }
  277. STATIC MP_DEFINE_CONST_FUN_OBJ_1(webrepl_set_password_obj, webrepl_set_password);
  278. STATIC const mp_rom_map_elem_t webrepl_locals_dict_table[] = {
  279. { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) },
  280. { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) },
  281. { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) },
  282. { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) },
  283. };
  284. STATIC MP_DEFINE_CONST_DICT(webrepl_locals_dict, webrepl_locals_dict_table);
  285. STATIC const mp_stream_p_t webrepl_stream_p = {
  286. .read = webrepl_read,
  287. .write = webrepl_write,
  288. .ioctl = webrepl_ioctl,
  289. };
  290. STATIC const mp_obj_type_t webrepl_type = {
  291. { &mp_type_type },
  292. .name = MP_QSTR__webrepl,
  293. .make_new = webrepl_make_new,
  294. .protocol = &webrepl_stream_p,
  295. .locals_dict = (mp_obj_dict_t*)&webrepl_locals_dict,
  296. };
  297. STATIC const mp_rom_map_elem_t webrepl_module_globals_table[] = {
  298. { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR__webrepl) },
  299. { MP_ROM_QSTR(MP_QSTR__webrepl), MP_ROM_PTR(&webrepl_type) },
  300. { MP_ROM_QSTR(MP_QSTR_password), MP_ROM_PTR(&webrepl_set_password_obj) },
  301. };
  302. STATIC MP_DEFINE_CONST_DICT(webrepl_module_globals, webrepl_module_globals_table);
  303. const mp_obj_module_t mp_module_webrepl = {
  304. .base = { &mp_type_module },
  305. .globals = (mp_obj_dict_t*)&webrepl_module_globals,
  306. };
  307. #endif // MICROPY_PY_WEBREPL