modwebrepl.c 12 KB

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