modwebrepl.c 12 KB

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