net.c 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655
  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, uint32_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, uint32_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, uint32_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. /* TODO: socket_close - TCP close; UDP... just clean us up */
  437. /* TODO: socket_open - idk, whatever */
  438. static fs_node_t * finddir_netfs(fs_node_t * node, char * name) {
  439. /* Should essentially find anything. */
  440. debug_print(WARNING, "Need to look up domain or check if is IP: %s", name);
  441. /* Block until lookup is complete */
  442. int port = 80;
  443. char * colon;
  444. if ((colon = strstr(name, ":"))) {
  445. /* Port numbers */
  446. *colon = '\0';
  447. colon++;
  448. port = atoi(colon);
  449. }
  450. uint32_t ip = 0;
  451. if (gethost(name, &ip)) return NULL;
  452. fs_node_t * fnode = malloc(sizeof(fs_node_t));
  453. memset(fnode, 0x00, sizeof(fs_node_t));
  454. fnode->inode = 0;
  455. strcpy(fnode->name, name);
  456. fnode->mask = 0666;
  457. fnode->flags = FS_CHARDEVICE;
  458. fnode->read = socket_read;
  459. fnode->write = socket_write;
  460. fnode->device = (void *)net_open(SOCK_STREAM);
  461. fnode->selectcheck = socket_check;
  462. fnode->selectwait = socket_wait;
  463. net_connect((struct socket *)fnode->device, ip, port);
  464. return fnode;
  465. }
  466. static int ioctl_netfs(fs_node_t * node, int request, void * argp) {
  467. switch (request) {
  468. case 0x5000: {
  469. /* */
  470. debug_print(INFO, "DNS query from userspace");
  471. void ** x = (void **)argp;
  472. char * host = x[0];
  473. uint32_t * ip = x[1];
  474. /* TODO: Validate */
  475. return gethost(host, ip);
  476. }
  477. }
  478. return 0;
  479. }
  480. static size_t write_dns_packet(uint8_t * buffer, size_t queries_len, uint8_t * queries) {
  481. size_t offset = 0;
  482. size_t payload_size = sizeof(struct dns_packet) + queries_len;
  483. /* Then, let's write an ethernet frame */
  484. struct ethernet_packet eth_out = {
  485. .source = { _netif.hwaddr[0], _netif.hwaddr[1], _netif.hwaddr[2],
  486. _netif.hwaddr[3], _netif.hwaddr[4], _netif.hwaddr[5] },
  487. .destination = BROADCAST_MAC,
  488. .type = htons(0x0800),
  489. };
  490. memcpy(&buffer[offset], &eth_out, sizeof(struct ethernet_packet));
  491. offset += sizeof(struct ethernet_packet);
  492. /* Prepare the IPv4 header */
  493. uint16_t _length = htons(sizeof(struct ipv4_packet) + sizeof(struct udp_packet) + payload_size);
  494. uint16_t _ident = htons(1);
  495. struct ipv4_packet ipv4_out = {
  496. .version_ihl = ((0x4 << 4) | (0x5 << 0)), /* 4 = ipv4, 5 = no options */
  497. .dscp_ecn = 0, /* not setting either of those */
  498. .length = _length,
  499. .ident = _ident,
  500. .flags_fragment = 0,
  501. .ttl = 0x40,
  502. .protocol = IPV4_PROT_UDP,
  503. .checksum = 0, /* fill this in later */
  504. .source = htonl(_netif.source),
  505. .destination = htonl(_dns_server),
  506. };
  507. uint16_t checksum = calculate_ipv4_checksum(&ipv4_out);
  508. ipv4_out.checksum = htons(checksum);
  509. memcpy(&buffer[offset], &ipv4_out, sizeof(struct ipv4_packet));
  510. offset += sizeof(struct ipv4_packet);
  511. uint16_t _udp_source = htons(50053); /* Use an ephemeral port */
  512. uint16_t _udp_destination = htons(53);
  513. uint16_t _udp_length = htons(sizeof(struct udp_packet) + payload_size);
  514. /* Now let's build a UDP packet */
  515. struct udp_packet udp_out = {
  516. .source_port = _udp_source,
  517. .destination_port = _udp_destination,
  518. .length = _udp_length,
  519. .checksum = 0,
  520. };
  521. /* XXX calculate checksum here */
  522. memcpy(&buffer[offset], &udp_out, sizeof(struct udp_packet));
  523. offset += sizeof(struct udp_packet);
  524. /* DNS header */
  525. struct dns_packet dns_out = {
  526. .qid = htons(0),
  527. .flags = htons(0x0100), /* Standard query */
  528. .questions = htons(1), /* 1 question */
  529. .answers = htons(0),
  530. .authorities = htons(0),
  531. .additional = htons(0),
  532. };
  533. memcpy(&buffer[offset], &dns_out, sizeof(struct dns_packet));
  534. offset += sizeof(struct dns_packet);
  535. memcpy(&buffer[offset], queries, queries_len);
  536. offset += queries_len;
  537. return offset;
  538. }
  539. static int net_send_ether(struct socket *socket, struct netif* netif, uint16_t ether_type, void* payload, uint32_t payload_size) {
  540. struct ethernet_packet *eth = malloc(sizeof(struct ethernet_packet) + payload_size);
  541. memcpy(eth->source, netif->hwaddr, sizeof(eth->source));
  542. //memset(eth->destination, 0xFF, sizeof(eth->destination));
  543. memcpy(eth->destination, _gateway, sizeof(_gateway));
  544. eth->type = htons(ether_type);
  545. if (payload_size) {
  546. memcpy(eth->payload, payload, payload_size);
  547. }
  548. netif->send_packet((uint8_t*)eth, sizeof(struct ethernet_packet) + payload_size);
  549. free(eth);
  550. return 1; // yolo
  551. }
  552. static int net_send_ip(struct socket *socket, int proto, void* payload, uint32_t payload_size) {
  553. struct ipv4_packet *ipv4 = malloc(sizeof(struct ipv4_packet) + payload_size);
  554. uint16_t _length = htons(sizeof(struct ipv4_packet) + payload_size);
  555. uint16_t _ident = htons(1);
  556. ipv4->version_ihl = ((0x4 << 4) | (0x5 << 0)); /* 4 = ipv4, 5 = no options */
  557. ipv4->dscp_ecn = 0; /* not setting either of those */
  558. ipv4->length = _length;
  559. ipv4->ident = _ident;
  560. ipv4->flags_fragment = 0;
  561. ipv4->ttl = 0x40;
  562. ipv4->protocol = proto;
  563. ipv4->checksum = 0; // Fill in later */
  564. ipv4->source = htonl(_netif.source),
  565. ipv4->destination = htonl(socket->ip);
  566. uint16_t checksum = calculate_ipv4_checksum(ipv4);
  567. ipv4->checksum = htons(checksum);
  568. if (proto == IPV4_PROT_TCP) {
  569. // Need to calculate TCP checksum
  570. struct tcp_check_header check_hd = {
  571. .source = ipv4->source,
  572. .destination = ipv4->destination,
  573. .zeros = 0,
  574. .protocol = 6,
  575. .tcp_len = htons(payload_size),
  576. };
  577. // debug_print(WARNING, "net_send_ip: Payload size: %d\n", payload_size);
  578. struct tcp_header* tcp_hdr = (struct tcp_header*)payload;
  579. // debug_print(WARNING, "net_send_ip: Header len htons: %d\n", TCP_HEADER_LENGTH_FLIPPED(tcp_hdr));
  580. size_t orig_payload_size = payload_size - TCP_HEADER_LENGTH_FLIPPED(tcp_hdr);
  581. uint16_t chk = calculate_tcp_checksum(&check_hd, tcp_hdr, tcp_hdr->payload, orig_payload_size);
  582. tcp_hdr->checksum = htons(chk);
  583. }
  584. if (payload) {
  585. memcpy(ipv4->payload, payload, payload_size);
  586. free(payload);
  587. }
  588. // TODO: netif should not be a global thing. But the route should be looked up here and a netif object created/returned
  589. int out = net_send_ether(socket, &_netif, ETHERNET_TYPE_IPV4, ipv4, sizeof(struct ipv4_packet) + payload_size);
  590. free(ipv4);
  591. return out;
  592. }
  593. static int net_send_tcp(struct socket *socket, uint16_t flags, uint8_t * payload, uint32_t payload_size) {
  594. struct tcp_header *tcp = malloc(sizeof(struct tcp_header) + payload_size);
  595. tcp->source_port = htons(socket->port_recv);
  596. tcp->destination_port = htons(socket->port_dest);
  597. tcp->seq_number = htonl(socket->proto_sock.tcp_socket.seq_no);
  598. tcp->ack_number = flags & (TCP_FLAGS_ACK) ? htonl(socket->proto_sock.tcp_socket.ack_no) : 0;
  599. tcp->flags = htons(0x5000 ^ (flags & 0xFF));
  600. tcp->window_size = htons(1548-54);
  601. tcp->checksum = 0; // Fill in later
  602. tcp->urgent = 0;
  603. if ((flags & 0xff) == TCP_FLAGS_SYN) {
  604. // If only SYN set, expected ACK will be 1 despite no payload
  605. socket->proto_sock.tcp_socket.seq_no += 1;
  606. } else {
  607. socket->proto_sock.tcp_socket.seq_no += payload_size;
  608. }
  609. if (payload) {
  610. memcpy(tcp->payload, payload, payload_size);
  611. }
  612. return net_send_ip(socket, IPV4_PROT_TCP, tcp, sizeof(struct tcp_header) + payload_size);
  613. }
  614. struct socket* net_open(uint32_t type) {
  615. // This is a socket() call
  616. struct socket *sock = malloc(sizeof(struct socket));
  617. memset(sock, 0, sizeof(struct socket));
  618. sock->sock_type = type;
  619. return sock;
  620. }
  621. int net_close(struct socket* socket) {
  622. // socket->is_connected;
  623. socket->status = 1; /* Disconnected */
  624. wakeup_queue(socket->packet_wait);
  625. socket_alert_waiters(socket);
  626. return 1;
  627. }
  628. int net_send(struct socket* socket, uint8_t* payload, size_t payload_size, int flags) {
  629. return net_send_tcp(socket, TCP_FLAGS_ACK | TCP_FLAGS_PSH, payload, payload_size);
  630. }
  631. size_t net_recv(struct socket* socket, uint8_t* buffer, size_t len) {
  632. tcpdata_t *tcpdata = NULL;
  633. node_t *node = NULL;
  634. debug_print(INFO, "0x%x [socket]", socket);
  635. size_t offset = 0;
  636. size_t size_to_read = 0;
  637. do {
  638. if (socket->bytes_available) {
  639. tcpdata = socket->current_packet;
  640. } else {
  641. spin_lock(socket->packet_queue_lock);
  642. do {
  643. if (socket->packet_queue->length > 0) {
  644. node = list_dequeue(socket->packet_queue);
  645. spin_unlock(socket->packet_queue_lock);
  646. break;
  647. } else {
  648. if (socket->status == 1) {
  649. spin_unlock(socket->packet_queue_lock);
  650. debug_print(WARNING, "Socket closed, done reading.");
  651. return 0;
  652. }
  653. spin_unlock(socket->packet_queue_lock);
  654. sleep_on(socket->packet_wait);
  655. spin_lock(socket->packet_queue_lock);
  656. }
  657. } while (1);
  658. tcpdata = node->value;
  659. socket->bytes_available = tcpdata->payload_size;
  660. socket->bytes_read = 0;
  661. free(node);
  662. }
  663. size_to_read = MIN(len, socket->bytes_available);
  664. if (tcpdata->payload != 0) {
  665. memcpy(buffer + offset, tcpdata->payload + socket->bytes_read, size_to_read);
  666. }
  667. offset += size_to_read;
  668. if (size_to_read < socket->bytes_available) {
  669. socket->bytes_available -= size_to_read;
  670. socket->bytes_read += size_to_read;
  671. socket->current_packet = tcpdata;
  672. } else {
  673. socket->bytes_available = 0;
  674. socket->current_packet = NULL;
  675. free(tcpdata->payload);
  676. free(tcpdata);
  677. }
  678. } while (!size_to_read);
  679. return size_to_read;
  680. }
  681. static void net_handle_tcp(struct tcp_header * tcp, size_t length) {
  682. size_t data_length = length - TCP_HEADER_LENGTH_FLIPPED(tcp);
  683. /* Find socket */
  684. if (hashmap_has(_tcp_sockets, (void *)ntohs(tcp->destination_port))) {
  685. struct socket *socket = hashmap_get(_tcp_sockets, (void *)ntohs(tcp->destination_port));
  686. if (socket->status == 1) {
  687. debug_print(ERROR, "Socket is closed, but still receiving packets. Should send FIN. socket=0x%x", socket);
  688. return;
  689. }
  690. if (socket->proto_sock.tcp_socket.seq_no != ntohl(tcp->ack_number)) {
  691. // Drop packet
  692. debug_print(WARNING, "Dropping packet. Expected ack: %d | Got ack: %d",
  693. socket->proto_sock.tcp_socket.seq_no, ntohl(tcp->ack_number));
  694. return;
  695. }
  696. if ((htons(tcp->flags) & TCP_FLAGS_SYN) && (htons(tcp->flags) & TCP_FLAGS_ACK)) {
  697. socket->proto_sock.tcp_socket.ack_no = ntohl(tcp->seq_number) + data_length + 1;
  698. net_send_tcp(socket, TCP_FLAGS_ACK, NULL, 0);
  699. wakeup_queue(socket->proto_sock.tcp_socket.is_connected);
  700. } else if (htons(tcp->flags) & TCP_FLAGS_RES) {
  701. /* Reset doesn't necessarily mean close. */
  702. debug_print(WARNING, "net_handle_tcp: Received RST - socket closing");
  703. net_close(socket);
  704. return;
  705. } else {
  706. // Store a copy of the layer 5 data for a userspace recv() call
  707. tcpdata_t *tcpdata = malloc(sizeof(tcpdata_t));
  708. tcpdata->payload_size = length - TCP_HEADER_LENGTH_FLIPPED(tcp);
  709. if (tcpdata->payload_size == 0) {
  710. if (htons(tcp->flags) & TCP_FLAGS_FIN) {
  711. /* We should make sure we finish sending before closing. */
  712. debug_print(WARNING, "net_handle_tcp: Received FIN - socket closing with SYNACK");
  713. socket->proto_sock.tcp_socket.ack_no = ntohl(tcp->seq_number) + data_length + 1;
  714. net_send_tcp(socket, TCP_FLAGS_ACK | TCP_FLAGS_FIN, NULL, 0);
  715. wakeup_queue(socket->proto_sock.tcp_socket.is_connected);
  716. net_close(socket);
  717. }
  718. free(tcpdata);
  719. return;
  720. }
  721. // debug_print(WARNING, "net_handle_tcp: payload length: %d\n", length);
  722. // debug_print(WARNING, "net_handle_tcp: flipped tcp flags hdr len: %d\n", TCP_HEADER_LENGTH_FLIPPED(tcp));
  723. // debug_print(WARNING, "net_handle_tcp: tcpdata->payload_size: %d\n", tcpdata->payload_size);
  724. if (tcpdata->payload_size > 0) {
  725. tcpdata->payload = malloc(tcpdata->payload_size);
  726. memcpy(tcpdata->payload, tcp->payload, tcpdata->payload_size);
  727. } else {
  728. tcpdata->payload = NULL;
  729. }
  730. socket->proto_sock.tcp_socket.ack_no = ntohl(tcp->seq_number) + data_length;
  731. if ((htons(tcp->flags) & TCP_FLAGS_SYN) && (htons(tcp->flags) & TCP_FLAGS_ACK) && data_length == 0) {
  732. socket->proto_sock.tcp_socket.ack_no += 1;
  733. }
  734. socket->proto_sock.tcp_socket.ack_no = ntohl(tcp->seq_number) + tcpdata->payload_size;
  735. spin_lock(socket->packet_queue_lock);
  736. list_insert(socket->packet_queue, tcpdata);
  737. spin_unlock(socket->packet_queue_lock);
  738. // Send acknowledgement of receiving data
  739. net_send_tcp(socket, TCP_FLAGS_ACK, NULL, 0);
  740. wakeup_queue(socket->packet_wait);
  741. socket_alert_waiters(socket);
  742. if (htons(tcp->flags) & TCP_FLAGS_FIN) {
  743. /* We should make sure we finish sending before closing. */
  744. debug_print(WARNING, "net_handle_tcp: Received FIN - socket closing with SYNACK");
  745. socket->proto_sock.tcp_socket.ack_no = ntohl(tcp->seq_number) + data_length + 1;
  746. net_send_tcp(socket, TCP_FLAGS_ACK | TCP_FLAGS_FIN, NULL, 0);
  747. wakeup_queue(socket->proto_sock.tcp_socket.is_connected);
  748. net_close(socket);
  749. }
  750. }
  751. } else {
  752. debug_print(WARNING, "net_handle_tcp: Received packet not associated with a socket!");
  753. }
  754. }
  755. static void net_handle_udp(struct udp_packet * udp, size_t length) {
  756. // size_t data_length = length - sizeof(struct tcp_header);
  757. debug_print(WARNING, "UDP response!");
  758. /* Short-circuit DNS */
  759. if (ntohs(udp->source_port) == 53) {
  760. debug_print(WARNING, "UDP response to DNS query!");
  761. parse_dns_response(debug_file, udp);
  762. return;
  763. }
  764. if (ntohs(udp->source_port) == 67) {
  765. debug_print(WARNING, "UDP response to DHCP!");
  766. {
  767. void * tmp = malloc(1024);
  768. size_t packet_size = write_arp_request(tmp, _netif.gateway);
  769. _netif.send_packet(tmp, packet_size);
  770. free(tmp);
  771. }
  772. return;
  773. }
  774. /* Find socket */
  775. if (hashmap_has(_udp_sockets, (void *)ntohs(udp->source_port))) {
  776. /* Do the thing */
  777. } else {
  778. /* ??? */
  779. }
  780. }
  781. static void net_handle_ipv4(struct ipv4_packet * ipv4) {
  782. debug_print(INFO, "net_handle_ipv4: ENTER");
  783. switch (ipv4->protocol) {
  784. case IPV4_PROT_TCP:
  785. net_handle_tcp((struct tcp_header *)ipv4->payload, ntohs(ipv4->length) - sizeof(struct ipv4_packet));
  786. break;
  787. case IPV4_PROT_UDP:
  788. net_handle_udp((struct udp_packet *)ipv4->payload, ntohs(ipv4->length) - sizeof(struct ipv4_packet));
  789. break;
  790. default:
  791. /* XXX */
  792. break;
  793. }
  794. }
  795. static struct ethernet_packet* net_receive(void) {
  796. struct ethernet_packet *eth = _netif.get_packet();
  797. return eth;
  798. }
  799. int net_connect(struct socket* socket, uint32_t dest_ip, uint16_t dest_port) {
  800. if (socket->sock_type == SOCK_DGRAM) {
  801. // Can't connect UDP
  802. return -1;
  803. }
  804. memset(socket->mac, 0, sizeof(socket->mac)); // idk
  805. socket->port_recv = next_ephemeral_port();
  806. socket->proto_sock.tcp_socket.is_connected = list_create();
  807. socket->proto_sock.tcp_socket.seq_no = 0;
  808. socket->proto_sock.tcp_socket.ack_no = 0;
  809. socket->proto_sock.tcp_socket.status = 0;
  810. socket->packet_queue = list_create();
  811. socket->packet_wait = list_create();
  812. socket->alert_waiters = list_create();
  813. socket->ip = dest_ip; //ip_aton("10.255.50.206");
  814. socket->port_dest = dest_port; //12345;
  815. debug_print(WARNING, "net_connect: using ephemeral port: %d", (void*)socket->port_recv);
  816. hashmap_set(_tcp_sockets, (void*)socket->port_recv, socket);
  817. net_send_tcp(socket, TCP_FLAGS_SYN, NULL, 0);
  818. // debug_print(WARNING, "net_connect:sent tcp SYN: %d", ret);
  819. // Race condition here - if net_handle_tcp runs and connects before this sleep
  820. sleep_on(socket->proto_sock.tcp_socket.is_connected);
  821. return 1;
  822. }
  823. static void placeholder_dhcp(void) {
  824. debug_print(NOTICE, "Sending DHCP discover");
  825. void * tmp = malloc(1024);
  826. size_t packet_size = write_dhcp_packet(tmp);
  827. _netif.send_packet(tmp, packet_size);
  828. free(tmp);
  829. while (1) {
  830. struct ethernet_packet * eth = (struct ethernet_packet *)_netif.get_packet();
  831. uint16_t eth_type = ntohs(eth->type);
  832. debug_print(NOTICE, "Ethernet II, Src: (%2x:%2x:%2x:%2x:%2x:%2x), Dst: (%2x:%2x:%2x:%2x:%2x:%2x) [type=%4x])",
  833. eth->source[0], eth->source[1], eth->source[2],
  834. eth->source[3], eth->source[4], eth->source[5],
  835. eth->destination[0], eth->destination[1], eth->destination[2],
  836. eth->destination[3], eth->destination[4], eth->destination[5],
  837. eth_type);
  838. if (eth_type != 0x0800) {
  839. debug_print(WARNING, "ARP packet while waiting for DHCP...");
  840. free(eth);
  841. continue;
  842. }
  843. struct ipv4_packet * ipv4 = (struct ipv4_packet *)eth->payload;
  844. uint32_t src_addr = ntohl(ipv4->source);
  845. uint32_t dst_addr = ntohl(ipv4->destination);
  846. uint16_t length = ntohs(ipv4->length);
  847. char src_ip[16];
  848. char dst_ip[16];
  849. ip_ntoa(src_addr, src_ip);
  850. ip_ntoa(dst_addr, dst_ip);
  851. debug_print(NOTICE, "IP packet [%s → %s] length=%d bytes",
  852. src_ip, dst_ip, length);
  853. if (ipv4->protocol != IPV4_PROT_UDP) {
  854. debug_print(WARNING, "Protocol: %d", ipv4->protocol);
  855. debug_print(WARNING, "Bad packet...");
  856. free(eth);
  857. continue;
  858. }
  859. struct udp_packet * udp = (struct udp_packet *)ipv4->payload;;
  860. uint16_t src_port = ntohs(udp->source_port);
  861. uint16_t dst_port = ntohs(udp->destination_port);
  862. uint16_t udp_len = ntohs(udp->length);
  863. debug_print(NOTICE, "UDP [%d → %d] length=%d bytes",
  864. src_port, dst_port, udp_len);
  865. if (dst_port != 68) {
  866. debug_print(WARNING, "Destination port: %d", dst_port);
  867. debug_print(WARNING, "Bad packet...");
  868. free(eth);
  869. continue;
  870. }
  871. struct dhcp_packet * dhcp = (struct dhcp_packet *)udp->payload;
  872. uint32_t yiaddr = ntohl(dhcp->yiaddr);
  873. char yiaddr_ip[16];
  874. ip_ntoa(yiaddr, yiaddr_ip);
  875. debug_print(NOTICE, "DHCP Offer: %s", yiaddr_ip);
  876. _netif.source = yiaddr;
  877. debug_print(NOTICE," Scanning offer for DNS servers...");
  878. size_t i = sizeof(struct dhcp_packet);
  879. size_t j = 0;
  880. while (i < length) {
  881. uint8_t type = dhcp->options[j];
  882. uint8_t len = dhcp->options[j+1];
  883. uint8_t * data = &dhcp->options[j+2];
  884. debug_print(NOTICE," type=%d, len=%d", type, len);
  885. if (type == 255) {
  886. break;
  887. } else if (type == 6) {
  888. /* DNS Server! */
  889. uint32_t dnsaddr = ntohl(*(uint32_t *)data);
  890. char ip[16];
  891. ip_ntoa(dnsaddr, ip);
  892. debug_print(NOTICE, "Found one: %s", ip);
  893. _dns_server = dnsaddr;
  894. } else if (type == 3) {
  895. _netif.gateway = ntohl(*(uint32_t *)data);
  896. }
  897. j += 2 + len;
  898. i += 2 + len;
  899. }
  900. debug_print(NOTICE, "Sending DHCP Request...");
  901. void * tmp = malloc(1024);
  902. size_t packet_size = write_dhcp_request(tmp, (uint8_t *)&dhcp->yiaddr);
  903. _netif.send_packet(tmp, packet_size);
  904. free(tmp);
  905. free(eth);
  906. break;
  907. }
  908. }
  909. struct arp {
  910. uint16_t htype;
  911. uint16_t proto;
  912. uint8_t hlen;
  913. uint8_t plen;
  914. uint16_t oper;
  915. uint8_t sender_ha[6];
  916. uint32_t sender_ip;
  917. uint8_t target_ha[6];
  918. uint32_t target_ip;
  919. uint8_t padding[18];
  920. } __attribute__((packed));
  921. static size_t write_arp_response(uint8_t * buffer, struct arp * source) {
  922. size_t offset = 0;
  923. /* Then, let's write an ethernet frame */
  924. struct ethernet_packet eth_out = {
  925. .source = { _netif.hwaddr[0], _netif.hwaddr[1], _netif.hwaddr[2],
  926. _netif.hwaddr[3], _netif.hwaddr[4], _netif.hwaddr[5] },
  927. .destination = BROADCAST_MAC,
  928. .type = htons(0x0806),
  929. };
  930. memcpy(&buffer[offset], &eth_out, sizeof(struct ethernet_packet));
  931. offset += sizeof(struct ethernet_packet);
  932. struct arp arp_out;
  933. arp_out.htype = source->htype;
  934. arp_out.proto = source->proto;
  935. arp_out.hlen = 6;
  936. arp_out.plen = 4;
  937. arp_out.oper = ntohs(2);
  938. arp_out.sender_ha[0] = _netif.hwaddr[0];
  939. arp_out.sender_ha[1] = _netif.hwaddr[1];
  940. arp_out.sender_ha[2] = _netif.hwaddr[2];
  941. arp_out.sender_ha[3] = _netif.hwaddr[3];
  942. arp_out.sender_ha[4] = _netif.hwaddr[4];
  943. arp_out.sender_ha[5] = _netif.hwaddr[5];
  944. arp_out.sender_ip = ntohl(_netif.source);
  945. arp_out.target_ha[0] = source->sender_ha[0];
  946. arp_out.target_ha[1] = source->sender_ha[1];
  947. arp_out.target_ha[2] = source->sender_ha[2];
  948. arp_out.target_ha[3] = source->sender_ha[3];
  949. arp_out.target_ha[4] = source->sender_ha[4];
  950. arp_out.target_ha[5] = source->sender_ha[5];
  951. arp_out.target_ip = source->sender_ip;
  952. memcpy(&buffer[offset], &arp_out, sizeof(struct arp));
  953. offset += sizeof(struct arp);
  954. return offset;
  955. }
  956. static size_t write_arp_request(uint8_t * buffer, uint32_t ip) {
  957. size_t offset = 0;
  958. debug_print(WARNING, "Request ARP from gateway address %x", ip);
  959. /* Then, let's write an ethernet frame */
  960. struct ethernet_packet eth_out = {
  961. .source = { _netif.hwaddr[0], _netif.hwaddr[1], _netif.hwaddr[2],
  962. _netif.hwaddr[3], _netif.hwaddr[4], _netif.hwaddr[5] },
  963. .destination = BROADCAST_MAC,
  964. .type = htons(0x0806),
  965. };
  966. memcpy(&buffer[offset], &eth_out, sizeof(struct ethernet_packet));
  967. offset += sizeof(struct ethernet_packet);
  968. struct arp arp_out;
  969. arp_out.htype = ntohs(1);
  970. debug_print(WARNING, "Request ARP from gateway address %x", ip);
  971. arp_out.proto = ntohs(0x0800);
  972. arp_out.hlen = 6;
  973. arp_out.plen = 4;
  974. arp_out.oper = ntohs(1);
  975. arp_out.sender_ha[0] = _netif.hwaddr[0];
  976. arp_out.sender_ha[1] = _netif.hwaddr[1];
  977. arp_out.sender_ha[2] = _netif.hwaddr[2];
  978. arp_out.sender_ha[3] = _netif.hwaddr[3];
  979. arp_out.sender_ha[4] = _netif.hwaddr[4];
  980. arp_out.sender_ha[5] = _netif.hwaddr[5];
  981. arp_out.sender_ip = ntohl(_netif.source);
  982. arp_out.target_ha[0] = 0;
  983. arp_out.target_ha[1] = 0;
  984. arp_out.target_ha[2] = 0;
  985. arp_out.target_ha[3] = 0;
  986. arp_out.target_ha[4] = 0;
  987. arp_out.target_ha[5] = 0;
  988. arp_out.target_ip = ntohl(ip);
  989. memcpy(&buffer[offset], &arp_out, sizeof(struct arp));
  990. offset += sizeof(struct arp);
  991. return offset;
  992. }
  993. static void net_handle_arp(struct ethernet_packet * eth) {
  994. debug_print(WARNING, "ARP packet...");
  995. struct arp * arp = (struct arp *)&eth->payload;
  996. char sender_ip[16];
  997. char target_ip[16];
  998. ip_ntoa(ntohl(arp->sender_ip), sender_ip);
  999. ip_ntoa(ntohl(arp->target_ip), target_ip);
  1000. debug_print(WARNING, "%2x:%2x:%2x:%2x:%2x:%2x (%s) → %2x:%2x:%2x:%2x:%2x:%2x (%s) is",
  1001. arp->sender_ha[0],
  1002. arp->sender_ha[1],
  1003. arp->sender_ha[2],
  1004. arp->sender_ha[3],
  1005. arp->sender_ha[4],
  1006. arp->sender_ha[5],
  1007. sender_ip,
  1008. arp->target_ha[0],
  1009. arp->target_ha[1],
  1010. arp->target_ha[2],
  1011. arp->target_ha[3],
  1012. arp->target_ha[4],
  1013. arp->target_ha[5],
  1014. target_ip);
  1015. if (ntohs(arp->oper) == 1) {
  1016. if (ntohl(arp->target_ip) == _netif.source) {
  1017. debug_print(WARNING, "That's us!");
  1018. {
  1019. void * tmp = malloc(1024);
  1020. size_t packet_size = write_arp_response(tmp, arp);
  1021. _netif.send_packet(tmp, packet_size);
  1022. free(tmp);
  1023. }
  1024. }
  1025. } else {
  1026. if (ntohl(arp->target_ip) == _netif.source) {
  1027. debug_print(WARNING, "It's a response to our query!");
  1028. if (ntohl(arp->sender_ip) == _netif.gateway) {
  1029. _gateway[0] = arp->sender_ha[0];
  1030. _gateway[1] = arp->sender_ha[1];
  1031. _gateway[2] = arp->sender_ha[2];
  1032. _gateway[3] = arp->sender_ha[3];
  1033. _gateway[4] = arp->sender_ha[4];
  1034. _gateway[5] = arp->sender_ha[5];
  1035. }
  1036. } else {
  1037. debug_print(WARNING, "Response to someone else...\n");
  1038. }
  1039. }
  1040. }
  1041. void net_handler(void * data, char * name) {
  1042. /* Network Packet Handler*/
  1043. _netif.extra = NULL;
  1044. _dns_server = ip_aton("10.0.2.3");
  1045. placeholder_dhcp();
  1046. dns_waiters = list_create();
  1047. _tcp_sockets = hashmap_create_int(0xFF);
  1048. _udp_sockets = hashmap_create_int(0xFF);
  1049. while (1) {
  1050. struct ethernet_packet * eth = net_receive();
  1051. if (!eth) continue;
  1052. switch (ntohs(eth->type)) {
  1053. case ETHERNET_TYPE_IPV4:
  1054. net_handle_ipv4((struct ipv4_packet *)eth->payload);
  1055. break;
  1056. case ETHERNET_TYPE_ARP:
  1057. net_handle_arp(eth);
  1058. break;
  1059. }
  1060. free(eth);
  1061. }
  1062. }
  1063. size_t write_dhcp_packet(uint8_t * buffer) {
  1064. size_t offset = 0;
  1065. size_t payload_size = sizeof(struct dhcp_packet);
  1066. /* First, let's figure out how big this is supposed to be... */
  1067. uint8_t dhcp_options[] = {
  1068. 53, /* Message type */
  1069. 1, /* Length: 1 */
  1070. 1, /* Discover */
  1071. 55,
  1072. 2,
  1073. 3,
  1074. 6,
  1075. 255, /* END */
  1076. };
  1077. payload_size += sizeof(dhcp_options);
  1078. /* Then, let's write an ethernet frame */
  1079. struct ethernet_packet eth_out = {
  1080. .source = { _netif.hwaddr[0], _netif.hwaddr[1], _netif.hwaddr[2],
  1081. _netif.hwaddr[3], _netif.hwaddr[4], _netif.hwaddr[5] },
  1082. .destination = BROADCAST_MAC,
  1083. .type = htons(0x0800),
  1084. };
  1085. memcpy(&buffer[offset], &eth_out, sizeof(struct ethernet_packet));
  1086. offset += sizeof(struct ethernet_packet);
  1087. /* Prepare the IPv4 header */
  1088. uint16_t _length = htons(sizeof(struct ipv4_packet) + sizeof(struct udp_packet) + payload_size);
  1089. uint16_t _ident = htons(1);
  1090. struct ipv4_packet ipv4_out = {
  1091. .version_ihl = ((0x4 << 4) | (0x5 << 0)), /* 4 = ipv4, 5 = no options */
  1092. .dscp_ecn = 0, /* not setting either of those */
  1093. .length = _length,
  1094. .ident = _ident,
  1095. .flags_fragment = 0,
  1096. .ttl = 0x40,
  1097. .protocol = IPV4_PROT_UDP,
  1098. .checksum = 0, /* fill this in later */
  1099. .source = htonl(ip_aton("0.0.0.0")),
  1100. .destination = htonl(ip_aton("255.255.255.255")),
  1101. };
  1102. uint16_t checksum = calculate_ipv4_checksum(&ipv4_out);
  1103. ipv4_out.checksum = htons(checksum);
  1104. memcpy(&buffer[offset], &ipv4_out, sizeof(struct ipv4_packet));
  1105. offset += sizeof(struct ipv4_packet);
  1106. uint16_t _udp_source = htons(68);
  1107. uint16_t _udp_destination = htons(67);
  1108. uint16_t _udp_length = htons(sizeof(struct udp_packet) + payload_size);
  1109. /* Now let's build a UDP packet */
  1110. struct udp_packet udp_out = {
  1111. .source_port = _udp_source,
  1112. .destination_port = _udp_destination,
  1113. .length = _udp_length,
  1114. .checksum = 0,
  1115. };
  1116. /* XXX calculate checksum here */
  1117. memcpy(&buffer[offset], &udp_out, sizeof(struct udp_packet));
  1118. offset += sizeof(struct udp_packet);
  1119. /* BOOTP headers */
  1120. struct dhcp_packet bootp_out = {
  1121. .op = 1,
  1122. .htype = 1,
  1123. .hlen = 6, /* mac address... */
  1124. .hops = 0,
  1125. .xid = htonl(0x1337), /* transaction id */
  1126. .secs = 0,
  1127. .flags = 0,
  1128. .ciaddr = 0x000000,
  1129. .yiaddr = 0x000000,
  1130. .siaddr = 0x000000,
  1131. .giaddr = 0x000000,
  1132. .chaddr = { _netif.hwaddr[0], _netif.hwaddr[1], _netif.hwaddr[2],
  1133. _netif.hwaddr[3], _netif.hwaddr[4], _netif.hwaddr[5] },
  1134. .sname = {0},
  1135. .file = {0},
  1136. .magic = htonl(DHCP_MAGIC),
  1137. };
  1138. memcpy(&buffer[offset], &bootp_out, sizeof(struct dhcp_packet));
  1139. offset += sizeof(struct dhcp_packet);
  1140. memcpy(&buffer[offset], &dhcp_options, sizeof(dhcp_options));
  1141. offset += sizeof(dhcp_options);
  1142. return offset;
  1143. }
  1144. size_t write_dhcp_request(uint8_t * buffer, uint8_t * ip) {
  1145. size_t offset = 0;
  1146. size_t payload_size = sizeof(struct dhcp_packet);
  1147. /* First, let's figure out how big this is supposed to be... */
  1148. uint8_t dhcp_options[] = {
  1149. 53, /* Message type */
  1150. 1, /* Length: 1 */
  1151. 3, /* Request */
  1152. 50,
  1153. 4, /* requested ip */
  1154. ip[0],ip[1],ip[2],ip[3],
  1155. 55,
  1156. 2,
  1157. 3,
  1158. 6,
  1159. 255, /* END */
  1160. };
  1161. payload_size += sizeof(dhcp_options);
  1162. /* Then, let's write an ethernet frame */
  1163. struct ethernet_packet eth_out = {
  1164. .source = { _netif.hwaddr[0], _netif.hwaddr[1], _netif.hwaddr[2],
  1165. _netif.hwaddr[3], _netif.hwaddr[4], _netif.hwaddr[5] },
  1166. .destination = BROADCAST_MAC,
  1167. .type = htons(0x0800),
  1168. };
  1169. memcpy(&buffer[offset], &eth_out, sizeof(struct ethernet_packet));
  1170. offset += sizeof(struct ethernet_packet);
  1171. /* Prepare the IPv4 header */
  1172. uint16_t _length = htons(sizeof(struct ipv4_packet) + sizeof(struct udp_packet) + payload_size);
  1173. uint16_t _ident = htons(1);
  1174. struct ipv4_packet ipv4_out = {
  1175. .version_ihl = ((0x4 << 4) | (0x5 << 0)), /* 4 = ipv4, 5 = no options */
  1176. .dscp_ecn = 0, /* not setting either of those */
  1177. .length = _length,
  1178. .ident = _ident,
  1179. .flags_fragment = 0,
  1180. .ttl = 0x40,
  1181. .protocol = IPV4_PROT_UDP,
  1182. .checksum = 0, /* fill this in later */
  1183. .source = htonl(ip_aton("0.0.0.0")),
  1184. .destination = htonl(ip_aton("255.255.255.255")),
  1185. };
  1186. uint16_t checksum = calculate_ipv4_checksum(&ipv4_out);
  1187. ipv4_out.checksum = htons(checksum);
  1188. memcpy(&buffer[offset], &ipv4_out, sizeof(struct ipv4_packet));
  1189. offset += sizeof(struct ipv4_packet);
  1190. uint16_t _udp_source = htons(68);
  1191. uint16_t _udp_destination = htons(67);
  1192. uint16_t _udp_length = htons(sizeof(struct udp_packet) + payload_size);
  1193. /* Now let's build a UDP packet */
  1194. struct udp_packet udp_out = {
  1195. .source_port = _udp_source,
  1196. .destination_port = _udp_destination,
  1197. .length = _udp_length,
  1198. .checksum = 0,
  1199. };
  1200. /* XXX calculate checksum here */
  1201. memcpy(&buffer[offset], &udp_out, sizeof(struct udp_packet));
  1202. offset += sizeof(struct udp_packet);
  1203. /* BOOTP headers */
  1204. struct dhcp_packet bootp_out = {
  1205. .op = 1,
  1206. .htype = 1,
  1207. .hlen = 6, /* mac address... */
  1208. .hops = 0,
  1209. .xid = htonl(0x1337), /* transaction id */
  1210. .secs = 0,
  1211. .flags = 0,
  1212. .ciaddr = 0x000000,
  1213. .yiaddr = 0x000000,
  1214. .siaddr = 0x000000,
  1215. .giaddr = 0x000000,
  1216. .chaddr = { _netif.hwaddr[0], _netif.hwaddr[1], _netif.hwaddr[2],
  1217. _netif.hwaddr[3], _netif.hwaddr[4], _netif.hwaddr[5] },
  1218. .sname = {0},
  1219. .file = {0},
  1220. .magic = htonl(DHCP_MAGIC),
  1221. };
  1222. memcpy(&buffer[offset], &bootp_out, sizeof(struct dhcp_packet));
  1223. offset += sizeof(struct dhcp_packet);
  1224. memcpy(&buffer[offset], &dhcp_options, sizeof(dhcp_options));
  1225. offset += sizeof(dhcp_options);
  1226. return offset;
  1227. }
  1228. static void parse_dns_response(fs_node_t * tty, void * last_packet) {
  1229. struct udp_packet * udp = (struct udp_packet *)last_packet;
  1230. uint16_t src_port = ntohs(udp->source_port);
  1231. uint16_t dst_port = ntohs(udp->destination_port);
  1232. uint16_t udp_len = ntohs(udp->length);
  1233. fprintf(tty, "UDP [%d → %d] length=%d bytes\n",
  1234. src_port, dst_port, udp_len);
  1235. struct dns_packet * dns = (struct dns_packet *)udp->payload;
  1236. uint16_t dns_questions = ntohs(dns->questions);
  1237. uint16_t dns_answers = ntohs(dns->answers);
  1238. fprintf(tty, "DNS - %d queries, %d answers\n",
  1239. dns_questions, dns_answers);
  1240. fprintf(tty, "Queries:\n");
  1241. int offset = sizeof(struct dns_packet);
  1242. int queries = 0;
  1243. uint8_t * bytes = (uint8_t *)dns;
  1244. while (queries < dns_questions) {
  1245. offset = print_dns_name(tty, dns, offset);
  1246. uint16_t * d = (uint16_t *)&bytes[offset];
  1247. fprintf(tty, " - Type: %4x %4x\n", ntohs(d[0]), ntohs(d[1]));
  1248. offset += 4;
  1249. queries++;
  1250. }
  1251. fprintf(tty, "Answers:\n");
  1252. int answers = 0;
  1253. while (answers < dns_answers) {
  1254. char buf[1024];
  1255. size_t ret = dns_name_to_normal_name(dns, offset, buf);
  1256. debug_print(WARNING, "%d - %s", ret, buf);
  1257. offset = print_dns_name(tty, dns, offset);
  1258. uint16_t * d = (uint16_t *)&bytes[offset];
  1259. fprintf(tty, " - Type: %4x %4x; ", ntohs(d[0]), ntohs(d[1]));
  1260. offset += 4;
  1261. uint32_t * t = (uint32_t *)&bytes[offset];
  1262. fprintf(tty, "TTL: %d; ", ntohl(t[0]));
  1263. offset += 4;
  1264. uint16_t * l = (uint16_t *)&bytes[offset];
  1265. int _l = ntohs(l[0]);
  1266. fprintf(tty, "len: %d; ", _l);
  1267. offset += 2;
  1268. if (_l == 4) {
  1269. uint32_t * i = (uint32_t *)&bytes[offset];
  1270. char ip[16];
  1271. ip_ntoa(ntohl(i[0]), ip);
  1272. fprintf(tty, " Address: %s\n", ip);
  1273. debug_print(NOTICE, "Domain [%s] maps to [%s]", buf, ip);
  1274. if (!hashmap_has(dns_cache, buf)) {
  1275. hashmap_set(dns_cache, buf, strdup(ip));
  1276. }
  1277. } else {
  1278. if (ntohs(d[0]) == 5) {
  1279. fprintf(tty, "CNAME: ");
  1280. char buffer[256];
  1281. get_dns_name(buffer, dns, offset);
  1282. fprintf(tty, "%s\n", buffer);
  1283. if (strlen(buffer)) {
  1284. buffer[strlen(buffer)-1] = '\0';
  1285. }
  1286. uint32_t addr;
  1287. if (gethost(buffer,&addr) == 2) {
  1288. debug_print(WARNING,"Can't provide a response yet, but going to query again in a moment.");
  1289. } else {
  1290. if (!hashmap_has(dns_cache, buf)) {
  1291. char ip[16];
  1292. ip_ntoa(addr, ip);
  1293. hashmap_set(dns_cache, buf, strdup(ip));
  1294. fprintf(tty, "resolves to %s\n", ip);
  1295. }
  1296. }
  1297. } else {
  1298. fprintf(tty, "dunno\n");
  1299. }
  1300. }
  1301. offset += _l;
  1302. answers++;
  1303. }
  1304. wakeup_queue(dns_waiters);
  1305. }
  1306. static fs_node_t * netfs_create(void) {
  1307. fs_node_t * fnode = malloc(sizeof(fs_node_t));
  1308. memset(fnode, 0x00, sizeof(fs_node_t));
  1309. fnode->inode = 0;
  1310. strcpy(fnode->name, "net");
  1311. fnode->mask = 0555;
  1312. fnode->flags = FS_DIRECTORY;
  1313. fnode->readdir = readdir_netfs;
  1314. fnode->finddir = finddir_netfs;
  1315. fnode->ioctl = ioctl_netfs;
  1316. fnode->nlink = 1;
  1317. return fnode;
  1318. }
  1319. static int init(void) {
  1320. dns_cache = hashmap_create(10);
  1321. hashmap_set(dns_cache, "dakko.us", strdup("104.131.140.26"));
  1322. hashmap_set(dns_cache, "toaruos.org", strdup("104.131.140.26"));
  1323. hashmap_set(dns_cache, "www.toaruos.org", strdup("104.131.140.26"));
  1324. hashmap_set(dns_cache, "www.yelp.com", strdup("104.16.57.23"));
  1325. hashmap_set(dns_cache, "s3-media2.fl.yelpcdn.com", strdup("199.27.79.175"));
  1326. hashmap_set(dns_cache, "forum.osdev.org", strdup("173.255.206.39"));
  1327. hashmap_set(dns_cache, "wolfgun.puckipedia.com", strdup("104.47.147.203"));
  1328. hashmap_set(dns_cache, "irc.freenode.net", strdup("91.217.189.42"));
  1329. hashmap_set(dns_cache, "i.imgur.com", strdup("23.235.47.193"));
  1330. /* /dev/net/{domain|ip}/{protocol}/{port} */
  1331. vfs_mount("/dev/net", netfs_create());
  1332. return 0;
  1333. }
  1334. static int fini(void) {
  1335. return 0;
  1336. }
  1337. MODULE_DEF(net, init, fini);