modwebrepl.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. #include "genhdr/mpversion.h"
  37. #if MICROPY_PY_WEBREPL
  38. #if 0 // print debugging info
  39. #define DEBUG_printf DEBUG_printf
  40. #else // don't print debugging info
  41. #define DEBUG_printf(...) (void)0
  42. #endif
  43. struct webrepl_file {
  44. char sig[2];
  45. char type;
  46. char flags;
  47. uint64_t offset;
  48. uint32_t size;
  49. uint16_t fname_len;
  50. char fname[64];
  51. } __attribute__((packed));
  52. enum { PUT_FILE = 1, GET_FILE, GET_VER };
  53. enum { STATE_PASSWD, STATE_NORMAL };
  54. typedef struct _mp_obj_webrepl_t {
  55. mp_obj_base_t base;
  56. mp_obj_t sock;
  57. byte state;
  58. byte hdr_to_recv;
  59. uint32_t data_to_recv;
  60. struct webrepl_file hdr;
  61. mp_obj_t cur_file;
  62. } mp_obj_webrepl_t;
  63. // These get passed to functions which aren't force-l32, so can't be const
  64. STATIC char passwd_prompt[] = "Password: ";
  65. STATIC char connected_prompt[] = "\r\nWebREPL connected\r\n>>> ";
  66. STATIC char denied_prompt[] = "\r\nAccess denied\r\n";
  67. STATIC char webrepl_passwd[10];
  68. STATIC void write_webrepl(mp_obj_t websock, const void *buf, size_t len) {
  69. const mp_stream_p_t *sock_stream = mp_get_stream_raise(websock, MP_STREAM_OP_WRITE | MP_STREAM_OP_IOCTL);
  70. int err;
  71. int old_opts = sock_stream->ioctl(websock, MP_STREAM_SET_DATA_OPTS, FRAME_BIN, &err);
  72. sock_stream->write(websock, buf, len, &err);
  73. sock_stream->ioctl(websock, MP_STREAM_SET_DATA_OPTS, old_opts, &err);
  74. }
  75. #define SSTR(s) s, sizeof(s) - 1
  76. STATIC void write_webrepl_str(mp_obj_t websock, const char *str, int sz) {
  77. int err;
  78. const mp_stream_p_t *sock_stream = mp_get_stream_raise(websock, MP_STREAM_OP_WRITE | MP_STREAM_OP_IOCTL);
  79. sock_stream->write(websock, str, sz, &err);
  80. }
  81. STATIC void write_webrepl_resp(mp_obj_t websock, uint16_t code) {
  82. char buf[4] = {'W', 'B', code & 0xff, code >> 8};
  83. write_webrepl(websock, buf, sizeof(buf));
  84. }
  85. 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) {
  86. mp_arg_check_num(n_args, n_kw, 1, 2, false);
  87. mp_get_stream_raise(args[0], MP_STREAM_OP_READ | MP_STREAM_OP_WRITE | MP_STREAM_OP_IOCTL);
  88. DEBUG_printf("sizeof(struct webrepl_file) = %lu\n", sizeof(struct webrepl_file));
  89. mp_obj_webrepl_t *o = m_new_obj(mp_obj_webrepl_t);
  90. o->base.type = type;
  91. o->sock = args[0];
  92. o->hdr_to_recv = sizeof(struct webrepl_file);
  93. o->data_to_recv = 0;
  94. o->state = STATE_PASSWD;
  95. write_webrepl_str(args[0], SSTR(passwd_prompt));
  96. return o;
  97. }
  98. STATIC int write_file_chunk(mp_obj_webrepl_t *self) {
  99. const mp_stream_p_t *file_stream =
  100. mp_get_stream_raise(self->cur_file, MP_STREAM_OP_READ | MP_STREAM_OP_WRITE | MP_STREAM_OP_IOCTL);
  101. byte readbuf[2 + 256];
  102. int err;
  103. mp_uint_t out_sz = file_stream->read(self->cur_file, readbuf + 2, sizeof(readbuf) - 2, &err);
  104. if (out_sz == MP_STREAM_ERROR) {
  105. return out_sz;
  106. }
  107. readbuf[0] = out_sz;
  108. readbuf[1] = out_sz >> 8;
  109. DEBUG_printf("webrepl: Sending %d bytes of file\n", out_sz);
  110. write_webrepl(self->sock, readbuf, 2 + out_sz);
  111. return out_sz;
  112. }
  113. STATIC void handle_op(mp_obj_webrepl_t *self) {
  114. // Handle operations not requiring opened file
  115. switch (self->hdr.type) {
  116. case GET_VER: {
  117. static char ver[] = {MICROPY_VERSION_MAJOR, MICROPY_VERSION_MINOR, MICROPY_VERSION_MICRO};
  118. write_webrepl(self->sock, ver, sizeof(ver));
  119. self->hdr_to_recv = sizeof(struct webrepl_file);
  120. return;
  121. }
  122. }
  123. // Handle operations requiring opened file
  124. mp_obj_t open_args[2] = {
  125. mp_obj_new_str(self->hdr.fname, strlen(self->hdr.fname), false),
  126. MP_OBJ_NEW_QSTR(MP_QSTR_rb)
  127. };
  128. if (self->hdr.type == PUT_FILE) {
  129. open_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_wb);
  130. }
  131. self->cur_file = mp_builtin_open(2, open_args, (mp_map_t*)&mp_const_empty_map);
  132. #if 0
  133. struct mp_stream_seek_t seek = { .offset = self->hdr.offset, .whence = 0 };
  134. int err;
  135. mp_uint_t res = file_stream->ioctl(self->cur_file, MP_STREAM_SEEK, (uintptr_t)&seek, &err);
  136. assert(res != MP_STREAM_ERROR);
  137. #endif
  138. write_webrepl_resp(self->sock, 0);
  139. if (self->hdr.type == PUT_FILE) {
  140. self->data_to_recv = self->hdr.size;
  141. } else if (self->hdr.type == GET_FILE) {
  142. self->data_to_recv = 1;
  143. }
  144. }
  145. STATIC mp_uint_t _webrepl_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode);
  146. STATIC mp_uint_t webrepl_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) {
  147. mp_uint_t out_sz;
  148. do {
  149. out_sz = _webrepl_read(self_in, buf, size, errcode);
  150. } while (out_sz == -2);
  151. return out_sz;
  152. }
  153. STATIC mp_uint_t _webrepl_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) {
  154. // We know that os.dupterm always calls with size = 1
  155. assert(size == 1);
  156. mp_obj_webrepl_t *self = self_in;
  157. const mp_stream_p_t *sock_stream = mp_get_stream_raise(self->sock, MP_STREAM_OP_READ);
  158. mp_uint_t out_sz = sock_stream->read(self->sock, buf, size, errcode);
  159. //DEBUG_printf("webrepl: Read %d initial bytes from websocket\n", out_sz);
  160. if (out_sz == 0 || out_sz == MP_STREAM_ERROR) {
  161. return out_sz;
  162. }
  163. if (self->state == STATE_PASSWD) {
  164. char c = *(char*)buf;
  165. if (c == '\r' || c == '\n') {
  166. self->hdr.fname[self->data_to_recv] = 0;
  167. DEBUG_printf("webrepl: entered password: %s\n", self->hdr.fname);
  168. if (strcmp(self->hdr.fname, webrepl_passwd) != 0) {
  169. write_webrepl_str(self->sock, SSTR(denied_prompt));
  170. return 0;
  171. }
  172. self->state = STATE_NORMAL;
  173. self->data_to_recv = 0;
  174. write_webrepl_str(self->sock, SSTR(connected_prompt));
  175. } else if (self->data_to_recv < 10) {
  176. self->hdr.fname[self->data_to_recv++] = c;
  177. }
  178. return -2;
  179. }
  180. // If last read data belonged to text record (== REPL)
  181. int err;
  182. if (sock_stream->ioctl(self->sock, MP_STREAM_GET_DATA_OPTS, 0, &err) == 1) {
  183. return out_sz;
  184. }
  185. DEBUG_printf("webrepl: received bin data, hdr_to_recv: %d, data_to_recv=%d\n", self->hdr_to_recv, self->data_to_recv);
  186. if (self->hdr_to_recv != 0) {
  187. char *p = (char*)&self->hdr + sizeof(self->hdr) - self->hdr_to_recv;
  188. *p++ = *(char*)buf;
  189. if (--self->hdr_to_recv != 0) {
  190. mp_uint_t hdr_sz = sock_stream->read(self->sock, p, self->hdr_to_recv, errcode);
  191. if (hdr_sz == MP_STREAM_ERROR) {
  192. return hdr_sz;
  193. }
  194. self->hdr_to_recv -= hdr_sz;
  195. if (self->hdr_to_recv != 0) {
  196. return -2;
  197. }
  198. }
  199. 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);
  200. handle_op(self);
  201. return -2;
  202. }
  203. if (self->data_to_recv != 0) {
  204. static byte filebuf[512];
  205. filebuf[0] = *(byte*)buf;
  206. mp_uint_t buf_sz = 1;
  207. if (--self->data_to_recv != 0) {
  208. size_t to_read = MIN(sizeof(filebuf) - 1, self->data_to_recv);
  209. mp_uint_t sz = sock_stream->read(self->sock, filebuf + 1, to_read, errcode);
  210. if (sz == MP_STREAM_ERROR) {
  211. return sz;
  212. }
  213. self->data_to_recv -= sz;
  214. buf_sz += sz;
  215. }
  216. if (self->hdr.type == PUT_FILE) {
  217. DEBUG_printf("webrepl: Writing %lu bytes to file\n", buf_sz);
  218. int err;
  219. mp_uint_t res = mp_stream_write_exactly(self->cur_file, filebuf, buf_sz, &err);
  220. if (err != 0 || res != buf_sz) {
  221. assert(0);
  222. }
  223. } else if (self->hdr.type == GET_FILE) {
  224. assert(buf_sz == 1);
  225. assert(self->data_to_recv == 0);
  226. assert(filebuf[0] == 0);
  227. mp_uint_t out_sz = write_file_chunk(self);
  228. if (out_sz != 0) {
  229. self->data_to_recv = 1;
  230. }
  231. }
  232. if (self->data_to_recv == 0) {
  233. mp_stream_close(self->cur_file);
  234. self->hdr_to_recv = sizeof(struct webrepl_file);
  235. DEBUG_printf("webrepl: Finished file operation %d\n", self->hdr.type);
  236. write_webrepl_resp(self->sock, 0);
  237. }
  238. #ifdef MICROPY_PY_WEBREPL_DELAY
  239. // Some platforms may have broken drivers and easily gets
  240. // overloaded with modest traffic WebREPL file transfers
  241. // generate. The basic workaround is a crude rate control
  242. // done in such way.
  243. mp_hal_delay_ms(MICROPY_PY_WEBREPL_DELAY);
  244. #endif
  245. }
  246. return -2;
  247. }
  248. STATIC mp_uint_t webrepl_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode) {
  249. mp_obj_webrepl_t *self = self_in;
  250. if (self->state == STATE_PASSWD) {
  251. // Don't forward output until passwd is entered
  252. return size;
  253. }
  254. const mp_stream_p_t *stream_p = mp_get_stream_raise(self->sock, MP_STREAM_OP_WRITE);
  255. return stream_p->write(self->sock, buf, size, errcode);
  256. }
  257. STATIC mp_obj_t webrepl_close(mp_obj_t self_in) {
  258. mp_obj_webrepl_t *self = MP_OBJ_TO_PTR(self_in);
  259. // TODO: This is a place to do cleanup
  260. return mp_stream_close(self->sock);
  261. }
  262. STATIC MP_DEFINE_CONST_FUN_OBJ_1(webrepl_close_obj, webrepl_close);
  263. STATIC mp_obj_t webrepl_set_password(mp_obj_t passwd_in) {
  264. size_t len;
  265. const char *passwd = mp_obj_str_get_data(passwd_in, &len);
  266. if (len > sizeof(webrepl_passwd) - 1) {
  267. mp_raise_ValueError(NULL);
  268. }
  269. strcpy(webrepl_passwd, passwd);
  270. return mp_const_none;
  271. }
  272. STATIC MP_DEFINE_CONST_FUN_OBJ_1(webrepl_set_password_obj, webrepl_set_password);
  273. STATIC const mp_rom_map_elem_t webrepl_locals_dict_table[] = {
  274. { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) },
  275. { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) },
  276. { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) },
  277. { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&webrepl_close_obj) },
  278. };
  279. STATIC MP_DEFINE_CONST_DICT(webrepl_locals_dict, webrepl_locals_dict_table);
  280. STATIC const mp_stream_p_t webrepl_stream_p = {
  281. .read = webrepl_read,
  282. .write = webrepl_write,
  283. };
  284. STATIC const mp_obj_type_t webrepl_type = {
  285. { &mp_type_type },
  286. .name = MP_QSTR__webrepl,
  287. .make_new = webrepl_make_new,
  288. .protocol = &webrepl_stream_p,
  289. .locals_dict = (mp_obj_dict_t*)&webrepl_locals_dict,
  290. };
  291. STATIC const mp_rom_map_elem_t webrepl_module_globals_table[] = {
  292. { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR__webrepl) },
  293. { MP_ROM_QSTR(MP_QSTR__webrepl), MP_ROM_PTR(&webrepl_type) },
  294. { MP_ROM_QSTR(MP_QSTR_password), MP_ROM_PTR(&webrepl_set_password_obj) },
  295. };
  296. STATIC MP_DEFINE_CONST_DICT(webrepl_module_globals, webrepl_module_globals_table);
  297. const mp_obj_module_t mp_module_webrepl = {
  298. .base = { &mp_type_module },
  299. .globals = (mp_obj_dict_t*)&webrepl_module_globals,
  300. };
  301. #endif // MICROPY_PY_WEBREPL