net.c 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678
  1. /* vim: tabstop=4 shiftwidth=4 noexpandtab
  2. * This file is part of ToaruOS and is released under the terms
  3. * of the NCSA / University of Illinois License - see LICENSE.md
  4. * Copyright (C) 2014-2018 K. Lange
  5. */
  6. #include <kernel/module.h>
  7. #include <kernel/logging.h>
  8. #include <kernel/ipv4.h>
  9. #include <kernel/printf.h>
  10. #include <kernel/tokenize.h>
  11. #include <kernel/mod/net.h>
  12. #include <kernel/mod/procfs.h>
  13. #include <toaru/list.h>
  14. #include <toaru/hashmap.h>
  15. static hashmap_t * dns_cache;
  16. static list_t * dns_waiters = NULL;
  17. static uint32_t _dns_server;
  18. static hashmap_t *_tcp_sockets = NULL;
  19. static hashmap_t *_udp_sockets = NULL;
  20. static void parse_dns_response(fs_node_t * tty, void * last_packet);
  21. static size_t write_dns_packet(uint8_t * buffer, size_t queries_len, uint8_t * queries);
  22. size_t write_dhcp_request(uint8_t * buffer, uint8_t * ip);
  23. static size_t write_arp_request(uint8_t * buffer, uint32_t ip);
  24. static uint8_t _gateway[6] = {255,255,255,255,255,255};
  25. static struct netif _netif = {0};
  26. static int tasklet_pid = 0;
  27. uint32_t get_primary_dns(void);
  28. static uint32_t netif_func(fs_node_t *node, uint64_t offset, uint32_t size, uint8_t *buffer) {
  29. char * buf = malloc(4096);
  30. struct netif * netif = &_netif;
  31. char ip[16];
  32. ip_ntoa(netif->source, ip);
  33. char dns[16];
  34. ip_ntoa(get_primary_dns(), dns);
  35. char gw[16];
  36. ip_ntoa(netif->gateway, gw);
  37. if (netif->hwaddr[0] == 0 &&
  38. netif->hwaddr[1] == 0 &&
  39. netif->hwaddr[2] == 0 &&
  40. netif->hwaddr[3] == 0 &&
  41. netif->hwaddr[4] == 0 &&
  42. netif->hwaddr[5] == 0) {
  43. sprintf(buf, "no network\n");
  44. } else {
  45. sprintf(buf,
  46. "ip:\t%s\n"
  47. "mac:\t%2x:%2x:%2x:%2x:%2x:%2x\n"
  48. "device:\t%s\n"
  49. "dns:\t%s\n"
  50. "gateway:\t%s\n"
  51. ,
  52. ip,
  53. netif->hwaddr[0], netif->hwaddr[1], netif->hwaddr[2], netif->hwaddr[3], netif->hwaddr[4], netif->hwaddr[5],
  54. netif->driver,
  55. dns,
  56. gw
  57. );
  58. }
  59. size_t _bsize = strlen(buf);
  60. if (offset > _bsize) {
  61. free(buf);
  62. return 0;
  63. }
  64. if (size > _bsize - offset) size = _bsize - offset;
  65. memcpy(buffer, buf + offset, size);
  66. free(buf);
  67. return size;
  68. }
  69. static struct procfs_entry netif_entry = {
  70. 0, /* filled by install */
  71. "netif",
  72. netif_func,
  73. };
  74. void init_netif_funcs(get_mac_func mac_func, get_packet_func get_func, send_packet_func send_func, char * device) {
  75. _netif.get_mac = mac_func;
  76. _netif.get_packet = get_func;
  77. _netif.send_packet = send_func;
  78. _netif.driver = device;
  79. memcpy(_netif.hwaddr, _netif.get_mac(), sizeof(_netif.hwaddr));
  80. if (!netif_entry.id) {
  81. int (*procfs_install)(struct procfs_entry *) = (int (*)(struct procfs_entry *))(uintptr_t)hashmap_get(modules_get_symbols(),"procfs_install");
  82. if (procfs_install) {
  83. procfs_install(&netif_entry);
  84. }
  85. }
  86. if (!tasklet_pid) {
  87. tasklet_pid = create_kernel_tasklet(net_handler, "[net]", NULL);
  88. debug_print(NOTICE, "Network worker tasklet started with pid %d", tasklet_pid);
  89. }
  90. }
  91. struct netif * get_default_network_interface(void) {
  92. return &_netif;
  93. }
  94. uint32_t get_primary_dns(void) {
  95. return _dns_server;
  96. }
  97. uint32_t ip_aton(const char * in) {
  98. char ip[16];
  99. char * c = ip;
  100. uint32_t out[4];
  101. char * i;
  102. memcpy(ip, in, strlen(in) < 15 ? strlen(in) + 1 : 15);
  103. ip[15] = '\0';
  104. i = (char *)lfind(c, '.');
  105. *i = '\0';
  106. out[0] = atoi(c);
  107. c += strlen(c) + 1;
  108. i = (char *)lfind(c, '.');
  109. *i = '\0';
  110. out[1] = atoi(c);
  111. c += strlen(c) + 1;
  112. i = (char *)lfind(c, '.');
  113. *i = '\0';
  114. out[2] = atoi(c);
  115. c += strlen(c) + 1;
  116. out[3] = atoi(c);
  117. return ((out[0] << 24) | (out[1] << 16) | (out[2] << 8) | (out[3]));
  118. }
  119. void ip_ntoa(uint32_t src_addr, char * out) {
  120. sprintf(out, "%d.%d.%d.%d",
  121. (src_addr & 0xFF000000) >> 24,
  122. (src_addr & 0xFF0000) >> 16,
  123. (src_addr & 0xFF00) >> 8,
  124. (src_addr & 0xFF));
  125. }
  126. uint16_t calculate_ipv4_checksum(struct ipv4_packet * p) {
  127. uint32_t sum = 0;
  128. uint16_t * s = (uint16_t *)p;
  129. /* TODO: Checksums for options? */
  130. for (int i = 0; i < 10; ++i) {
  131. sum += ntohs(s[i]);
  132. }
  133. if (sum > 0xFFFF) {
  134. sum = (sum >> 16) + (sum & 0xFFFF);
  135. }
  136. return ~(sum & 0xFFFF) & 0xFFFF;
  137. }
  138. uint16_t calculate_tcp_checksum(struct tcp_check_header * p, struct tcp_header * h, void * d, size_t payload_size) {
  139. uint32_t sum = 0;
  140. uint16_t * s = (uint16_t *)p;
  141. /* TODO: Checksums for options? */
  142. for (int i = 0; i < 6; ++i) {
  143. sum += ntohs(s[i]);
  144. if (sum > 0xFFFF) {
  145. sum = (sum >> 16) + (sum & 0xFFFF);
  146. }
  147. }
  148. s = (uint16_t *)h;
  149. for (int i = 0; i < 10; ++i) {
  150. sum += ntohs(s[i]);
  151. if (sum > 0xFFFF) {
  152. sum = (sum >> 16) + (sum & 0xFFFF);
  153. }
  154. }
  155. uint16_t d_words = payload_size / 2;
  156. s = (uint16_t *)d;
  157. for (unsigned int i = 0; i < d_words; ++i) {
  158. sum += ntohs(s[i]);
  159. if (sum > 0xFFFF) {
  160. sum = (sum >> 16) + (sum & 0xFFFF);
  161. }
  162. }
  163. if (d_words * 2 != payload_size) {
  164. uint8_t * t = (uint8_t *)d;
  165. uint8_t tmp[2];
  166. tmp[0] = t[d_words * sizeof(uint16_t)];
  167. tmp[1] = 0;
  168. uint16_t * f = (uint16_t *)tmp;
  169. sum += ntohs(f[0]);
  170. if (sum > 0xFFFF) {
  171. sum = (sum >> 16) + (sum & 0xFFFF);
  172. }
  173. }
  174. return ~(sum & 0xFFFF) & 0xFFFF;
  175. }
  176. static struct dirent * readdir_netfs(fs_node_t *node, uint32_t index) {
  177. if (index == 0) {
  178. struct dirent * out = malloc(sizeof(struct dirent));
  179. memset(out, 0x00, sizeof(struct dirent));
  180. out->ino = 0;
  181. strcpy(out->name, ".");
  182. return out;
  183. }
  184. if (index == 1) {
  185. struct dirent * out = malloc(sizeof(struct dirent));
  186. memset(out, 0x00, sizeof(struct dirent));
  187. out->ino = 0;
  188. strcpy(out->name, "..");
  189. return out;
  190. }
  191. index -= 2;
  192. return NULL;
  193. }
  194. size_t dns_name_to_normal_name(struct dns_packet * dns, size_t offset, char * buf) {
  195. uint8_t * bytes = (uint8_t *)dns;
  196. size_t i = 0;
  197. while (1) {
  198. uint8_t c = bytes[offset];
  199. if (c == 0) break;
  200. if (c >= 0xC0) {
  201. uint16_t ref = ((c - 0xC0) << 8) + bytes[offset+1];
  202. i += dns_name_to_normal_name(dns, ref, &buf[i]);
  203. return i;
  204. }
  205. offset++;
  206. for (size_t j = 0; j < c; j++) {
  207. buf[i] = bytes[offset];
  208. i++;
  209. offset++;
  210. }
  211. buf[i] = '.';
  212. i++;
  213. buf[i] = '\0';
  214. }
  215. if (i == 0) return 0;
  216. buf[i-1] = '\0';
  217. return i-1;
  218. }
  219. size_t get_dns_name(char * buffer, struct dns_packet * dns, size_t offset) {
  220. uint8_t * bytes = (uint8_t *)dns;
  221. while (1) {
  222. uint8_t c = bytes[offset];
  223. if (c == 0) {
  224. offset++;
  225. return offset;
  226. } else if (c >= 0xC0) {
  227. uint16_t ref = ((c - 0xC0) << 8) + bytes[offset+1];
  228. get_dns_name(buffer, dns, ref);
  229. offset++;
  230. offset++;
  231. return offset;
  232. } else {
  233. for (int i = 0; i < c; ++i) {
  234. *buffer = bytes[offset+1+i];
  235. buffer++;
  236. *buffer = '\0';
  237. }
  238. *buffer = '.';
  239. buffer++;
  240. *buffer = '\0';
  241. offset += c + 1;
  242. }
  243. }
  244. }
  245. size_t print_dns_name(fs_node_t * tty, struct dns_packet * dns, size_t offset) {
  246. uint8_t * bytes = (uint8_t *)dns;
  247. while (1) {
  248. uint8_t c = bytes[offset];
  249. if (c == 0) {
  250. offset++;
  251. return offset;
  252. } else if (c >= 0xC0) {
  253. uint16_t ref = ((c - 0xC0) << 8) + bytes[offset+1];
  254. print_dns_name(tty, dns, ref);
  255. offset++;
  256. offset++;
  257. return offset;
  258. } else {
  259. for (int i = 0; i < c; ++i) {
  260. fprintf(tty,"%c",bytes[offset+1+i]);
  261. }
  262. fprintf(tty,".");
  263. offset += c + 1;
  264. }
  265. }
  266. }
  267. static int is_ip(char * name) {
  268. unsigned int dot_count = 0;
  269. unsigned int t = 0;
  270. for (char * c = name; *c != '\0'; ++c) {
  271. if ((*c < '0' || *c > '9') && (*c != '.')) return 0;
  272. if (*c == '.') {
  273. if (t > 255) return 0;
  274. dot_count++;
  275. t = 0;
  276. } else {
  277. t *= 10;
  278. t += *c - '0';
  279. }
  280. if (dot_count == 4) return 0;
  281. }
  282. if (dot_count != 3) return 0;
  283. return 1;
  284. }
  285. static char read_a_byte(struct socket * stream, int * status) {
  286. static char * foo = NULL;
  287. static char * read_ptr = NULL;
  288. static int have_bytes = 0;
  289. if (!foo) foo = malloc(4096);
  290. while (!have_bytes) {
  291. memset(foo, 0x00, 4096);
  292. have_bytes = net_recv(stream, (uint8_t *)foo, 4096);
  293. if (have_bytes == 0) {
  294. *status = 1;
  295. return 0;
  296. }
  297. debug_print(WARNING, "Received %d bytes...", have_bytes);
  298. read_ptr = foo;
  299. }
  300. char ret = *read_ptr;
  301. have_bytes -= 1;
  302. read_ptr++;
  303. return ret;
  304. }
  305. static char * fgets(char * buf, int size, struct socket * stream) {
  306. char * x = buf;
  307. int collected = 0;
  308. while (collected < size) {
  309. int status = 0;
  310. *x = read_a_byte(stream, &status);
  311. if (status == 1) {
  312. return buf;
  313. }
  314. collected++;
  315. if (*x == '\n') break;
  316. x++;
  317. }
  318. x++;
  319. *x = '\0';
  320. return buf;
  321. }
  322. static void socket_alert_waiters(struct socket * sock) {
  323. if (sock->alert_waiters) {
  324. while (sock->alert_waiters->head) {
  325. node_t * node = list_dequeue(sock->alert_waiters);
  326. process_t * p = node->value;
  327. process_alert_node(p, sock);
  328. free(node);
  329. }
  330. }
  331. }
  332. static int socket_check(fs_node_t * node) {
  333. struct socket * sock = node->device;
  334. if (sock->bytes_available) {
  335. return 0;
  336. }
  337. if (sock->packet_queue->length > 0) {
  338. return 0;
  339. }
  340. return 1;
  341. }
  342. static int socket_wait(fs_node_t * node, void * process) {
  343. struct socket * sock = node->device;
  344. if (!list_find(sock->alert_waiters, process)) {
  345. list_insert(sock->alert_waiters, process);
  346. }
  347. list_insert(((process_t *)process)->node_waits, sock);
  348. return 0;
  349. }
  350. static uint32_t socket_read(fs_node_t * node, uint64_t offset, uint32_t size, uint8_t * buffer) {
  351. /* Sleep until we have something to receive */
  352. #if 0
  353. fgets((char *)buffer, size, node->device);
  354. return strlen((char *)buffer);
  355. #else
  356. return net_recv(node->device, buffer, size);
  357. #endif
  358. }
  359. static uint32_t socket_write(fs_node_t * node, uint64_t offset, uint32_t size, uint8_t * buffer) {
  360. /* Add the packet to the appropriate interface queue and send it off. */
  361. net_send((struct socket *)node->device, buffer, size, 0);
  362. return size;
  363. }
  364. uint16_t next_ephemeral_port(void) {
  365. static uint16_t next = 49152;
  366. if (next == 0) {
  367. assert(0 && "All out of ephemeral ports, halting this time.");
  368. }
  369. uint16_t out = next;
  370. next++;
  371. if (next == 0) {
  372. debug_print(WARNING, "Ran out of ephemeral ports - next time I'm going to bail.");
  373. debug_print(WARNING, "You really need to implement a bitmap here.");
  374. }
  375. return out;
  376. }
  377. fs_node_t * socket_ipv4_tcp_create(uint32_t dest, uint16_t target_port, uint16_t source_port) {
  378. /* Okay, first step is to get us added to the table so we can receive syns. */
  379. return NULL;
  380. }
  381. static int gethost(char * name, uint32_t * ip) {
  382. if (is_ip(name)) {
  383. debug_print(WARNING, " IP: %x", ip_aton(name));
  384. *ip = ip_aton(name);
  385. return 0;
  386. } else {
  387. if (hashmap_has(dns_cache, name)) {
  388. *ip = ip_aton(hashmap_get(dns_cache, name));
  389. debug_print(WARNING, " In Cache: %s → %x", name, ip);
  390. return 0;
  391. } else {
  392. debug_print(WARNING, " Not in cache: %s", name);
  393. debug_print(WARNING, " Still needs look up.");
  394. char * xname = strdup(name);
  395. char * queries = malloc(1024);
  396. queries[0] = '\0';
  397. char * subs[10]; /* 10 is probably not the best number. */
  398. int argc = tokenize(xname, ".", subs);
  399. int n = 0;
  400. for (int i = 0; i < argc; ++i) {
  401. debug_print(WARNING, "dns [%d]%s", strlen(subs[i]), subs[i]);
  402. sprintf(&queries[n], "%c%s", strlen(subs[i]), subs[i]);
  403. n += strlen(&queries[n]);
  404. }
  405. int c = strlen(queries) + 1;
  406. queries[c+0] = 0x00;
  407. queries[c+1] = 0x01; /* A */
  408. queries[c+2] = 0x00;
  409. queries[c+3] = 0x01; /* IN */
  410. free(xname);
  411. debug_print(WARNING, "Querying...");
  412. void * tmp = malloc(1024);
  413. size_t packet_size = write_dns_packet(tmp, c + 4, (uint8_t *)queries);
  414. free(queries);
  415. _netif.send_packet(tmp, packet_size);
  416. free(tmp);
  417. /* wait for response */
  418. if (current_process->id != tasklet_pid) {
  419. sleep_on(dns_waiters);
  420. }
  421. if (hashmap_has(dns_cache, name)) {
  422. *ip = ip_aton(hashmap_get(dns_cache, name));
  423. debug_print(WARNING, " Now in cache: %s → %x", name, ip);
  424. return 0;
  425. } else {
  426. if (current_process->id == tasklet_pid) {
  427. debug_print(WARNING, "Query hasn't returned yet, but we're in the network thread, so we need to yield.");
  428. return 2;
  429. }
  430. gethost(name,ip);
  431. return 1;
  432. }
  433. }
  434. }
  435. }
  436. static int net_send_tcp(struct socket *socket, uint16_t flags, uint8_t * payload, uint32_t payload_size);
  437. static void socket_close(fs_node_t * node) {
  438. debug_print(WARNING, "Closing socket");
  439. struct socket * sock = node->device;
  440. if (sock->status == 1) return; /* already closed */
  441. net_send_tcp(sock, TCP_FLAGS_ACK | TCP_FLAGS_FIN, NULL, 0);
  442. sock->status = 2;
  443. }
  444. /* TODO: socket_close - TCP close; UDP... just clean us up */
  445. /* TODO: socket_open - idk, whatever */
  446. static fs_node_t * finddir_netfs(fs_node_t * node, char * name) {
  447. /* Should essentially find anything. */
  448. debug_print(WARNING, "Need to look up domain or check if is IP: %s", name);
  449. /* Block until lookup is complete */
  450. int port = 80;
  451. char * colon;
  452. if ((colon = strstr(name, ":"))) {
  453. /* Port numbers */
  454. *colon = '\0';
  455. colon++;
  456. port = atoi(colon);
  457. }
  458. uint32_t ip = 0;
  459. if (gethost(name, &ip)) return NULL;
  460. fs_node_t * fnode = malloc(sizeof(fs_node_t));
  461. memset(fnode, 0x00, sizeof(fs_node_t));
  462. fnode->inode = 0;
  463. strcpy(fnode->name, name);
  464. fnode->mask = 0666;
  465. fnode->flags = FS_CHARDEVICE;
  466. fnode->read = socket_read;
  467. fnode->write = socket_write;
  468. fnode->close = socket_close;
  469. fnode->device = (void *)net_open(SOCK_STREAM);
  470. fnode->selectcheck = socket_check;
  471. fnode->selectwait = socket_wait;
  472. net_connect((struct socket *)fnode->device, ip, port);
  473. return fnode;
  474. }
  475. static int ioctl_netfs(fs_node_t * node, int request, void * argp) {
  476. switch (request) {
  477. case 0x5000: {
  478. /* */
  479. debug_print(INFO, "DNS query from userspace");
  480. void ** x = (void **)argp;
  481. char * host = x[0];
  482. uint32_t * ip = x[1];
  483. /* TODO: Validate */
  484. return gethost(host, ip);
  485. }
  486. }
  487. return 0;
  488. }
  489. static size_t write_dns_packet(uint8_t * buffer, size_t queries_len, uint8_t * queries) {
  490. size_t offset = 0;
  491. size_t payload_size = sizeof(struct dns_packet) + queries_len;
  492. /* Then, let's write an ethernet frame */
  493. struct ethernet_packet eth_out = {
  494. .source = { _netif.hwaddr[0], _netif.hwaddr[1], _netif.hwaddr[2],
  495. _netif.hwaddr[3], _netif.hwaddr[4], _netif.hwaddr[5] },
  496. .destination = BROADCAST_MAC,
  497. .type = htons(0x0800),
  498. };
  499. memcpy(&buffer[offset], &eth_out, sizeof(struct ethernet_packet));
  500. offset += sizeof(struct ethernet_packet);
  501. /* Prepare the IPv4 header */
  502. uint16_t _length = htons(sizeof(struct ipv4_packet) + sizeof(struct udp_packet) + payload_size);
  503. uint16_t _ident = htons(1);
  504. struct ipv4_packet ipv4_out = {
  505. .version_ihl = ((0x4 << 4) | (0x5 << 0)), /* 4 = ipv4, 5 = no options */
  506. .dscp_ecn = 0, /* not setting either of those */
  507. .length = _length,
  508. .ident = _ident,
  509. .flags_fragment = 0,
  510. .ttl = 0x40,
  511. .protocol = IPV4_PROT_UDP,
  512. .checksum = 0, /* fill this in later */
  513. .source = htonl(_netif.source),
  514. .destination = htonl(_dns_server),
  515. };
  516. uint16_t checksum = calculate_ipv4_checksum(&ipv4_out);
  517. ipv4_out.checksum = htons(checksum);
  518. memcpy(&buffer[offset], &ipv4_out, sizeof(struct ipv4_packet));
  519. offset += sizeof(struct ipv4_packet);
  520. uint16_t _udp_source = htons(50053); /* Use an ephemeral port */
  521. uint16_t _udp_destination = htons(53);
  522. uint16_t _udp_length = htons(sizeof(struct udp_packet) + payload_size);
  523. /* Now let's build a UDP packet */
  524. struct udp_packet udp_out = {
  525. .source_port = _udp_source,
  526. .destination_port = _udp_destination,
  527. .length = _udp_length,
  528. .checksum = 0,
  529. };
  530. /* XXX calculate checksum here */
  531. memcpy(&buffer[offset], &udp_out, sizeof(struct udp_packet));
  532. offset += sizeof(struct udp_packet);
  533. /* DNS header */
  534. struct dns_packet dns_out = {
  535. .qid = htons(0),
  536. .flags = htons(0x0100), /* Standard query */
  537. .questions = htons(1), /* 1 question */
  538. .answers = htons(0),
  539. .authorities = htons(0),
  540. .additional = htons(0),
  541. };
  542. memcpy(&buffer[offset], &dns_out, sizeof(struct dns_packet));
  543. offset += sizeof(struct dns_packet);
  544. memcpy(&buffer[offset], queries, queries_len);
  545. offset += queries_len;
  546. return offset;
  547. }
  548. static int net_send_ether(struct socket *socket, struct netif* netif, uint16_t ether_type, void* payload, uint32_t payload_size) {
  549. struct ethernet_packet *eth = malloc(sizeof(struct ethernet_packet) + payload_size);
  550. memcpy(eth->source, netif->hwaddr, sizeof(eth->source));
  551. //memset(eth->destination, 0xFF, sizeof(eth->destination));
  552. memcpy(eth->destination, _gateway, sizeof(_gateway));
  553. eth->type = htons(ether_type);
  554. if (payload_size) {
  555. memcpy(eth->payload, payload, payload_size);
  556. }
  557. netif->send_packet((uint8_t*)eth, sizeof(struct ethernet_packet) + payload_size);
  558. free(eth);
  559. return 1; // yolo
  560. }
  561. static int net_send_ip(struct socket *socket, int proto, void* payload, uint32_t payload_size) {
  562. struct ipv4_packet *ipv4 = malloc(sizeof(struct ipv4_packet) + payload_size);
  563. uint16_t _length = htons(sizeof(struct ipv4_packet) + payload_size);
  564. uint16_t _ident = htons(1);
  565. ipv4->version_ihl = ((0x4 << 4) | (0x5 << 0)); /* 4 = ipv4, 5 = no options */
  566. ipv4->dscp_ecn = 0; /* not setting either of those */
  567. ipv4->length = _length;
  568. ipv4->ident = _ident;
  569. ipv4->flags_fragment = 0;
  570. ipv4->ttl = 0x40;
  571. ipv4->protocol = proto;
  572. ipv4->checksum = 0; // Fill in later */
  573. ipv4->source = htonl(_netif.source),
  574. ipv4->destination = htonl(socket->ip);
  575. uint16_t checksum = calculate_ipv4_checksum(ipv4);
  576. ipv4->checksum = htons(checksum);
  577. if (proto == IPV4_PROT_TCP) {
  578. // Need to calculate TCP checksum
  579. struct tcp_check_header check_hd = {
  580. .source = ipv4->source,
  581. .destination = ipv4->destination,
  582. .zeros = 0,
  583. .protocol = 6,
  584. .tcp_len = htons(payload_size),
  585. };
  586. // debug_print(WARNING, "net_send_ip: Payload size: %d\n", payload_size);
  587. struct tcp_header* tcp_hdr = (struct tcp_header*)payload;
  588. // debug_print(WARNING, "net_send_ip: Header len htons: %d\n", TCP_HEADER_LENGTH_FLIPPED(tcp_hdr));
  589. size_t orig_payload_size = payload_size - TCP_HEADER_LENGTH_FLIPPED(tcp_hdr);
  590. uint16_t chk = calculate_tcp_checksum(&check_hd, tcp_hdr, tcp_hdr->payload, orig_payload_size);
  591. tcp_hdr->checksum = htons(chk);
  592. }
  593. if (payload) {
  594. memcpy(ipv4->payload, payload, payload_size);
  595. free(payload);
  596. }
  597. // TODO: netif should not be a global thing. But the route should be looked up here and a netif object created/returned
  598. int out = net_send_ether(socket, &_netif, ETHERNET_TYPE_IPV4, ipv4, sizeof(struct ipv4_packet) + payload_size);
  599. free(ipv4);
  600. return out;
  601. }
  602. static int net_send_tcp(struct socket *socket, uint16_t flags, uint8_t * payload, uint32_t payload_size) {
  603. struct tcp_header *tcp = malloc(sizeof(struct tcp_header) + payload_size);
  604. tcp->source_port = htons(socket->port_recv);
  605. tcp->destination_port = htons(socket->port_dest);
  606. tcp->seq_number = htonl(socket->proto_sock.tcp_socket.seq_no);
  607. tcp->ack_number = flags & (TCP_FLAGS_ACK) ? htonl(socket->proto_sock.tcp_socket.ack_no) : 0;
  608. tcp->flags = htons(0x5000 ^ (flags & 0xFF));
  609. tcp->window_size = htons(1548-54);
  610. tcp->checksum = 0; // Fill in later
  611. tcp->urgent = 0;
  612. if ((flags & 0xff) == TCP_FLAGS_SYN) {
  613. // If only SYN set, expected ACK will be 1 despite no payload
  614. socket->proto_sock.tcp_socket.seq_no += 1;
  615. } else {
  616. socket->proto_sock.tcp_socket.seq_no += payload_size;
  617. }
  618. if (payload) {
  619. memcpy(tcp->payload, payload, payload_size);
  620. }
  621. return net_send_ip(socket, IPV4_PROT_TCP, tcp, sizeof(struct tcp_header) + payload_size);
  622. }
  623. struct socket* net_open(uint32_t type) {
  624. // This is a socket() call
  625. struct socket *sock = malloc(sizeof(struct socket));
  626. memset(sock, 0, sizeof(struct socket));
  627. sock->sock_type = type;
  628. return sock;
  629. }
  630. int net_close(struct socket* socket) {
  631. // socket->is_connected;
  632. socket->status = 1; /* Disconnected */
  633. wakeup_queue(socket->packet_wait);
  634. socket_alert_waiters(socket);
  635. return 1;
  636. }
  637. int net_send(struct socket* socket, uint8_t* payload, size_t payload_size, int flags) {
  638. return net_send_tcp(socket, TCP_FLAGS_ACK | TCP_FLAGS_PSH, payload, payload_size);
  639. }
  640. size_t net_recv(struct socket* socket, uint8_t* buffer, size_t len) {
  641. tcpdata_t *tcpdata = NULL;
  642. node_t *node = NULL;
  643. debug_print(INFO, "0x%x [socket]", socket);
  644. size_t offset = 0;
  645. size_t size_to_read = 0;
  646. do {
  647. if (socket->bytes_available) {
  648. tcpdata = socket->current_packet;
  649. } else {
  650. spin_lock(socket->packet_queue_lock);
  651. do {
  652. if (socket->packet_queue->length > 0) {
  653. node = list_dequeue(socket->packet_queue);
  654. spin_unlock(socket->packet_queue_lock);
  655. break;
  656. } else {
  657. if (socket->status == 1) {
  658. spin_unlock(socket->packet_queue_lock);
  659. debug_print(WARNING, "Socket closed, done reading.");
  660. return 0;
  661. }
  662. spin_unlock(socket->packet_queue_lock);
  663. sleep_on(socket->packet_wait);
  664. spin_lock(socket->packet_queue_lock);
  665. }
  666. } while (1);
  667. tcpdata = node->value;
  668. socket->bytes_available = tcpdata->payload_size;
  669. socket->bytes_read = 0;
  670. free(node);
  671. }
  672. size_to_read = MIN(len, socket->bytes_available);
  673. if (tcpdata->payload != 0) {
  674. memcpy(buffer + offset, tcpdata->payload + socket->bytes_read, size_to_read);
  675. }
  676. offset += size_to_read;
  677. if (size_to_read < socket->bytes_available) {
  678. socket->bytes_available -= size_to_read;
  679. socket->bytes_read += size_to_read;
  680. socket->current_packet = tcpdata;
  681. } else {
  682. socket->bytes_available = 0;
  683. socket->current_packet = NULL;
  684. free(tcpdata->payload);
  685. free(tcpdata);
  686. }
  687. } while (!size_to_read);
  688. return size_to_read;
  689. }
  690. static void net_handle_tcp(struct tcp_header * tcp, size_t length) {
  691. size_t data_length = length - TCP_HEADER_LENGTH_FLIPPED(tcp);
  692. /* Find socket */
  693. if (hashmap_has(_tcp_sockets, (void *)ntohs(tcp->destination_port))) {
  694. struct socket *socket = hashmap_get(_tcp_sockets, (void *)ntohs(tcp->destination_port));
  695. if (socket->status == 2) {
  696. debug_print(WARNING, "Received packet while connection is in 'closing' statuus");
  697. }
  698. if (socket->status == 1) {
  699. if ((htons(tcp->flags) & TCP_FLAGS_FIN)) {
  700. debug_print(WARNING, "TCP close sequence continues");
  701. return;
  702. }
  703. if ((htons(tcp->flags) & TCP_FLAGS_ACK)) {
  704. debug_print(WARNING, "TCP close sequence continues");
  705. return;
  706. }
  707. debug_print(ERROR, "Socket is closed? Should send FIN. socket=0x%x flags=0x%x", socket, tcp->flags);
  708. net_send_tcp(socket, TCP_FLAGS_FIN | TCP_FLAGS_ACK, NULL, 0);
  709. return;
  710. }
  711. if (socket->proto_sock.tcp_socket.seq_no != ntohl(tcp->ack_number)) {
  712. // Drop packet
  713. debug_print(WARNING, "Dropping packet. Expected ack: %d | Got ack: %d",
  714. socket->proto_sock.tcp_socket.seq_no, ntohl(tcp->ack_number));
  715. return;
  716. }
  717. if ((htons(tcp->flags) & TCP_FLAGS_SYN) && (htons(tcp->flags) & TCP_FLAGS_ACK)) {
  718. socket->proto_sock.tcp_socket.ack_no = ntohl(tcp->seq_number) + data_length + 1;
  719. net_send_tcp(socket, TCP_FLAGS_ACK, NULL, 0);
  720. wakeup_queue(socket->proto_sock.tcp_socket.is_connected);
  721. } else if (htons(tcp->flags) & TCP_FLAGS_RES) {
  722. /* Reset doesn't necessarily mean close. */
  723. debug_print(WARNING, "net_handle_tcp: Received RST - socket closing");
  724. net_close(socket);
  725. return;
  726. } else {
  727. // Store a copy of the layer 5 data for a userspace recv() call
  728. tcpdata_t *tcpdata = malloc(sizeof(tcpdata_t));
  729. tcpdata->payload_size = length - TCP_HEADER_LENGTH_FLIPPED(tcp);
  730. if (tcpdata->payload_size == 0) {
  731. if (htons(tcp->flags) & TCP_FLAGS_FIN) {
  732. /* We should make sure we finish sending before closing. */
  733. debug_print(WARNING, "net_handle_tcp: Received FIN - socket closing with SYNACK");
  734. socket->proto_sock.tcp_socket.ack_no = ntohl(tcp->seq_number) + data_length + 1;
  735. net_send_tcp(socket, TCP_FLAGS_ACK | TCP_FLAGS_FIN, NULL, 0);
  736. wakeup_queue(socket->proto_sock.tcp_socket.is_connected);
  737. net_close(socket);
  738. }
  739. free(tcpdata);
  740. return;
  741. }
  742. // debug_print(WARNING, "net_handle_tcp: payload length: %d\n", length);
  743. // debug_print(WARNING, "net_handle_tcp: flipped tcp flags hdr len: %d\n", TCP_HEADER_LENGTH_FLIPPED(tcp));
  744. // debug_print(WARNING, "net_handle_tcp: tcpdata->payload_size: %d\n", tcpdata->payload_size);
  745. if (tcpdata->payload_size > 0) {
  746. tcpdata->payload = malloc(tcpdata->payload_size);
  747. memcpy(tcpdata->payload, tcp->payload, tcpdata->payload_size);
  748. } else {
  749. tcpdata->payload = NULL;
  750. }
  751. socket->proto_sock.tcp_socket.ack_no = ntohl(tcp->seq_number) + data_length;
  752. if ((htons(tcp->flags) & TCP_FLAGS_SYN) && (htons(tcp->flags) & TCP_FLAGS_ACK) && data_length == 0) {
  753. socket->proto_sock.tcp_socket.ack_no += 1;
  754. }
  755. socket->proto_sock.tcp_socket.ack_no = ntohl(tcp->seq_number) + tcpdata->payload_size;
  756. spin_lock(socket->packet_queue_lock);
  757. list_insert(socket->packet_queue, tcpdata);
  758. spin_unlock(socket->packet_queue_lock);
  759. // Send acknowledgement of receiving data
  760. net_send_tcp(socket, TCP_FLAGS_ACK, NULL, 0);
  761. wakeup_queue(socket->packet_wait);
  762. socket_alert_waiters(socket);
  763. if (htons(tcp->flags) & TCP_FLAGS_FIN) {
  764. /* We should make sure we finish sending before closing. */
  765. debug_print(WARNING, "net_handle_tcp: Received FIN - socket closing with SYNACK");
  766. socket->proto_sock.tcp_socket.ack_no = ntohl(tcp->seq_number) + data_length + 1;
  767. net_send_tcp(socket, TCP_FLAGS_ACK | TCP_FLAGS_FIN, NULL, 0);
  768. wakeup_queue(socket->proto_sock.tcp_socket.is_connected);
  769. net_close(socket);
  770. }
  771. }
  772. } else {
  773. debug_print(WARNING, "net_handle_tcp: Received packet not associated with a socket!");
  774. }
  775. }
  776. static void net_handle_udp(struct udp_packet * udp, size_t length) {
  777. // size_t data_length = length - sizeof(struct tcp_header);
  778. debug_print(WARNING, "UDP response!");
  779. /* Short-circuit DNS */
  780. if (ntohs(udp->source_port) == 53) {
  781. debug_print(WARNING, "UDP response to DNS query!");
  782. parse_dns_response(debug_file, udp);
  783. return;
  784. }
  785. if (ntohs(udp->source_port) == 67) {
  786. debug_print(WARNING, "UDP response to DHCP!");
  787. {
  788. void * tmp = malloc(1024);
  789. size_t packet_size = write_arp_request(tmp, _netif.gateway);
  790. _netif.send_packet(tmp, packet_size);
  791. free(tmp);
  792. }
  793. return;
  794. }
  795. /* Find socket */
  796. if (hashmap_has(_udp_sockets, (void *)ntohs(udp->source_port))) {
  797. /* Do the thing */
  798. } else {
  799. /* ??? */
  800. }
  801. }
  802. static void net_handle_ipv4(struct ipv4_packet * ipv4) {
  803. debug_print(INFO, "net_handle_ipv4: ENTER");
  804. switch (ipv4->protocol) {
  805. case IPV4_PROT_TCP:
  806. net_handle_tcp((struct tcp_header *)ipv4->payload, ntohs(ipv4->length) - sizeof(struct ipv4_packet));
  807. break;
  808. case IPV4_PROT_UDP:
  809. net_handle_udp((struct udp_packet *)ipv4->payload, ntohs(ipv4->length) - sizeof(struct ipv4_packet));
  810. break;
  811. default:
  812. /* XXX */
  813. break;
  814. }
  815. }
  816. static struct ethernet_packet* net_receive(void) {
  817. struct ethernet_packet *eth = _netif.get_packet();
  818. return eth;
  819. }
  820. int net_connect(struct socket* socket, uint32_t dest_ip, uint16_t dest_port) {
  821. if (socket->sock_type == SOCK_DGRAM) {
  822. // Can't connect UDP
  823. return -1;
  824. }
  825. memset(socket->mac, 0, sizeof(socket->mac)); // idk
  826. socket->port_recv = next_ephemeral_port();
  827. socket->proto_sock.tcp_socket.is_connected = list_create();
  828. socket->proto_sock.tcp_socket.seq_no = 0;
  829. socket->proto_sock.tcp_socket.ack_no = 0;
  830. socket->proto_sock.tcp_socket.status = 0;
  831. socket->packet_queue = list_create();
  832. socket->packet_wait = list_create();
  833. socket->alert_waiters = list_create();
  834. socket->ip = dest_ip; //ip_aton("10.255.50.206");
  835. socket->port_dest = dest_port; //12345;
  836. debug_print(WARNING, "net_connect: using ephemeral port: %d", (void*)socket->port_recv);
  837. hashmap_set(_tcp_sockets, (void*)socket->port_recv, socket);
  838. net_send_tcp(socket, TCP_FLAGS_SYN, NULL, 0);
  839. // debug_print(WARNING, "net_connect:sent tcp SYN: %d", ret);
  840. // Race condition here - if net_handle_tcp runs and connects before this sleep
  841. sleep_on(socket->proto_sock.tcp_socket.is_connected);
  842. return 1;
  843. }
  844. static void placeholder_dhcp(void) {
  845. debug_print(NOTICE, "Sending DHCP discover");
  846. void * tmp = malloc(1024);
  847. size_t packet_size = write_dhcp_packet(tmp);
  848. _netif.send_packet(tmp, packet_size);
  849. free(tmp);
  850. while (1) {
  851. struct ethernet_packet * eth = (struct ethernet_packet *)_netif.get_packet();
  852. uint16_t eth_type = ntohs(eth->type);
  853. debug_print(NOTICE, "Ethernet II, Src: (%2x:%2x:%2x:%2x:%2x:%2x), Dst: (%2x:%2x:%2x:%2x:%2x:%2x) [type=%4x])",
  854. eth->source[0], eth->source[1], eth->source[2],
  855. eth->source[3], eth->source[4], eth->source[5],
  856. eth->destination[0], eth->destination[1], eth->destination[2],
  857. eth->destination[3], eth->destination[4], eth->destination[5],
  858. eth_type);
  859. if (eth_type != 0x0800) {
  860. debug_print(WARNING, "ARP packet while waiting for DHCP...");
  861. free(eth);
  862. continue;
  863. }
  864. struct ipv4_packet * ipv4 = (struct ipv4_packet *)eth->payload;
  865. uint32_t src_addr = ntohl(ipv4->source);
  866. uint32_t dst_addr = ntohl(ipv4->destination);
  867. uint16_t length = ntohs(ipv4->length);
  868. char src_ip[16];
  869. char dst_ip[16];
  870. ip_ntoa(src_addr, src_ip);
  871. ip_ntoa(dst_addr, dst_ip);
  872. debug_print(NOTICE, "IP packet [%s → %s] length=%d bytes",
  873. src_ip, dst_ip, length);
  874. if (ipv4->protocol != IPV4_PROT_UDP) {
  875. debug_print(WARNING, "Protocol: %d", ipv4->protocol);
  876. debug_print(WARNING, "Bad packet...");
  877. free(eth);
  878. continue;
  879. }
  880. struct udp_packet * udp = (struct udp_packet *)ipv4->payload;;
  881. uint16_t src_port = ntohs(udp->source_port);
  882. uint16_t dst_port = ntohs(udp->destination_port);
  883. uint16_t udp_len = ntohs(udp->length);
  884. debug_print(NOTICE, "UDP [%d → %d] length=%d bytes",
  885. src_port, dst_port, udp_len);
  886. if (dst_port != 68) {
  887. debug_print(WARNING, "Destination port: %d", dst_port);
  888. debug_print(WARNING, "Bad packet...");
  889. free(eth);
  890. continue;
  891. }
  892. struct dhcp_packet * dhcp = (struct dhcp_packet *)udp->payload;
  893. uint32_t yiaddr = ntohl(dhcp->yiaddr);
  894. char yiaddr_ip[16];
  895. ip_ntoa(yiaddr, yiaddr_ip);
  896. debug_print(NOTICE, "DHCP Offer: %s", yiaddr_ip);
  897. _netif.source = yiaddr;
  898. debug_print(NOTICE," Scanning offer for DNS servers...");
  899. size_t i = sizeof(struct dhcp_packet);
  900. size_t j = 0;
  901. while (i < length) {
  902. uint8_t type = dhcp->options[j];
  903. uint8_t len = dhcp->options[j+1];
  904. uint8_t * data = &dhcp->options[j+2];
  905. debug_print(NOTICE," type=%d, len=%d", type, len);
  906. if (type == 255) {
  907. break;
  908. } else if (type == 6) {
  909. /* DNS Server! */
  910. uint32_t dnsaddr = ntohl(*(uint32_t *)data);
  911. char ip[16];
  912. ip_ntoa(dnsaddr, ip);
  913. debug_print(NOTICE, "Found one: %s", ip);
  914. _dns_server = dnsaddr;
  915. } else if (type == 3) {
  916. _netif.gateway = ntohl(*(uint32_t *)data);
  917. }
  918. j += 2 + len;
  919. i += 2 + len;
  920. }
  921. debug_print(NOTICE, "Sending DHCP Request...");
  922. void * tmp = malloc(1024);
  923. size_t packet_size = write_dhcp_request(tmp, (uint8_t *)&dhcp->yiaddr);
  924. _netif.send_packet(tmp, packet_size);
  925. free(tmp);
  926. free(eth);
  927. break;
  928. }
  929. }
  930. struct arp {
  931. uint16_t htype;
  932. uint16_t proto;
  933. uint8_t hlen;
  934. uint8_t plen;
  935. uint16_t oper;
  936. uint8_t sender_ha[6];
  937. uint32_t sender_ip;
  938. uint8_t target_ha[6];
  939. uint32_t target_ip;
  940. uint8_t padding[18];
  941. } __attribute__((packed));
  942. static size_t write_arp_response(uint8_t * buffer, struct arp * source) {
  943. size_t offset = 0;
  944. /* Then, let's write an ethernet frame */
  945. struct ethernet_packet eth_out = {
  946. .source = { _netif.hwaddr[0], _netif.hwaddr[1], _netif.hwaddr[2],
  947. _netif.hwaddr[3], _netif.hwaddr[4], _netif.hwaddr[5] },
  948. .destination = BROADCAST_MAC,
  949. .type = htons(0x0806),
  950. };
  951. memcpy(&buffer[offset], &eth_out, sizeof(struct ethernet_packet));
  952. offset += sizeof(struct ethernet_packet);
  953. struct arp arp_out;
  954. arp_out.htype = source->htype;
  955. arp_out.proto = source->proto;
  956. arp_out.hlen = 6;
  957. arp_out.plen = 4;
  958. arp_out.oper = ntohs(2);
  959. arp_out.sender_ha[0] = _netif.hwaddr[0];
  960. arp_out.sender_ha[1] = _netif.hwaddr[1];
  961. arp_out.sender_ha[2] = _netif.hwaddr[2];
  962. arp_out.sender_ha[3] = _netif.hwaddr[3];
  963. arp_out.sender_ha[4] = _netif.hwaddr[4];
  964. arp_out.sender_ha[5] = _netif.hwaddr[5];
  965. arp_out.sender_ip = ntohl(_netif.source);
  966. arp_out.target_ha[0] = source->sender_ha[0];
  967. arp_out.target_ha[1] = source->sender_ha[1];
  968. arp_out.target_ha[2] = source->sender_ha[2];
  969. arp_out.target_ha[3] = source->sender_ha[3];
  970. arp_out.target_ha[4] = source->sender_ha[4];
  971. arp_out.target_ha[5] = source->sender_ha[5];
  972. arp_out.target_ip = source->sender_ip;
  973. memcpy(&buffer[offset], &arp_out, sizeof(struct arp));
  974. offset += sizeof(struct arp);
  975. return offset;
  976. }
  977. static size_t write_arp_request(uint8_t * buffer, uint32_t ip) {
  978. size_t offset = 0;
  979. debug_print(WARNING, "Request ARP from gateway address %x", ip);
  980. /* Then, let's write an ethernet frame */
  981. struct ethernet_packet eth_out = {
  982. .source = { _netif.hwaddr[0], _netif.hwaddr[1], _netif.hwaddr[2],
  983. _netif.hwaddr[3], _netif.hwaddr[4], _netif.hwaddr[5] },
  984. .destination = BROADCAST_MAC,
  985. .type = htons(0x0806),
  986. };
  987. memcpy(&buffer[offset], &eth_out, sizeof(struct ethernet_packet));
  988. offset += sizeof(struct ethernet_packet);
  989. struct arp arp_out;
  990. arp_out.htype = ntohs(1);
  991. debug_print(WARNING, "Request ARP from gateway address %x", ip);
  992. arp_out.proto = ntohs(0x0800);
  993. arp_out.hlen = 6;
  994. arp_out.plen = 4;
  995. arp_out.oper = ntohs(1);
  996. arp_out.sender_ha[0] = _netif.hwaddr[0];
  997. arp_out.sender_ha[1] = _netif.hwaddr[1];
  998. arp_out.sender_ha[2] = _netif.hwaddr[2];
  999. arp_out.sender_ha[3] = _netif.hwaddr[3];
  1000. arp_out.sender_ha[4] = _netif.hwaddr[4];
  1001. arp_out.sender_ha[5] = _netif.hwaddr[5];
  1002. arp_out.sender_ip = ntohl(_netif.source);
  1003. arp_out.target_ha[0] = 0;
  1004. arp_out.target_ha[1] = 0;
  1005. arp_out.target_ha[2] = 0;
  1006. arp_out.target_ha[3] = 0;
  1007. arp_out.target_ha[4] = 0;
  1008. arp_out.target_ha[5] = 0;
  1009. arp_out.target_ip = ntohl(ip);
  1010. memcpy(&buffer[offset], &arp_out, sizeof(struct arp));
  1011. offset += sizeof(struct arp);
  1012. return offset;
  1013. }
  1014. static void net_handle_arp(struct ethernet_packet * eth) {
  1015. debug_print(WARNING, "ARP packet...");
  1016. struct arp * arp = (struct arp *)&eth->payload;
  1017. char sender_ip[16];
  1018. char target_ip[16];
  1019. ip_ntoa(ntohl(arp->sender_ip), sender_ip);
  1020. ip_ntoa(ntohl(arp->target_ip), target_ip);
  1021. debug_print(WARNING, "%2x:%2x:%2x:%2x:%2x:%2x (%s) → %2x:%2x:%2x:%2x:%2x:%2x (%s) is",
  1022. arp->sender_ha[0],
  1023. arp->sender_ha[1],
  1024. arp->sender_ha[2],
  1025. arp->sender_ha[3],
  1026. arp->sender_ha[4],
  1027. arp->sender_ha[5],
  1028. sender_ip,
  1029. arp->target_ha[0],
  1030. arp->target_ha[1],
  1031. arp->target_ha[2],
  1032. arp->target_ha[3],
  1033. arp->target_ha[4],
  1034. arp->target_ha[5],
  1035. target_ip);
  1036. if (ntohs(arp->oper) == 1) {
  1037. if (ntohl(arp->target_ip) == _netif.source) {
  1038. debug_print(WARNING, "That's us!");
  1039. {
  1040. void * tmp = malloc(1024);
  1041. size_t packet_size = write_arp_response(tmp, arp);
  1042. _netif.send_packet(tmp, packet_size);
  1043. free(tmp);
  1044. }
  1045. }
  1046. } else {
  1047. if (ntohl(arp->target_ip) == _netif.source) {
  1048. debug_print(WARNING, "It's a response to our query!");
  1049. if (ntohl(arp->sender_ip) == _netif.gateway) {
  1050. _gateway[0] = arp->sender_ha[0];
  1051. _gateway[1] = arp->sender_ha[1];
  1052. _gateway[2] = arp->sender_ha[2];
  1053. _gateway[3] = arp->sender_ha[3];
  1054. _gateway[4] = arp->sender_ha[4];
  1055. _gateway[5] = arp->sender_ha[5];
  1056. }
  1057. } else {
  1058. debug_print(WARNING, "Response to someone else...\n");
  1059. }
  1060. }
  1061. }
  1062. void net_handler(void * data, char * name) {
  1063. /* Network Packet Handler*/
  1064. _netif.extra = NULL;
  1065. _dns_server = ip_aton("10.0.2.3");
  1066. placeholder_dhcp();
  1067. dns_waiters = list_create();
  1068. _tcp_sockets = hashmap_create_int(0xFF);
  1069. _udp_sockets = hashmap_create_int(0xFF);
  1070. while (1) {
  1071. struct ethernet_packet * eth = net_receive();
  1072. if (!eth) continue;
  1073. switch (ntohs(eth->type)) {
  1074. case ETHERNET_TYPE_IPV4:
  1075. net_handle_ipv4((struct ipv4_packet *)eth->payload);
  1076. break;
  1077. case ETHERNET_TYPE_ARP:
  1078. net_handle_arp(eth);
  1079. break;
  1080. }
  1081. free(eth);
  1082. }
  1083. }
  1084. size_t write_dhcp_packet(uint8_t * buffer) {
  1085. size_t offset = 0;
  1086. size_t payload_size = sizeof(struct dhcp_packet);
  1087. /* First, let's figure out how big this is supposed to be... */
  1088. uint8_t dhcp_options[] = {
  1089. 53, /* Message type */
  1090. 1, /* Length: 1 */
  1091. 1, /* Discover */
  1092. 55,
  1093. 2,
  1094. 3,
  1095. 6,
  1096. 255, /* END */
  1097. };
  1098. payload_size += sizeof(dhcp_options);
  1099. /* Then, let's write an ethernet frame */
  1100. struct ethernet_packet eth_out = {
  1101. .source = { _netif.hwaddr[0], _netif.hwaddr[1], _netif.hwaddr[2],
  1102. _netif.hwaddr[3], _netif.hwaddr[4], _netif.hwaddr[5] },
  1103. .destination = BROADCAST_MAC,
  1104. .type = htons(0x0800),
  1105. };
  1106. memcpy(&buffer[offset], &eth_out, sizeof(struct ethernet_packet));
  1107. offset += sizeof(struct ethernet_packet);
  1108. /* Prepare the IPv4 header */
  1109. uint16_t _length = htons(sizeof(struct ipv4_packet) + sizeof(struct udp_packet) + payload_size);
  1110. uint16_t _ident = htons(1);
  1111. struct ipv4_packet ipv4_out = {
  1112. .version_ihl = ((0x4 << 4) | (0x5 << 0)), /* 4 = ipv4, 5 = no options */
  1113. .dscp_ecn = 0, /* not setting either of those */
  1114. .length = _length,
  1115. .ident = _ident,
  1116. .flags_fragment = 0,
  1117. .ttl = 0x40,
  1118. .protocol = IPV4_PROT_UDP,
  1119. .checksum = 0, /* fill this in later */
  1120. .source = htonl(ip_aton("0.0.0.0")),
  1121. .destination = htonl(ip_aton("255.255.255.255")),
  1122. };
  1123. uint16_t checksum = calculate_ipv4_checksum(&ipv4_out);
  1124. ipv4_out.checksum = htons(checksum);
  1125. memcpy(&buffer[offset], &ipv4_out, sizeof(struct ipv4_packet));
  1126. offset += sizeof(struct ipv4_packet);
  1127. uint16_t _udp_source = htons(68);
  1128. uint16_t _udp_destination = htons(67);
  1129. uint16_t _udp_length = htons(sizeof(struct udp_packet) + payload_size);
  1130. /* Now let's build a UDP packet */
  1131. struct udp_packet udp_out = {
  1132. .source_port = _udp_source,
  1133. .destination_port = _udp_destination,
  1134. .length = _udp_length,
  1135. .checksum = 0,
  1136. };
  1137. /* XXX calculate checksum here */
  1138. memcpy(&buffer[offset], &udp_out, sizeof(struct udp_packet));
  1139. offset += sizeof(struct udp_packet);
  1140. /* BOOTP headers */
  1141. struct dhcp_packet bootp_out = {
  1142. .op = 1,
  1143. .htype = 1,
  1144. .hlen = 6, /* mac address... */
  1145. .hops = 0,
  1146. .xid = htonl(0x1337), /* transaction id */
  1147. .secs = 0,
  1148. .flags = 0,
  1149. .ciaddr = 0x000000,
  1150. .yiaddr = 0x000000,
  1151. .siaddr = 0x000000,
  1152. .giaddr = 0x000000,
  1153. .chaddr = { _netif.hwaddr[0], _netif.hwaddr[1], _netif.hwaddr[2],
  1154. _netif.hwaddr[3], _netif.hwaddr[4], _netif.hwaddr[5] },
  1155. .sname = {0},
  1156. .file = {0},
  1157. .magic = htonl(DHCP_MAGIC),
  1158. };
  1159. memcpy(&buffer[offset], &bootp_out, sizeof(struct dhcp_packet));
  1160. offset += sizeof(struct dhcp_packet);
  1161. memcpy(&buffer[offset], &dhcp_options, sizeof(dhcp_options));
  1162. offset += sizeof(dhcp_options);
  1163. return offset;
  1164. }
  1165. size_t write_dhcp_request(uint8_t * buffer, uint8_t * ip) {
  1166. size_t offset = 0;
  1167. size_t payload_size = sizeof(struct dhcp_packet);
  1168. /* First, let's figure out how big this is supposed to be... */
  1169. uint8_t dhcp_options[] = {
  1170. 53, /* Message type */
  1171. 1, /* Length: 1 */
  1172. 3, /* Request */
  1173. 50,
  1174. 4, /* requested ip */
  1175. ip[0],ip[1],ip[2],ip[3],
  1176. 55,
  1177. 2,
  1178. 3,
  1179. 6,
  1180. 255, /* END */
  1181. };
  1182. payload_size += sizeof(dhcp_options);
  1183. /* Then, let's write an ethernet frame */
  1184. struct ethernet_packet eth_out = {
  1185. .source = { _netif.hwaddr[0], _netif.hwaddr[1], _netif.hwaddr[2],
  1186. _netif.hwaddr[3], _netif.hwaddr[4], _netif.hwaddr[5] },
  1187. .destination = BROADCAST_MAC,
  1188. .type = htons(0x0800),
  1189. };
  1190. memcpy(&buffer[offset], &eth_out, sizeof(struct ethernet_packet));
  1191. offset += sizeof(struct ethernet_packet);
  1192. /* Prepare the IPv4 header */
  1193. uint16_t _length = htons(sizeof(struct ipv4_packet) + sizeof(struct udp_packet) + payload_size);
  1194. uint16_t _ident = htons(1);
  1195. struct ipv4_packet ipv4_out = {
  1196. .version_ihl = ((0x4 << 4) | (0x5 << 0)), /* 4 = ipv4, 5 = no options */
  1197. .dscp_ecn = 0, /* not setting either of those */
  1198. .length = _length,
  1199. .ident = _ident,
  1200. .flags_fragment = 0,
  1201. .ttl = 0x40,
  1202. .protocol = IPV4_PROT_UDP,
  1203. .checksum = 0, /* fill this in later */
  1204. .source = htonl(ip_aton("0.0.0.0")),
  1205. .destination = htonl(ip_aton("255.255.255.255")),
  1206. };
  1207. uint16_t checksum = calculate_ipv4_checksum(&ipv4_out);
  1208. ipv4_out.checksum = htons(checksum);
  1209. memcpy(&buffer[offset], &ipv4_out, sizeof(struct ipv4_packet));
  1210. offset += sizeof(struct ipv4_packet);
  1211. uint16_t _udp_source = htons(68);
  1212. uint16_t _udp_destination = htons(67);
  1213. uint16_t _udp_length = htons(sizeof(struct udp_packet) + payload_size);
  1214. /* Now let's build a UDP packet */
  1215. struct udp_packet udp_out = {
  1216. .source_port = _udp_source,
  1217. .destination_port = _udp_destination,
  1218. .length = _udp_length,
  1219. .checksum = 0,
  1220. };
  1221. /* XXX calculate checksum here */
  1222. memcpy(&buffer[offset], &udp_out, sizeof(struct udp_packet));
  1223. offset += sizeof(struct udp_packet);
  1224. /* BOOTP headers */
  1225. struct dhcp_packet bootp_out = {
  1226. .op = 1,
  1227. .htype = 1,
  1228. .hlen = 6, /* mac address... */
  1229. .hops = 0,
  1230. .xid = htonl(0x1337), /* transaction id */
  1231. .secs = 0,
  1232. .flags = 0,
  1233. .ciaddr = 0x000000,
  1234. .yiaddr = 0x000000,
  1235. .siaddr = 0x000000,
  1236. .giaddr = 0x000000,
  1237. .chaddr = { _netif.hwaddr[0], _netif.hwaddr[1], _netif.hwaddr[2],
  1238. _netif.hwaddr[3], _netif.hwaddr[4], _netif.hwaddr[5] },
  1239. .sname = {0},
  1240. .file = {0},
  1241. .magic = htonl(DHCP_MAGIC),
  1242. };
  1243. memcpy(&buffer[offset], &bootp_out, sizeof(struct dhcp_packet));
  1244. offset += sizeof(struct dhcp_packet);
  1245. memcpy(&buffer[offset], &dhcp_options, sizeof(dhcp_options));
  1246. offset += sizeof(dhcp_options);
  1247. return offset;
  1248. }
  1249. static void parse_dns_response(fs_node_t * tty, void * last_packet) {
  1250. struct udp_packet * udp = (struct udp_packet *)last_packet;
  1251. uint16_t src_port = ntohs(udp->source_port);
  1252. uint16_t dst_port = ntohs(udp->destination_port);
  1253. uint16_t udp_len = ntohs(udp->length);
  1254. fprintf(tty, "UDP [%d → %d] length=%d bytes\n",
  1255. src_port, dst_port, udp_len);
  1256. struct dns_packet * dns = (struct dns_packet *)udp->payload;
  1257. uint16_t dns_questions = ntohs(dns->questions);
  1258. uint16_t dns_answers = ntohs(dns->answers);
  1259. fprintf(tty, "DNS - %d queries, %d answers\n",
  1260. dns_questions, dns_answers);
  1261. fprintf(tty, "Queries:\n");
  1262. int offset = sizeof(struct dns_packet);
  1263. int queries = 0;
  1264. uint8_t * bytes = (uint8_t *)dns;
  1265. while (queries < dns_questions) {
  1266. offset = print_dns_name(tty, dns, offset);
  1267. uint16_t * d = (uint16_t *)&bytes[offset];
  1268. fprintf(tty, " - Type: %4x %4x\n", ntohs(d[0]), ntohs(d[1]));
  1269. offset += 4;
  1270. queries++;
  1271. }
  1272. fprintf(tty, "Answers:\n");
  1273. int answers = 0;
  1274. while (answers < dns_answers) {
  1275. char buf[1024];
  1276. size_t ret = dns_name_to_normal_name(dns, offset, buf);
  1277. debug_print(WARNING, "%d - %s", ret, buf);
  1278. offset = print_dns_name(tty, dns, offset);
  1279. uint16_t * d = (uint16_t *)&bytes[offset];
  1280. fprintf(tty, " - Type: %4x %4x; ", ntohs(d[0]), ntohs(d[1]));
  1281. offset += 4;
  1282. uint32_t * t = (uint32_t *)&bytes[offset];
  1283. fprintf(tty, "TTL: %d; ", ntohl(t[0]));
  1284. offset += 4;
  1285. uint16_t * l = (uint16_t *)&bytes[offset];
  1286. int _l = ntohs(l[0]);
  1287. fprintf(tty, "len: %d; ", _l);
  1288. offset += 2;
  1289. if (_l == 4) {
  1290. uint32_t * i = (uint32_t *)&bytes[offset];
  1291. char ip[16];
  1292. ip_ntoa(ntohl(i[0]), ip);
  1293. fprintf(tty, " Address: %s\n", ip);
  1294. debug_print(NOTICE, "Domain [%s] maps to [%s]", buf, ip);
  1295. if (!hashmap_has(dns_cache, buf)) {
  1296. hashmap_set(dns_cache, buf, strdup(ip));
  1297. }
  1298. } else {
  1299. if (ntohs(d[0]) == 5) {
  1300. fprintf(tty, "CNAME: ");
  1301. char buffer[256];
  1302. get_dns_name(buffer, dns, offset);
  1303. fprintf(tty, "%s\n", buffer);
  1304. if (strlen(buffer)) {
  1305. buffer[strlen(buffer)-1] = '\0';
  1306. }
  1307. uint32_t addr;
  1308. if (gethost(buffer,&addr) == 2) {
  1309. debug_print(WARNING,"Can't provide a response yet, but going to query again in a moment.");
  1310. } else {
  1311. if (!hashmap_has(dns_cache, buf)) {
  1312. char ip[16];
  1313. ip_ntoa(addr, ip);
  1314. hashmap_set(dns_cache, buf, strdup(ip));
  1315. fprintf(tty, "resolves to %s\n", ip);
  1316. }
  1317. }
  1318. } else {
  1319. fprintf(tty, "dunno\n");
  1320. }
  1321. }
  1322. offset += _l;
  1323. answers++;
  1324. }
  1325. wakeup_queue(dns_waiters);
  1326. }
  1327. static fs_node_t * netfs_create(void) {
  1328. fs_node_t * fnode = malloc(sizeof(fs_node_t));
  1329. memset(fnode, 0x00, sizeof(fs_node_t));
  1330. fnode->inode = 0;
  1331. strcpy(fnode->name, "net");
  1332. fnode->mask = 0555;
  1333. fnode->flags = FS_DIRECTORY;
  1334. fnode->readdir = readdir_netfs;
  1335. fnode->finddir = finddir_netfs;
  1336. fnode->ioctl = ioctl_netfs;
  1337. fnode->nlink = 1;
  1338. return fnode;
  1339. }
  1340. static int init(void) {
  1341. dns_cache = hashmap_create(10);
  1342. hashmap_set(dns_cache, "dakko.us", strdup("104.131.140.26"));
  1343. hashmap_set(dns_cache, "toaruos.org", strdup("104.131.140.26"));
  1344. hashmap_set(dns_cache, "www.toaruos.org", strdup("104.131.140.26"));
  1345. hashmap_set(dns_cache, "www.yelp.com", strdup("104.16.57.23"));
  1346. hashmap_set(dns_cache, "s3-media2.fl.yelpcdn.com", strdup("199.27.79.175"));
  1347. hashmap_set(dns_cache, "forum.osdev.org", strdup("173.255.206.39"));
  1348. hashmap_set(dns_cache, "wolfgun.puckipedia.com", strdup("104.47.147.203"));
  1349. hashmap_set(dns_cache, "irc.freenode.net", strdup("91.217.189.42"));
  1350. hashmap_set(dns_cache, "i.imgur.com", strdup("23.235.47.193"));
  1351. /* /dev/net/{domain|ip}/{protocol}/{port} */
  1352. vfs_mount("/dev/net", netfs_create());
  1353. return 0;
  1354. }
  1355. static int fini(void) {
  1356. return 0;
  1357. }
  1358. MODULE_DEF(net, init, fini);