net.c 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105
  1. /*
  2. * QEMU System Emulator
  3. *
  4. * Copyright (c) 2003-2008 Fabrice Bellard
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  19. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. * THE SOFTWARE.
  23. */
  24. #include "qemu/osdep.h"
  25. #include "net/net.h"
  26. #include "clients.h"
  27. #include "hub.h"
  28. #include "hw/qdev-properties.h"
  29. #include "net/slirp.h"
  30. #include "net/eth.h"
  31. #include "util.h"
  32. #include "monitor/monitor.h"
  33. #include "qemu/help_option.h"
  34. #include "qapi/qapi-commands-net.h"
  35. #include "qapi/qapi-visit-net.h"
  36. #include "qapi/qmp/qdict.h"
  37. #include "qapi/qmp/qerror.h"
  38. #include "qemu/error-report.h"
  39. #include "qemu/sockets.h"
  40. #include "qemu/cutils.h"
  41. #include "qemu/config-file.h"
  42. #include "qemu/ctype.h"
  43. #include "qemu/id.h"
  44. #include "qemu/iov.h"
  45. #include "qemu/qemu-print.h"
  46. #include "qemu/main-loop.h"
  47. #include "qemu/option.h"
  48. #include "qemu/keyval.h"
  49. #include "qapi/error.h"
  50. #include "qapi/opts-visitor.h"
  51. #include "sysemu/runstate.h"
  52. #include "net/colo-compare.h"
  53. #include "net/filter.h"
  54. #include "qapi/string-output-visitor.h"
  55. #include "qapi/qobject-input-visitor.h"
  56. #include "standard-headers/linux/virtio_net.h"
  57. /* Net bridge is currently not supported for W32. */
  58. #if !defined(_WIN32)
  59. # define CONFIG_NET_BRIDGE
  60. #endif
  61. static VMChangeStateEntry *net_change_state_entry;
  62. NetClientStateList net_clients;
  63. typedef struct NetdevQueueEntry {
  64. Netdev *nd;
  65. Location loc;
  66. QSIMPLEQ_ENTRY(NetdevQueueEntry) entry;
  67. } NetdevQueueEntry;
  68. typedef QSIMPLEQ_HEAD(, NetdevQueueEntry) NetdevQueue;
  69. static NetdevQueue nd_queue = QSIMPLEQ_HEAD_INITIALIZER(nd_queue);
  70. static GHashTable *nic_model_help;
  71. static int nb_nics;
  72. static NICInfo nd_table[MAX_NICS];
  73. /***********************************************************/
  74. /* network device redirectors */
  75. int convert_host_port(struct sockaddr_in *saddr, const char *host,
  76. const char *port, Error **errp)
  77. {
  78. struct hostent *he;
  79. const char *r;
  80. long p;
  81. memset(saddr, 0, sizeof(*saddr));
  82. saddr->sin_family = AF_INET;
  83. if (host[0] == '\0') {
  84. saddr->sin_addr.s_addr = 0;
  85. } else {
  86. if (qemu_isdigit(host[0])) {
  87. if (!inet_aton(host, &saddr->sin_addr)) {
  88. error_setg(errp, "host address '%s' is not a valid "
  89. "IPv4 address", host);
  90. return -1;
  91. }
  92. } else {
  93. he = gethostbyname(host);
  94. if (he == NULL) {
  95. error_setg(errp, "can't resolve host address '%s'", host);
  96. return -1;
  97. }
  98. saddr->sin_addr = *(struct in_addr *)he->h_addr;
  99. }
  100. }
  101. if (qemu_strtol(port, &r, 0, &p) != 0) {
  102. error_setg(errp, "port number '%s' is invalid", port);
  103. return -1;
  104. }
  105. saddr->sin_port = htons(p);
  106. return 0;
  107. }
  108. int parse_host_port(struct sockaddr_in *saddr, const char *str,
  109. Error **errp)
  110. {
  111. gchar **substrings;
  112. int ret;
  113. substrings = g_strsplit(str, ":", 2);
  114. if (!substrings || !substrings[0] || !substrings[1]) {
  115. error_setg(errp, "host address '%s' doesn't contain ':' "
  116. "separating host from port", str);
  117. ret = -1;
  118. goto out;
  119. }
  120. ret = convert_host_port(saddr, substrings[0], substrings[1], errp);
  121. out:
  122. g_strfreev(substrings);
  123. return ret;
  124. }
  125. char *qemu_mac_strdup_printf(const uint8_t *macaddr)
  126. {
  127. return g_strdup_printf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",
  128. macaddr[0], macaddr[1], macaddr[2],
  129. macaddr[3], macaddr[4], macaddr[5]);
  130. }
  131. void qemu_set_info_str(NetClientState *nc, const char *fmt, ...)
  132. {
  133. va_list ap;
  134. va_start(ap, fmt);
  135. vsnprintf(nc->info_str, sizeof(nc->info_str), fmt, ap);
  136. va_end(ap);
  137. }
  138. void qemu_format_nic_info_str(NetClientState *nc, uint8_t macaddr[6])
  139. {
  140. qemu_set_info_str(nc, "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
  141. nc->model, macaddr[0], macaddr[1], macaddr[2],
  142. macaddr[3], macaddr[4], macaddr[5]);
  143. }
  144. static int mac_table[256] = {0};
  145. static void qemu_macaddr_set_used(MACAddr *macaddr)
  146. {
  147. int index;
  148. for (index = 0x56; index < 0xFF; index++) {
  149. if (macaddr->a[5] == index) {
  150. mac_table[index]++;
  151. }
  152. }
  153. }
  154. static void qemu_macaddr_set_free(MACAddr *macaddr)
  155. {
  156. int index;
  157. static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
  158. if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
  159. return;
  160. }
  161. for (index = 0x56; index < 0xFF; index++) {
  162. if (macaddr->a[5] == index) {
  163. mac_table[index]--;
  164. }
  165. }
  166. }
  167. static int qemu_macaddr_get_free(void)
  168. {
  169. int index;
  170. for (index = 0x56; index < 0xFF; index++) {
  171. if (mac_table[index] == 0) {
  172. return index;
  173. }
  174. }
  175. return -1;
  176. }
  177. void qemu_macaddr_default_if_unset(MACAddr *macaddr)
  178. {
  179. static const MACAddr zero = { .a = { 0,0,0,0,0,0 } };
  180. static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
  181. if (memcmp(macaddr, &zero, sizeof(zero)) != 0) {
  182. if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
  183. return;
  184. } else {
  185. qemu_macaddr_set_used(macaddr);
  186. return;
  187. }
  188. }
  189. macaddr->a[0] = 0x52;
  190. macaddr->a[1] = 0x54;
  191. macaddr->a[2] = 0x00;
  192. macaddr->a[3] = 0x12;
  193. macaddr->a[4] = 0x34;
  194. macaddr->a[5] = qemu_macaddr_get_free();
  195. qemu_macaddr_set_used(macaddr);
  196. }
  197. /**
  198. * Generate a name for net client
  199. *
  200. * Only net clients created with the legacy -net option and NICs need this.
  201. */
  202. static char *assign_name(NetClientState *nc1, const char *model)
  203. {
  204. NetClientState *nc;
  205. int id = 0;
  206. QTAILQ_FOREACH(nc, &net_clients, next) {
  207. if (nc == nc1) {
  208. continue;
  209. }
  210. if (strcmp(nc->model, model) == 0) {
  211. id++;
  212. }
  213. }
  214. return g_strdup_printf("%s.%d", model, id);
  215. }
  216. static void qemu_net_client_destructor(NetClientState *nc)
  217. {
  218. g_free(nc);
  219. }
  220. static ssize_t qemu_deliver_packet_iov(NetClientState *sender,
  221. unsigned flags,
  222. const struct iovec *iov,
  223. int iovcnt,
  224. void *opaque);
  225. static void qemu_net_client_setup(NetClientState *nc,
  226. NetClientInfo *info,
  227. NetClientState *peer,
  228. const char *model,
  229. const char *name,
  230. NetClientDestructor *destructor,
  231. bool is_datapath)
  232. {
  233. nc->info = info;
  234. nc->model = g_strdup(model);
  235. if (name) {
  236. nc->name = g_strdup(name);
  237. } else {
  238. nc->name = assign_name(nc, model);
  239. }
  240. if (peer) {
  241. assert(!peer->peer);
  242. nc->peer = peer;
  243. peer->peer = nc;
  244. }
  245. QTAILQ_INSERT_TAIL(&net_clients, nc, next);
  246. nc->incoming_queue = qemu_new_net_queue(qemu_deliver_packet_iov, nc);
  247. nc->destructor = destructor;
  248. nc->is_datapath = is_datapath;
  249. QTAILQ_INIT(&nc->filters);
  250. }
  251. NetClientState *qemu_new_net_client(NetClientInfo *info,
  252. NetClientState *peer,
  253. const char *model,
  254. const char *name)
  255. {
  256. NetClientState *nc;
  257. assert(info->size >= sizeof(NetClientState));
  258. nc = g_malloc0(info->size);
  259. qemu_net_client_setup(nc, info, peer, model, name,
  260. qemu_net_client_destructor, true);
  261. return nc;
  262. }
  263. NetClientState *qemu_new_net_control_client(NetClientInfo *info,
  264. NetClientState *peer,
  265. const char *model,
  266. const char *name)
  267. {
  268. NetClientState *nc;
  269. assert(info->size >= sizeof(NetClientState));
  270. nc = g_malloc0(info->size);
  271. qemu_net_client_setup(nc, info, peer, model, name,
  272. qemu_net_client_destructor, false);
  273. return nc;
  274. }
  275. NICState *qemu_new_nic(NetClientInfo *info,
  276. NICConf *conf,
  277. const char *model,
  278. const char *name,
  279. MemReentrancyGuard *reentrancy_guard,
  280. void *opaque)
  281. {
  282. NetClientState **peers = conf->peers.ncs;
  283. NICState *nic;
  284. int i, queues = MAX(1, conf->peers.queues);
  285. assert(info->type == NET_CLIENT_DRIVER_NIC);
  286. assert(info->size >= sizeof(NICState));
  287. nic = g_malloc0(info->size + sizeof(NetClientState) * queues);
  288. nic->ncs = (void *)nic + info->size;
  289. nic->conf = conf;
  290. nic->reentrancy_guard = reentrancy_guard,
  291. nic->opaque = opaque;
  292. for (i = 0; i < queues; i++) {
  293. qemu_net_client_setup(&nic->ncs[i], info, peers[i], model, name,
  294. NULL, true);
  295. nic->ncs[i].queue_index = i;
  296. }
  297. return nic;
  298. }
  299. NetClientState *qemu_get_subqueue(NICState *nic, int queue_index)
  300. {
  301. return nic->ncs + queue_index;
  302. }
  303. NetClientState *qemu_get_queue(NICState *nic)
  304. {
  305. return qemu_get_subqueue(nic, 0);
  306. }
  307. NICState *qemu_get_nic(NetClientState *nc)
  308. {
  309. NetClientState *nc0 = nc - nc->queue_index;
  310. return (NICState *)((void *)nc0 - nc->info->size);
  311. }
  312. void *qemu_get_nic_opaque(NetClientState *nc)
  313. {
  314. NICState *nic = qemu_get_nic(nc);
  315. return nic->opaque;
  316. }
  317. NetClientState *qemu_get_peer(NetClientState *nc, int queue_index)
  318. {
  319. assert(nc != NULL);
  320. NetClientState *ncs = nc + queue_index;
  321. return ncs->peer;
  322. }
  323. static void qemu_cleanup_net_client(NetClientState *nc)
  324. {
  325. QTAILQ_REMOVE(&net_clients, nc, next);
  326. if (nc->info->cleanup) {
  327. nc->info->cleanup(nc);
  328. }
  329. }
  330. static void qemu_free_net_client(NetClientState *nc)
  331. {
  332. if (nc->incoming_queue) {
  333. qemu_del_net_queue(nc->incoming_queue);
  334. }
  335. if (nc->peer) {
  336. nc->peer->peer = NULL;
  337. }
  338. g_free(nc->name);
  339. g_free(nc->model);
  340. if (nc->destructor) {
  341. nc->destructor(nc);
  342. }
  343. }
  344. void qemu_del_net_client(NetClientState *nc)
  345. {
  346. NetClientState *ncs[MAX_QUEUE_NUM];
  347. int queues, i;
  348. NetFilterState *nf, *next;
  349. assert(nc->info->type != NET_CLIENT_DRIVER_NIC);
  350. /* If the NetClientState belongs to a multiqueue backend, we will change all
  351. * other NetClientStates also.
  352. */
  353. queues = qemu_find_net_clients_except(nc->name, ncs,
  354. NET_CLIENT_DRIVER_NIC,
  355. MAX_QUEUE_NUM);
  356. assert(queues != 0);
  357. QTAILQ_FOREACH_SAFE(nf, &nc->filters, next, next) {
  358. object_unparent(OBJECT(nf));
  359. }
  360. /* If there is a peer NIC, delete and cleanup client, but do not free. */
  361. if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_NIC) {
  362. NICState *nic = qemu_get_nic(nc->peer);
  363. if (nic->peer_deleted) {
  364. return;
  365. }
  366. nic->peer_deleted = true;
  367. for (i = 0; i < queues; i++) {
  368. ncs[i]->peer->link_down = true;
  369. }
  370. if (nc->peer->info->link_status_changed) {
  371. nc->peer->info->link_status_changed(nc->peer);
  372. }
  373. for (i = 0; i < queues; i++) {
  374. qemu_cleanup_net_client(ncs[i]);
  375. }
  376. return;
  377. }
  378. for (i = 0; i < queues; i++) {
  379. qemu_cleanup_net_client(ncs[i]);
  380. qemu_free_net_client(ncs[i]);
  381. }
  382. }
  383. void qemu_del_nic(NICState *nic)
  384. {
  385. int i, queues = MAX(nic->conf->peers.queues, 1);
  386. qemu_macaddr_set_free(&nic->conf->macaddr);
  387. for (i = 0; i < queues; i++) {
  388. NetClientState *nc = qemu_get_subqueue(nic, i);
  389. /* If this is a peer NIC and peer has already been deleted, free it now. */
  390. if (nic->peer_deleted) {
  391. qemu_free_net_client(nc->peer);
  392. } else if (nc->peer) {
  393. /* if there are RX packets pending, complete them */
  394. qemu_purge_queued_packets(nc->peer);
  395. }
  396. }
  397. for (i = queues - 1; i >= 0; i--) {
  398. NetClientState *nc = qemu_get_subqueue(nic, i);
  399. qemu_cleanup_net_client(nc);
  400. qemu_free_net_client(nc);
  401. }
  402. g_free(nic);
  403. }
  404. void qemu_foreach_nic(qemu_nic_foreach func, void *opaque)
  405. {
  406. NetClientState *nc;
  407. QTAILQ_FOREACH(nc, &net_clients, next) {
  408. if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
  409. if (nc->queue_index == 0) {
  410. func(qemu_get_nic(nc), opaque);
  411. }
  412. }
  413. }
  414. }
  415. bool qemu_has_ufo(NetClientState *nc)
  416. {
  417. if (!nc || !nc->info->has_ufo) {
  418. return false;
  419. }
  420. return nc->info->has_ufo(nc);
  421. }
  422. bool qemu_has_uso(NetClientState *nc)
  423. {
  424. if (!nc || !nc->info->has_uso) {
  425. return false;
  426. }
  427. return nc->info->has_uso(nc);
  428. }
  429. bool qemu_has_vnet_hdr(NetClientState *nc)
  430. {
  431. if (!nc || !nc->info->has_vnet_hdr) {
  432. return false;
  433. }
  434. return nc->info->has_vnet_hdr(nc);
  435. }
  436. bool qemu_has_vnet_hdr_len(NetClientState *nc, int len)
  437. {
  438. if (!nc || !nc->info->has_vnet_hdr_len) {
  439. return false;
  440. }
  441. return nc->info->has_vnet_hdr_len(nc, len);
  442. }
  443. void qemu_set_offload(NetClientState *nc, int csum, int tso4, int tso6,
  444. int ecn, int ufo, int uso4, int uso6)
  445. {
  446. if (!nc || !nc->info->set_offload) {
  447. return;
  448. }
  449. nc->info->set_offload(nc, csum, tso4, tso6, ecn, ufo, uso4, uso6);
  450. }
  451. int qemu_get_vnet_hdr_len(NetClientState *nc)
  452. {
  453. return nc->vnet_hdr_len;
  454. }
  455. void qemu_set_vnet_hdr_len(NetClientState *nc, int len)
  456. {
  457. if (!nc || !nc->info->set_vnet_hdr_len) {
  458. return;
  459. }
  460. assert(len == sizeof(struct virtio_net_hdr_mrg_rxbuf) ||
  461. len == sizeof(struct virtio_net_hdr) ||
  462. len == sizeof(struct virtio_net_hdr_v1_hash));
  463. nc->vnet_hdr_len = len;
  464. nc->info->set_vnet_hdr_len(nc, len);
  465. }
  466. int qemu_set_vnet_le(NetClientState *nc, bool is_le)
  467. {
  468. #if HOST_BIG_ENDIAN
  469. if (!nc || !nc->info->set_vnet_le) {
  470. return -ENOSYS;
  471. }
  472. return nc->info->set_vnet_le(nc, is_le);
  473. #else
  474. return 0;
  475. #endif
  476. }
  477. int qemu_set_vnet_be(NetClientState *nc, bool is_be)
  478. {
  479. #if HOST_BIG_ENDIAN
  480. return 0;
  481. #else
  482. if (!nc || !nc->info->set_vnet_be) {
  483. return -ENOSYS;
  484. }
  485. return nc->info->set_vnet_be(nc, is_be);
  486. #endif
  487. }
  488. int qemu_can_receive_packet(NetClientState *nc)
  489. {
  490. if (nc->receive_disabled) {
  491. return 0;
  492. } else if (nc->info->can_receive &&
  493. !nc->info->can_receive(nc)) {
  494. return 0;
  495. }
  496. return 1;
  497. }
  498. int qemu_can_send_packet(NetClientState *sender)
  499. {
  500. int vm_running = runstate_is_running();
  501. if (!vm_running) {
  502. return 0;
  503. }
  504. if (!sender->peer) {
  505. return 1;
  506. }
  507. return qemu_can_receive_packet(sender->peer);
  508. }
  509. static ssize_t filter_receive_iov(NetClientState *nc,
  510. NetFilterDirection direction,
  511. NetClientState *sender,
  512. unsigned flags,
  513. const struct iovec *iov,
  514. int iovcnt,
  515. NetPacketSent *sent_cb)
  516. {
  517. ssize_t ret = 0;
  518. NetFilterState *nf = NULL;
  519. if (direction == NET_FILTER_DIRECTION_TX) {
  520. QTAILQ_FOREACH(nf, &nc->filters, next) {
  521. ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
  522. iovcnt, sent_cb);
  523. if (ret) {
  524. return ret;
  525. }
  526. }
  527. } else {
  528. QTAILQ_FOREACH_REVERSE(nf, &nc->filters, next) {
  529. ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
  530. iovcnt, sent_cb);
  531. if (ret) {
  532. return ret;
  533. }
  534. }
  535. }
  536. return ret;
  537. }
  538. static ssize_t filter_receive(NetClientState *nc,
  539. NetFilterDirection direction,
  540. NetClientState *sender,
  541. unsigned flags,
  542. const uint8_t *data,
  543. size_t size,
  544. NetPacketSent *sent_cb)
  545. {
  546. struct iovec iov = {
  547. .iov_base = (void *)data,
  548. .iov_len = size
  549. };
  550. return filter_receive_iov(nc, direction, sender, flags, &iov, 1, sent_cb);
  551. }
  552. void qemu_purge_queued_packets(NetClientState *nc)
  553. {
  554. if (!nc->peer) {
  555. return;
  556. }
  557. qemu_net_queue_purge(nc->peer->incoming_queue, nc);
  558. }
  559. void qemu_flush_or_purge_queued_packets(NetClientState *nc, bool purge)
  560. {
  561. nc->receive_disabled = 0;
  562. if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_HUBPORT) {
  563. if (net_hub_flush(nc->peer)) {
  564. qemu_notify_event();
  565. }
  566. }
  567. if (qemu_net_queue_flush(nc->incoming_queue)) {
  568. /* We emptied the queue successfully, signal to the IO thread to repoll
  569. * the file descriptor (for tap, for example).
  570. */
  571. qemu_notify_event();
  572. } else if (purge) {
  573. /* Unable to empty the queue, purge remaining packets */
  574. qemu_net_queue_purge(nc->incoming_queue, nc->peer);
  575. }
  576. }
  577. void qemu_flush_queued_packets(NetClientState *nc)
  578. {
  579. qemu_flush_or_purge_queued_packets(nc, false);
  580. }
  581. static ssize_t qemu_send_packet_async_with_flags(NetClientState *sender,
  582. unsigned flags,
  583. const uint8_t *buf, int size,
  584. NetPacketSent *sent_cb)
  585. {
  586. NetQueue *queue;
  587. int ret;
  588. #ifdef DEBUG_NET
  589. printf("qemu_send_packet_async:\n");
  590. qemu_hexdump(stdout, "net", buf, size);
  591. #endif
  592. if (sender->link_down || !sender->peer) {
  593. return size;
  594. }
  595. /* Let filters handle the packet first */
  596. ret = filter_receive(sender, NET_FILTER_DIRECTION_TX,
  597. sender, flags, buf, size, sent_cb);
  598. if (ret) {
  599. return ret;
  600. }
  601. ret = filter_receive(sender->peer, NET_FILTER_DIRECTION_RX,
  602. sender, flags, buf, size, sent_cb);
  603. if (ret) {
  604. return ret;
  605. }
  606. queue = sender->peer->incoming_queue;
  607. return qemu_net_queue_send(queue, sender, flags, buf, size, sent_cb);
  608. }
  609. ssize_t qemu_send_packet_async(NetClientState *sender,
  610. const uint8_t *buf, int size,
  611. NetPacketSent *sent_cb)
  612. {
  613. return qemu_send_packet_async_with_flags(sender, QEMU_NET_PACKET_FLAG_NONE,
  614. buf, size, sent_cb);
  615. }
  616. ssize_t qemu_send_packet(NetClientState *nc, const uint8_t *buf, int size)
  617. {
  618. return qemu_send_packet_async(nc, buf, size, NULL);
  619. }
  620. ssize_t qemu_receive_packet(NetClientState *nc, const uint8_t *buf, int size)
  621. {
  622. if (!qemu_can_receive_packet(nc)) {
  623. return 0;
  624. }
  625. return qemu_net_queue_receive(nc->incoming_queue, buf, size);
  626. }
  627. ssize_t qemu_send_packet_raw(NetClientState *nc, const uint8_t *buf, int size)
  628. {
  629. return qemu_send_packet_async_with_flags(nc, QEMU_NET_PACKET_FLAG_RAW,
  630. buf, size, NULL);
  631. }
  632. static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov,
  633. int iovcnt, unsigned flags)
  634. {
  635. uint8_t *buf = NULL;
  636. uint8_t *buffer;
  637. size_t offset;
  638. ssize_t ret;
  639. if (iovcnt == 1) {
  640. buffer = iov[0].iov_base;
  641. offset = iov[0].iov_len;
  642. } else {
  643. offset = iov_size(iov, iovcnt);
  644. if (offset > NET_BUFSIZE) {
  645. return -1;
  646. }
  647. buf = g_malloc(offset);
  648. buffer = buf;
  649. offset = iov_to_buf(iov, iovcnt, 0, buf, offset);
  650. }
  651. ret = nc->info->receive(nc, buffer, offset);
  652. g_free(buf);
  653. return ret;
  654. }
  655. static ssize_t qemu_deliver_packet_iov(NetClientState *sender,
  656. unsigned flags,
  657. const struct iovec *iov,
  658. int iovcnt,
  659. void *opaque)
  660. {
  661. MemReentrancyGuard *owned_reentrancy_guard;
  662. NetClientState *nc = opaque;
  663. int ret;
  664. struct virtio_net_hdr_v1_hash vnet_hdr = { };
  665. g_autofree struct iovec *iov_copy = NULL;
  666. if (nc->link_down) {
  667. return iov_size(iov, iovcnt);
  668. }
  669. if (nc->receive_disabled) {
  670. return 0;
  671. }
  672. if (nc->info->type != NET_CLIENT_DRIVER_NIC ||
  673. qemu_get_nic(nc)->reentrancy_guard->engaged_in_io) {
  674. owned_reentrancy_guard = NULL;
  675. } else {
  676. owned_reentrancy_guard = qemu_get_nic(nc)->reentrancy_guard;
  677. owned_reentrancy_guard->engaged_in_io = true;
  678. }
  679. if ((flags & QEMU_NET_PACKET_FLAG_RAW) && nc->vnet_hdr_len) {
  680. iov_copy = g_new(struct iovec, iovcnt + 1);
  681. iov_copy[0].iov_base = &vnet_hdr;
  682. iov_copy[0].iov_len = nc->vnet_hdr_len;
  683. memcpy(&iov_copy[1], iov, iovcnt * sizeof(*iov));
  684. iov = iov_copy;
  685. }
  686. if (nc->info->receive_iov) {
  687. ret = nc->info->receive_iov(nc, iov, iovcnt);
  688. } else {
  689. ret = nc_sendv_compat(nc, iov, iovcnt, flags);
  690. }
  691. if (owned_reentrancy_guard) {
  692. owned_reentrancy_guard->engaged_in_io = false;
  693. }
  694. if (ret == 0) {
  695. nc->receive_disabled = 1;
  696. }
  697. return ret;
  698. }
  699. ssize_t qemu_sendv_packet_async(NetClientState *sender,
  700. const struct iovec *iov, int iovcnt,
  701. NetPacketSent *sent_cb)
  702. {
  703. NetQueue *queue;
  704. size_t size = iov_size(iov, iovcnt);
  705. int ret;
  706. if (size > NET_BUFSIZE) {
  707. return size;
  708. }
  709. if (sender->link_down || !sender->peer) {
  710. return size;
  711. }
  712. /* Let filters handle the packet first */
  713. ret = filter_receive_iov(sender, NET_FILTER_DIRECTION_TX, sender,
  714. QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
  715. if (ret) {
  716. return ret;
  717. }
  718. ret = filter_receive_iov(sender->peer, NET_FILTER_DIRECTION_RX, sender,
  719. QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
  720. if (ret) {
  721. return ret;
  722. }
  723. queue = sender->peer->incoming_queue;
  724. return qemu_net_queue_send_iov(queue, sender,
  725. QEMU_NET_PACKET_FLAG_NONE,
  726. iov, iovcnt, sent_cb);
  727. }
  728. ssize_t
  729. qemu_sendv_packet(NetClientState *nc, const struct iovec *iov, int iovcnt)
  730. {
  731. return qemu_sendv_packet_async(nc, iov, iovcnt, NULL);
  732. }
  733. NetClientState *qemu_find_netdev(const char *id)
  734. {
  735. NetClientState *nc;
  736. QTAILQ_FOREACH(nc, &net_clients, next) {
  737. if (nc->info->type == NET_CLIENT_DRIVER_NIC)
  738. continue;
  739. if (!strcmp(nc->name, id)) {
  740. return nc;
  741. }
  742. }
  743. return NULL;
  744. }
  745. int qemu_find_net_clients_except(const char *id, NetClientState **ncs,
  746. NetClientDriver type, int max)
  747. {
  748. NetClientState *nc;
  749. int ret = 0;
  750. QTAILQ_FOREACH(nc, &net_clients, next) {
  751. if (nc->info->type == type) {
  752. continue;
  753. }
  754. if (!id || !strcmp(nc->name, id)) {
  755. if (ret < max) {
  756. ncs[ret] = nc;
  757. }
  758. ret++;
  759. }
  760. }
  761. return ret;
  762. }
  763. static int nic_get_free_idx(void)
  764. {
  765. int index;
  766. for (index = 0; index < MAX_NICS; index++)
  767. if (!nd_table[index].used)
  768. return index;
  769. return -1;
  770. }
  771. GPtrArray *qemu_get_nic_models(const char *device_type)
  772. {
  773. GPtrArray *nic_models = g_ptr_array_new();
  774. GSList *list = object_class_get_list_sorted(device_type, false);
  775. while (list) {
  776. DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, list->data,
  777. TYPE_DEVICE);
  778. GSList *next;
  779. if (test_bit(DEVICE_CATEGORY_NETWORK, dc->categories) &&
  780. dc->user_creatable) {
  781. const char *name = object_class_get_name(list->data);
  782. /*
  783. * A network device might also be something else than a NIC, see
  784. * e.g. the "rocker" device. Thus we have to look for the "netdev"
  785. * property, too. Unfortunately, some devices like virtio-net only
  786. * create this property during instance_init, so we have to create
  787. * a temporary instance here to be able to check it.
  788. */
  789. Object *obj = object_new_with_class(OBJECT_CLASS(dc));
  790. if (object_property_find(obj, "netdev")) {
  791. g_ptr_array_add(nic_models, (gpointer)name);
  792. }
  793. object_unref(obj);
  794. }
  795. next = list->next;
  796. g_slist_free_1(list);
  797. list = next;
  798. }
  799. g_ptr_array_add(nic_models, NULL);
  800. return nic_models;
  801. }
  802. static int net_init_nic(const Netdev *netdev, const char *name,
  803. NetClientState *peer, Error **errp)
  804. {
  805. int idx;
  806. NICInfo *nd;
  807. const NetLegacyNicOptions *nic;
  808. assert(netdev->type == NET_CLIENT_DRIVER_NIC);
  809. nic = &netdev->u.nic;
  810. idx = nic_get_free_idx();
  811. if (idx == -1 || nb_nics >= MAX_NICS) {
  812. error_setg(errp, "too many NICs");
  813. return -1;
  814. }
  815. nd = &nd_table[idx];
  816. memset(nd, 0, sizeof(*nd));
  817. if (nic->netdev) {
  818. nd->netdev = qemu_find_netdev(nic->netdev);
  819. if (!nd->netdev) {
  820. error_setg(errp, "netdev '%s' not found", nic->netdev);
  821. return -1;
  822. }
  823. } else {
  824. assert(peer);
  825. nd->netdev = peer;
  826. }
  827. nd->name = g_strdup(name);
  828. if (nic->model) {
  829. nd->model = g_strdup(nic->model);
  830. }
  831. if (nic->addr) {
  832. nd->devaddr = g_strdup(nic->addr);
  833. }
  834. if (nic->macaddr &&
  835. net_parse_macaddr(nd->macaddr.a, nic->macaddr) < 0) {
  836. error_setg(errp, "invalid syntax for ethernet address");
  837. return -1;
  838. }
  839. if (nic->macaddr &&
  840. is_multicast_ether_addr(nd->macaddr.a)) {
  841. error_setg(errp,
  842. "NIC cannot have multicast MAC address (odd 1st byte)");
  843. return -1;
  844. }
  845. qemu_macaddr_default_if_unset(&nd->macaddr);
  846. if (nic->has_vectors) {
  847. if (nic->vectors > 0x7ffffff) {
  848. error_setg(errp, "invalid # of vectors: %"PRIu32, nic->vectors);
  849. return -1;
  850. }
  851. nd->nvectors = nic->vectors;
  852. } else {
  853. nd->nvectors = DEV_NVECTORS_UNSPECIFIED;
  854. }
  855. nd->used = 1;
  856. nb_nics++;
  857. return idx;
  858. }
  859. static gboolean add_nic_result(gpointer key, gpointer value, gpointer user_data)
  860. {
  861. GPtrArray *results = user_data;
  862. GPtrArray *alias_list = value;
  863. const char *model = key;
  864. char *result;
  865. if (!alias_list) {
  866. result = g_strdup(model);
  867. } else {
  868. GString *result_str = g_string_new(model);
  869. int i;
  870. g_string_append(result_str, " (aka ");
  871. for (i = 0; i < alias_list->len; i++) {
  872. if (i) {
  873. g_string_append(result_str, ", ");
  874. }
  875. g_string_append(result_str, alias_list->pdata[i]);
  876. }
  877. g_string_append(result_str, ")");
  878. result = result_str->str;
  879. g_string_free(result_str, false);
  880. g_ptr_array_unref(alias_list);
  881. }
  882. g_ptr_array_add(results, result);
  883. return true;
  884. }
  885. static int model_cmp(char **a, char **b)
  886. {
  887. return strcmp(*a, *b);
  888. }
  889. static void show_nic_models(void)
  890. {
  891. GPtrArray *results = g_ptr_array_new();
  892. int i;
  893. g_hash_table_foreach_remove(nic_model_help, add_nic_result, results);
  894. g_ptr_array_sort(results, (GCompareFunc)model_cmp);
  895. printf("Available NIC models for this configuration:\n");
  896. for (i = 0 ; i < results->len; i++) {
  897. printf("%s\n", (char *)results->pdata[i]);
  898. }
  899. g_hash_table_unref(nic_model_help);
  900. nic_model_help = NULL;
  901. }
  902. static void add_nic_model_help(const char *model, const char *alias)
  903. {
  904. GPtrArray *alias_list = NULL;
  905. if (g_hash_table_lookup_extended(nic_model_help, model, NULL,
  906. (gpointer *)&alias_list)) {
  907. /* Already exists, no alias to add: return */
  908. if (!alias) {
  909. return;
  910. }
  911. if (alias_list) {
  912. /* Check if this alias is already in the list. Add if not. */
  913. if (!g_ptr_array_find_with_equal_func(alias_list, alias,
  914. g_str_equal, NULL)) {
  915. g_ptr_array_add(alias_list, g_strdup(alias));
  916. }
  917. return;
  918. }
  919. }
  920. /* Either this model wasn't in the list already, or a first alias added */
  921. if (alias) {
  922. alias_list = g_ptr_array_new();
  923. g_ptr_array_set_free_func(alias_list, g_free);
  924. g_ptr_array_add(alias_list, g_strdup(alias));
  925. }
  926. g_hash_table_replace(nic_model_help, g_strdup(model), alias_list);
  927. }
  928. NICInfo *qemu_find_nic_info(const char *typename, bool match_default,
  929. const char *alias)
  930. {
  931. NICInfo *nd;
  932. int i;
  933. if (nic_model_help) {
  934. add_nic_model_help(typename, alias);
  935. }
  936. for (i = 0; i < nb_nics; i++) {
  937. nd = &nd_table[i];
  938. if (!nd->used || nd->instantiated) {
  939. continue;
  940. }
  941. if ((match_default && !nd->model) || !g_strcmp0(nd->model, typename)
  942. || (alias && !g_strcmp0(nd->model, alias))) {
  943. return nd;
  944. }
  945. }
  946. return NULL;
  947. }
  948. static bool is_nic_model_help_option(const char *model)
  949. {
  950. if (model && is_help_option(model)) {
  951. /*
  952. * Trigger the help output by instantiating the hash table which
  953. * will gather tha available models as they get registered.
  954. */
  955. if (!nic_model_help) {
  956. nic_model_help = g_hash_table_new_full(g_str_hash, g_str_equal,
  957. g_free, NULL);
  958. }
  959. return true;
  960. }
  961. return false;
  962. }
  963. /* "I have created a device. Please configure it if you can" */
  964. bool qemu_configure_nic_device(DeviceState *dev, bool match_default,
  965. const char *alias)
  966. {
  967. NICInfo *nd = qemu_find_nic_info(object_get_typename(OBJECT(dev)),
  968. match_default, alias);
  969. if (nd) {
  970. qdev_set_nic_properties(dev, nd);
  971. return true;
  972. }
  973. return false;
  974. }
  975. /* "Please create a device, if you have a configuration for it" */
  976. DeviceState *qemu_create_nic_device(const char *typename, bool match_default,
  977. const char *alias)
  978. {
  979. NICInfo *nd = qemu_find_nic_info(typename, match_default, alias);
  980. DeviceState *dev;
  981. if (!nd) {
  982. return NULL;
  983. }
  984. dev = qdev_new(typename);
  985. qdev_set_nic_properties(dev, nd);
  986. return dev;
  987. }
  988. void qemu_create_nic_bus_devices(BusState *bus, const char *parent_type,
  989. const char *default_model,
  990. const char *alias, const char *alias_target)
  991. {
  992. GPtrArray *nic_models = qemu_get_nic_models(parent_type);
  993. const char *model;
  994. DeviceState *dev;
  995. NICInfo *nd;
  996. int i;
  997. if (nic_model_help) {
  998. if (alias_target) {
  999. add_nic_model_help(alias_target, alias);
  1000. }
  1001. for (i = 0; i < nic_models->len - 1; i++) {
  1002. add_nic_model_help(nic_models->pdata[i], NULL);
  1003. }
  1004. }
  1005. /* Drop the NULL terminator which would make g_str_equal() unhappy */
  1006. nic_models->len--;
  1007. for (i = 0; i < nb_nics; i++) {
  1008. nd = &nd_table[i];
  1009. if (!nd->used || nd->instantiated) {
  1010. continue;
  1011. }
  1012. model = nd->model ? nd->model : default_model;
  1013. if (!model) {
  1014. continue;
  1015. }
  1016. /* Each bus type is allowed *one* substitution */
  1017. if (g_str_equal(model, alias)) {
  1018. model = alias_target;
  1019. }
  1020. if (!g_ptr_array_find_with_equal_func(nic_models, model,
  1021. g_str_equal, NULL)) {
  1022. /* This NIC does not live on this bus. */
  1023. continue;
  1024. }
  1025. dev = qdev_new(model);
  1026. qdev_set_nic_properties(dev, nd);
  1027. qdev_realize_and_unref(dev, bus, &error_fatal);
  1028. }
  1029. g_ptr_array_free(nic_models, true);
  1030. }
  1031. static int (* const net_client_init_fun[NET_CLIENT_DRIVER__MAX])(
  1032. const Netdev *netdev,
  1033. const char *name,
  1034. NetClientState *peer, Error **errp) = {
  1035. [NET_CLIENT_DRIVER_NIC] = net_init_nic,
  1036. #ifdef CONFIG_SLIRP
  1037. [NET_CLIENT_DRIVER_USER] = net_init_slirp,
  1038. #endif
  1039. [NET_CLIENT_DRIVER_TAP] = net_init_tap,
  1040. [NET_CLIENT_DRIVER_SOCKET] = net_init_socket,
  1041. [NET_CLIENT_DRIVER_STREAM] = net_init_stream,
  1042. [NET_CLIENT_DRIVER_DGRAM] = net_init_dgram,
  1043. #ifdef CONFIG_VDE
  1044. [NET_CLIENT_DRIVER_VDE] = net_init_vde,
  1045. #endif
  1046. #ifdef CONFIG_NETMAP
  1047. [NET_CLIENT_DRIVER_NETMAP] = net_init_netmap,
  1048. #endif
  1049. #ifdef CONFIG_AF_XDP
  1050. [NET_CLIENT_DRIVER_AF_XDP] = net_init_af_xdp,
  1051. #endif
  1052. #ifdef CONFIG_NET_BRIDGE
  1053. [NET_CLIENT_DRIVER_BRIDGE] = net_init_bridge,
  1054. #endif
  1055. [NET_CLIENT_DRIVER_HUBPORT] = net_init_hubport,
  1056. #ifdef CONFIG_VHOST_NET_USER
  1057. [NET_CLIENT_DRIVER_VHOST_USER] = net_init_vhost_user,
  1058. #endif
  1059. #ifdef CONFIG_VHOST_NET_VDPA
  1060. [NET_CLIENT_DRIVER_VHOST_VDPA] = net_init_vhost_vdpa,
  1061. #endif
  1062. #ifdef CONFIG_L2TPV3
  1063. [NET_CLIENT_DRIVER_L2TPV3] = net_init_l2tpv3,
  1064. #endif
  1065. #ifdef CONFIG_VMNET
  1066. [NET_CLIENT_DRIVER_VMNET_HOST] = net_init_vmnet_host,
  1067. [NET_CLIENT_DRIVER_VMNET_SHARED] = net_init_vmnet_shared,
  1068. [NET_CLIENT_DRIVER_VMNET_BRIDGED] = net_init_vmnet_bridged,
  1069. #endif /* CONFIG_VMNET */
  1070. };
  1071. static int net_client_init1(const Netdev *netdev, bool is_netdev, Error **errp)
  1072. {
  1073. NetClientState *peer = NULL;
  1074. NetClientState *nc;
  1075. if (is_netdev) {
  1076. if (netdev->type == NET_CLIENT_DRIVER_NIC ||
  1077. !net_client_init_fun[netdev->type]) {
  1078. error_setg(errp, "network backend '%s' is not compiled into this binary",
  1079. NetClientDriver_str(netdev->type));
  1080. return -1;
  1081. }
  1082. } else {
  1083. if (netdev->type == NET_CLIENT_DRIVER_NONE) {
  1084. return 0; /* nothing to do */
  1085. }
  1086. if (netdev->type == NET_CLIENT_DRIVER_HUBPORT) {
  1087. error_setg(errp, "network backend '%s' is only supported with -netdev/-nic",
  1088. NetClientDriver_str(netdev->type));
  1089. return -1;
  1090. }
  1091. if (!net_client_init_fun[netdev->type]) {
  1092. error_setg(errp, "network backend '%s' is not compiled into this binary",
  1093. NetClientDriver_str(netdev->type));
  1094. return -1;
  1095. }
  1096. /* Do not add to a hub if it's a nic with a netdev= parameter. */
  1097. if (netdev->type != NET_CLIENT_DRIVER_NIC ||
  1098. !netdev->u.nic.netdev) {
  1099. peer = net_hub_add_port(0, NULL, NULL);
  1100. }
  1101. }
  1102. nc = qemu_find_netdev(netdev->id);
  1103. if (nc) {
  1104. error_setg(errp, "Duplicate ID '%s'", netdev->id);
  1105. return -1;
  1106. }
  1107. if (net_client_init_fun[netdev->type](netdev, netdev->id, peer, errp) < 0) {
  1108. /* FIXME drop when all init functions store an Error */
  1109. if (errp && !*errp) {
  1110. error_setg(errp, "Device '%s' could not be initialized",
  1111. NetClientDriver_str(netdev->type));
  1112. }
  1113. return -1;
  1114. }
  1115. if (is_netdev) {
  1116. nc = qemu_find_netdev(netdev->id);
  1117. assert(nc);
  1118. nc->is_netdev = true;
  1119. }
  1120. return 0;
  1121. }
  1122. void show_netdevs(void)
  1123. {
  1124. int idx;
  1125. const char *available_netdevs[] = {
  1126. "socket",
  1127. "stream",
  1128. "dgram",
  1129. "hubport",
  1130. "tap",
  1131. #ifdef CONFIG_SLIRP
  1132. "user",
  1133. #endif
  1134. #ifdef CONFIG_L2TPV3
  1135. "l2tpv3",
  1136. #endif
  1137. #ifdef CONFIG_VDE
  1138. "vde",
  1139. #endif
  1140. #ifdef CONFIG_NET_BRIDGE
  1141. "bridge",
  1142. #endif
  1143. #ifdef CONFIG_NETMAP
  1144. "netmap",
  1145. #endif
  1146. #ifdef CONFIG_AF_XDP
  1147. "af-xdp",
  1148. #endif
  1149. #ifdef CONFIG_POSIX
  1150. "vhost-user",
  1151. #endif
  1152. #ifdef CONFIG_VHOST_VDPA
  1153. "vhost-vdpa",
  1154. #endif
  1155. #ifdef CONFIG_VMNET
  1156. "vmnet-host",
  1157. "vmnet-shared",
  1158. "vmnet-bridged",
  1159. #endif
  1160. };
  1161. qemu_printf("Available netdev backend types:\n");
  1162. for (idx = 0; idx < ARRAY_SIZE(available_netdevs); idx++) {
  1163. qemu_printf("%s\n", available_netdevs[idx]);
  1164. }
  1165. }
  1166. static int net_client_init(QemuOpts *opts, bool is_netdev, Error **errp)
  1167. {
  1168. gchar **substrings = NULL;
  1169. Netdev *object = NULL;
  1170. int ret = -1;
  1171. Visitor *v = opts_visitor_new(opts);
  1172. /* Parse convenience option format ipv6-net=fec0::0[/64] */
  1173. const char *ip6_net = qemu_opt_get(opts, "ipv6-net");
  1174. if (ip6_net) {
  1175. char *prefix_addr;
  1176. unsigned long prefix_len = 64; /* Default 64bit prefix length. */
  1177. substrings = g_strsplit(ip6_net, "/", 2);
  1178. if (!substrings || !substrings[0]) {
  1179. error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "ipv6-net",
  1180. "a valid IPv6 prefix");
  1181. goto out;
  1182. }
  1183. prefix_addr = substrings[0];
  1184. /* Handle user-specified prefix length. */
  1185. if (substrings[1] &&
  1186. qemu_strtoul(substrings[1], NULL, 10, &prefix_len))
  1187. {
  1188. error_setg(errp,
  1189. "parameter 'ipv6-net' expects a number after '/'");
  1190. goto out;
  1191. }
  1192. qemu_opt_set(opts, "ipv6-prefix", prefix_addr, &error_abort);
  1193. qemu_opt_set_number(opts, "ipv6-prefixlen", prefix_len,
  1194. &error_abort);
  1195. qemu_opt_unset(opts, "ipv6-net");
  1196. }
  1197. /* Create an ID for -net if the user did not specify one */
  1198. if (!is_netdev && !qemu_opts_id(opts)) {
  1199. qemu_opts_set_id(opts, id_generate(ID_NET));
  1200. }
  1201. if (visit_type_Netdev(v, NULL, &object, errp)) {
  1202. ret = net_client_init1(object, is_netdev, errp);
  1203. }
  1204. qapi_free_Netdev(object);
  1205. out:
  1206. g_strfreev(substrings);
  1207. visit_free(v);
  1208. return ret;
  1209. }
  1210. void netdev_add(QemuOpts *opts, Error **errp)
  1211. {
  1212. net_client_init(opts, true, errp);
  1213. }
  1214. void qmp_netdev_add(Netdev *netdev, Error **errp)
  1215. {
  1216. if (!id_wellformed(netdev->id)) {
  1217. error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "id", "an identifier");
  1218. return;
  1219. }
  1220. net_client_init1(netdev, true, errp);
  1221. }
  1222. void qmp_netdev_del(const char *id, Error **errp)
  1223. {
  1224. NetClientState *nc;
  1225. QemuOpts *opts;
  1226. nc = qemu_find_netdev(id);
  1227. if (!nc) {
  1228. error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
  1229. "Device '%s' not found", id);
  1230. return;
  1231. }
  1232. if (!nc->is_netdev) {
  1233. error_setg(errp, "Device '%s' is not a netdev", id);
  1234. return;
  1235. }
  1236. qemu_del_net_client(nc);
  1237. /*
  1238. * Wart: we need to delete the QemuOpts associated with netdevs
  1239. * created via CLI or HMP, to avoid bogus "Duplicate ID" errors in
  1240. * HMP netdev_add.
  1241. */
  1242. opts = qemu_opts_find(qemu_find_opts("netdev"), id);
  1243. if (opts) {
  1244. qemu_opts_del(opts);
  1245. }
  1246. }
  1247. static void netfilter_print_info(Monitor *mon, NetFilterState *nf)
  1248. {
  1249. char *str;
  1250. ObjectProperty *prop;
  1251. ObjectPropertyIterator iter;
  1252. Visitor *v;
  1253. /* generate info str */
  1254. object_property_iter_init(&iter, OBJECT(nf));
  1255. while ((prop = object_property_iter_next(&iter))) {
  1256. if (!strcmp(prop->name, "type")) {
  1257. continue;
  1258. }
  1259. v = string_output_visitor_new(false, &str);
  1260. object_property_get(OBJECT(nf), prop->name, v, NULL);
  1261. visit_complete(v, &str);
  1262. visit_free(v);
  1263. monitor_printf(mon, ",%s=%s", prop->name, str);
  1264. g_free(str);
  1265. }
  1266. monitor_printf(mon, "\n");
  1267. }
  1268. void print_net_client(Monitor *mon, NetClientState *nc)
  1269. {
  1270. NetFilterState *nf;
  1271. monitor_printf(mon, "%s: index=%d,type=%s,%s\n", nc->name,
  1272. nc->queue_index,
  1273. NetClientDriver_str(nc->info->type),
  1274. nc->info_str);
  1275. if (!QTAILQ_EMPTY(&nc->filters)) {
  1276. monitor_printf(mon, "filters:\n");
  1277. }
  1278. QTAILQ_FOREACH(nf, &nc->filters, next) {
  1279. monitor_printf(mon, " - %s: type=%s",
  1280. object_get_canonical_path_component(OBJECT(nf)),
  1281. object_get_typename(OBJECT(nf)));
  1282. netfilter_print_info(mon, nf);
  1283. }
  1284. }
  1285. RxFilterInfoList *qmp_query_rx_filter(const char *name, Error **errp)
  1286. {
  1287. NetClientState *nc;
  1288. RxFilterInfoList *filter_list = NULL, **tail = &filter_list;
  1289. QTAILQ_FOREACH(nc, &net_clients, next) {
  1290. RxFilterInfo *info;
  1291. if (name && strcmp(nc->name, name) != 0) {
  1292. continue;
  1293. }
  1294. /* only query rx-filter information of NIC */
  1295. if (nc->info->type != NET_CLIENT_DRIVER_NIC) {
  1296. if (name) {
  1297. error_setg(errp, "net client(%s) isn't a NIC", name);
  1298. assert(!filter_list);
  1299. return NULL;
  1300. }
  1301. continue;
  1302. }
  1303. /* only query information on queue 0 since the info is per nic,
  1304. * not per queue
  1305. */
  1306. if (nc->queue_index != 0)
  1307. continue;
  1308. if (nc->info->query_rx_filter) {
  1309. info = nc->info->query_rx_filter(nc);
  1310. QAPI_LIST_APPEND(tail, info);
  1311. } else if (name) {
  1312. error_setg(errp, "net client(%s) doesn't support"
  1313. " rx-filter querying", name);
  1314. assert(!filter_list);
  1315. return NULL;
  1316. }
  1317. if (name) {
  1318. break;
  1319. }
  1320. }
  1321. if (filter_list == NULL && name) {
  1322. error_setg(errp, "invalid net client name: %s", name);
  1323. }
  1324. return filter_list;
  1325. }
  1326. void colo_notify_filters_event(int event, Error **errp)
  1327. {
  1328. NetClientState *nc;
  1329. NetFilterState *nf;
  1330. NetFilterClass *nfc = NULL;
  1331. Error *local_err = NULL;
  1332. QTAILQ_FOREACH(nc, &net_clients, next) {
  1333. QTAILQ_FOREACH(nf, &nc->filters, next) {
  1334. nfc = NETFILTER_GET_CLASS(OBJECT(nf));
  1335. nfc->handle_event(nf, event, &local_err);
  1336. if (local_err) {
  1337. error_propagate(errp, local_err);
  1338. return;
  1339. }
  1340. }
  1341. }
  1342. }
  1343. void qmp_set_link(const char *name, bool up, Error **errp)
  1344. {
  1345. NetClientState *ncs[MAX_QUEUE_NUM];
  1346. NetClientState *nc;
  1347. int queues, i;
  1348. queues = qemu_find_net_clients_except(name, ncs,
  1349. NET_CLIENT_DRIVER__MAX,
  1350. MAX_QUEUE_NUM);
  1351. if (queues == 0) {
  1352. error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
  1353. "Device '%s' not found", name);
  1354. return;
  1355. }
  1356. nc = ncs[0];
  1357. for (i = 0; i < queues; i++) {
  1358. ncs[i]->link_down = !up;
  1359. }
  1360. if (nc->info->link_status_changed) {
  1361. nc->info->link_status_changed(nc);
  1362. }
  1363. if (nc->peer) {
  1364. /* Change peer link only if the peer is NIC and then notify peer.
  1365. * If the peer is a HUBPORT or a backend, we do not change the
  1366. * link status.
  1367. *
  1368. * This behavior is compatible with qemu hubs where there could be
  1369. * multiple clients that can still communicate with each other in
  1370. * disconnected mode. For now maintain this compatibility.
  1371. */
  1372. if (nc->peer->info->type == NET_CLIENT_DRIVER_NIC) {
  1373. for (i = 0; i < queues; i++) {
  1374. ncs[i]->peer->link_down = !up;
  1375. }
  1376. }
  1377. if (nc->peer->info->link_status_changed) {
  1378. nc->peer->info->link_status_changed(nc->peer);
  1379. }
  1380. }
  1381. }
  1382. static void net_vm_change_state_handler(void *opaque, bool running,
  1383. RunState state)
  1384. {
  1385. NetClientState *nc;
  1386. NetClientState *tmp;
  1387. QTAILQ_FOREACH_SAFE(nc, &net_clients, next, tmp) {
  1388. if (running) {
  1389. /* Flush queued packets and wake up backends. */
  1390. if (nc->peer && qemu_can_send_packet(nc)) {
  1391. qemu_flush_queued_packets(nc->peer);
  1392. }
  1393. } else {
  1394. /* Complete all queued packets, to guarantee we don't modify
  1395. * state later when VM is not running.
  1396. */
  1397. qemu_flush_or_purge_queued_packets(nc, true);
  1398. }
  1399. }
  1400. }
  1401. void net_cleanup(void)
  1402. {
  1403. NetClientState *nc, **p = &QTAILQ_FIRST(&net_clients);
  1404. /*cleanup colo compare module for COLO*/
  1405. colo_compare_cleanup();
  1406. /*
  1407. * Walk the net_clients list and remove the netdevs but *not* any
  1408. * NET_CLIENT_DRIVER_NIC entries. The latter are owned by the device
  1409. * model which created them, and in some cases (e.g. xen-net-device)
  1410. * the device itself may do cleanup at exit and will be upset if we
  1411. * just delete its NIC from underneath it.
  1412. *
  1413. * Since qemu_del_net_client() may delete multiple entries, using
  1414. * QTAILQ_FOREACH_SAFE() is not safe here. The only safe pointer
  1415. * to keep as a bookmark is a NET_CLIENT_DRIVER_NIC entry, so keep
  1416. * 'p' pointing to either the head of the list, or the 'next' field
  1417. * of the latest NET_CLIENT_DRIVER_NIC, and operate on *p as we walk
  1418. * the list.
  1419. *
  1420. * The 'nc' variable isn't part of the list traversal; it's purely
  1421. * for convenience as too much '(*p)->' has a tendency to make the
  1422. * readers' eyes bleed.
  1423. */
  1424. while (*p) {
  1425. nc = *p;
  1426. if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
  1427. /* Skip NET_CLIENT_DRIVER_NIC entries */
  1428. p = &QTAILQ_NEXT(nc, next);
  1429. } else {
  1430. qemu_del_net_client(nc);
  1431. }
  1432. }
  1433. qemu_del_vm_change_state_handler(net_change_state_entry);
  1434. }
  1435. void net_check_clients(void)
  1436. {
  1437. NetClientState *nc;
  1438. int i;
  1439. if (nic_model_help) {
  1440. show_nic_models();
  1441. exit(0);
  1442. }
  1443. net_hub_check_clients();
  1444. QTAILQ_FOREACH(nc, &net_clients, next) {
  1445. if (!nc->peer) {
  1446. warn_report("%s %s has no peer",
  1447. nc->info->type == NET_CLIENT_DRIVER_NIC
  1448. ? "nic" : "netdev",
  1449. nc->name);
  1450. }
  1451. }
  1452. /* Check that all NICs requested via -net nic actually got created.
  1453. * NICs created via -device don't need to be checked here because
  1454. * they are always instantiated.
  1455. */
  1456. for (i = 0; i < MAX_NICS; i++) {
  1457. NICInfo *nd = &nd_table[i];
  1458. if (nd->used && !nd->instantiated) {
  1459. warn_report("requested NIC (%s, model %s) "
  1460. "was not created (not supported by this machine?)",
  1461. nd->name ? nd->name : "anonymous",
  1462. nd->model ? nd->model : "unspecified");
  1463. }
  1464. }
  1465. }
  1466. static int net_init_client(void *dummy, QemuOpts *opts, Error **errp)
  1467. {
  1468. const char *model = qemu_opt_get(opts, "model");
  1469. if (is_nic_model_help_option(model)) {
  1470. return 0;
  1471. }
  1472. return net_client_init(opts, false, errp);
  1473. }
  1474. static int net_init_netdev(void *dummy, QemuOpts *opts, Error **errp)
  1475. {
  1476. const char *type = qemu_opt_get(opts, "type");
  1477. if (type && is_help_option(type)) {
  1478. show_netdevs();
  1479. exit(0);
  1480. }
  1481. return net_client_init(opts, true, errp);
  1482. }
  1483. /* For the convenience "--nic" parameter */
  1484. static int net_param_nic(void *dummy, QemuOpts *opts, Error **errp)
  1485. {
  1486. char *mac, *nd_id;
  1487. int idx, ret;
  1488. NICInfo *ni;
  1489. const char *type;
  1490. type = qemu_opt_get(opts, "type");
  1491. if (type) {
  1492. if (g_str_equal(type, "none")) {
  1493. return 0; /* Nothing to do, default_net is cleared in vl.c */
  1494. }
  1495. if (is_help_option(type)) {
  1496. GPtrArray *nic_models = qemu_get_nic_models(TYPE_DEVICE);
  1497. int i;
  1498. show_netdevs();
  1499. printf("\n");
  1500. printf("Available NIC models "
  1501. "(use -nic model=help for a filtered list):\n");
  1502. for (i = 0 ; nic_models->pdata[i]; i++) {
  1503. printf("%s\n", (char *)nic_models->pdata[i]);
  1504. }
  1505. g_ptr_array_free(nic_models, true);
  1506. exit(0);
  1507. }
  1508. }
  1509. idx = nic_get_free_idx();
  1510. if (idx == -1 || nb_nics >= MAX_NICS) {
  1511. error_setg(errp, "no more on-board/default NIC slots available");
  1512. return -1;
  1513. }
  1514. if (!type) {
  1515. qemu_opt_set(opts, "type", "user", &error_abort);
  1516. }
  1517. ni = &nd_table[idx];
  1518. memset(ni, 0, sizeof(*ni));
  1519. ni->model = qemu_opt_get_del(opts, "model");
  1520. if (is_nic_model_help_option(ni->model)) {
  1521. return 0;
  1522. }
  1523. /* Create an ID if the user did not specify one */
  1524. nd_id = g_strdup(qemu_opts_id(opts));
  1525. if (!nd_id) {
  1526. nd_id = id_generate(ID_NET);
  1527. qemu_opts_set_id(opts, nd_id);
  1528. }
  1529. /* Handle MAC address */
  1530. mac = qemu_opt_get_del(opts, "mac");
  1531. if (mac) {
  1532. ret = net_parse_macaddr(ni->macaddr.a, mac);
  1533. g_free(mac);
  1534. if (ret) {
  1535. error_setg(errp, "invalid syntax for ethernet address");
  1536. goto out;
  1537. }
  1538. if (is_multicast_ether_addr(ni->macaddr.a)) {
  1539. error_setg(errp, "NIC cannot have multicast MAC address");
  1540. ret = -1;
  1541. goto out;
  1542. }
  1543. }
  1544. qemu_macaddr_default_if_unset(&ni->macaddr);
  1545. ret = net_client_init(opts, true, errp);
  1546. if (ret == 0) {
  1547. ni->netdev = qemu_find_netdev(nd_id);
  1548. ni->used = true;
  1549. nb_nics++;
  1550. }
  1551. out:
  1552. g_free(nd_id);
  1553. return ret;
  1554. }
  1555. static void netdev_init_modern(void)
  1556. {
  1557. while (!QSIMPLEQ_EMPTY(&nd_queue)) {
  1558. NetdevQueueEntry *nd = QSIMPLEQ_FIRST(&nd_queue);
  1559. QSIMPLEQ_REMOVE_HEAD(&nd_queue, entry);
  1560. loc_push_restore(&nd->loc);
  1561. net_client_init1(nd->nd, true, &error_fatal);
  1562. loc_pop(&nd->loc);
  1563. qapi_free_Netdev(nd->nd);
  1564. g_free(nd);
  1565. }
  1566. }
  1567. void net_init_clients(void)
  1568. {
  1569. net_change_state_entry =
  1570. qemu_add_vm_change_state_handler(net_vm_change_state_handler, NULL);
  1571. QTAILQ_INIT(&net_clients);
  1572. netdev_init_modern();
  1573. qemu_opts_foreach(qemu_find_opts("netdev"), net_init_netdev, NULL,
  1574. &error_fatal);
  1575. qemu_opts_foreach(qemu_find_opts("nic"), net_param_nic, NULL,
  1576. &error_fatal);
  1577. qemu_opts_foreach(qemu_find_opts("net"), net_init_client, NULL,
  1578. &error_fatal);
  1579. }
  1580. /*
  1581. * Does this -netdev argument use modern rather than traditional syntax?
  1582. * Modern syntax is to be parsed with netdev_parse_modern().
  1583. * Traditional syntax is to be parsed with net_client_parse().
  1584. */
  1585. bool netdev_is_modern(const char *optstr)
  1586. {
  1587. QemuOpts *opts;
  1588. bool is_modern;
  1589. const char *type;
  1590. static QemuOptsList dummy_opts = {
  1591. .name = "netdev",
  1592. .implied_opt_name = "type",
  1593. .head = QTAILQ_HEAD_INITIALIZER(dummy_opts.head),
  1594. .desc = { { } },
  1595. };
  1596. if (optstr[0] == '{') {
  1597. /* This is JSON, which means it's modern syntax */
  1598. return true;
  1599. }
  1600. opts = qemu_opts_create(&dummy_opts, NULL, false, &error_abort);
  1601. qemu_opts_do_parse(opts, optstr, dummy_opts.implied_opt_name,
  1602. &error_abort);
  1603. type = qemu_opt_get(opts, "type");
  1604. is_modern = !g_strcmp0(type, "stream") || !g_strcmp0(type, "dgram");
  1605. qemu_opts_reset(&dummy_opts);
  1606. return is_modern;
  1607. }
  1608. /*
  1609. * netdev_parse_modern() uses modern, more expressive syntax than
  1610. * net_client_parse(), but supports only the -netdev option.
  1611. * netdev_parse_modern() appends to @nd_queue, whereas net_client_parse()
  1612. * appends to @qemu_netdev_opts.
  1613. */
  1614. void netdev_parse_modern(const char *optstr)
  1615. {
  1616. Visitor *v;
  1617. NetdevQueueEntry *nd;
  1618. v = qobject_input_visitor_new_str(optstr, "type", &error_fatal);
  1619. nd = g_new(NetdevQueueEntry, 1);
  1620. visit_type_Netdev(v, NULL, &nd->nd, &error_fatal);
  1621. visit_free(v);
  1622. loc_save(&nd->loc);
  1623. QSIMPLEQ_INSERT_TAIL(&nd_queue, nd, entry);
  1624. }
  1625. void net_client_parse(QemuOptsList *opts_list, const char *optstr)
  1626. {
  1627. if (!qemu_opts_parse_noisily(opts_list, optstr, true)) {
  1628. exit(1);
  1629. }
  1630. }
  1631. /* From FreeBSD */
  1632. /* XXX: optimize */
  1633. uint32_t net_crc32(const uint8_t *p, int len)
  1634. {
  1635. uint32_t crc;
  1636. int carry, i, j;
  1637. uint8_t b;
  1638. crc = 0xffffffff;
  1639. for (i = 0; i < len; i++) {
  1640. b = *p++;
  1641. for (j = 0; j < 8; j++) {
  1642. carry = ((crc & 0x80000000L) ? 1 : 0) ^ (b & 0x01);
  1643. crc <<= 1;
  1644. b >>= 1;
  1645. if (carry) {
  1646. crc = ((crc ^ POLYNOMIAL_BE) | carry);
  1647. }
  1648. }
  1649. }
  1650. return crc;
  1651. }
  1652. uint32_t net_crc32_le(const uint8_t *p, int len)
  1653. {
  1654. uint32_t crc;
  1655. int carry, i, j;
  1656. uint8_t b;
  1657. crc = 0xffffffff;
  1658. for (i = 0; i < len; i++) {
  1659. b = *p++;
  1660. for (j = 0; j < 8; j++) {
  1661. carry = (crc & 0x1) ^ (b & 0x01);
  1662. crc >>= 1;
  1663. b >>= 1;
  1664. if (carry) {
  1665. crc ^= POLYNOMIAL_LE;
  1666. }
  1667. }
  1668. }
  1669. return crc;
  1670. }
  1671. QemuOptsList qemu_netdev_opts = {
  1672. .name = "netdev",
  1673. .implied_opt_name = "type",
  1674. .head = QTAILQ_HEAD_INITIALIZER(qemu_netdev_opts.head),
  1675. .desc = {
  1676. /*
  1677. * no elements => accept any params
  1678. * validation will happen later
  1679. */
  1680. { /* end of list */ }
  1681. },
  1682. };
  1683. QemuOptsList qemu_nic_opts = {
  1684. .name = "nic",
  1685. .implied_opt_name = "type",
  1686. .head = QTAILQ_HEAD_INITIALIZER(qemu_nic_opts.head),
  1687. .desc = {
  1688. /*
  1689. * no elements => accept any params
  1690. * validation will happen later
  1691. */
  1692. { /* end of list */ }
  1693. },
  1694. };
  1695. QemuOptsList qemu_net_opts = {
  1696. .name = "net",
  1697. .implied_opt_name = "type",
  1698. .head = QTAILQ_HEAD_INITIALIZER(qemu_net_opts.head),
  1699. .desc = {
  1700. /*
  1701. * no elements => accept any params
  1702. * validation will happen later
  1703. */
  1704. { /* end of list */ }
  1705. },
  1706. };
  1707. void net_socket_rs_init(SocketReadState *rs,
  1708. SocketReadStateFinalize *finalize,
  1709. bool vnet_hdr)
  1710. {
  1711. rs->state = 0;
  1712. rs->vnet_hdr = vnet_hdr;
  1713. rs->index = 0;
  1714. rs->packet_len = 0;
  1715. rs->vnet_hdr_len = 0;
  1716. memset(rs->buf, 0, sizeof(rs->buf));
  1717. rs->finalize = finalize;
  1718. }
  1719. /*
  1720. * Returns
  1721. * 0: success
  1722. * -1: error occurs
  1723. */
  1724. int net_fill_rstate(SocketReadState *rs, const uint8_t *buf, int size)
  1725. {
  1726. unsigned int l;
  1727. while (size > 0) {
  1728. /* Reassemble a packet from the network.
  1729. * 0 = getting length.
  1730. * 1 = getting vnet header length.
  1731. * 2 = getting data.
  1732. */
  1733. switch (rs->state) {
  1734. case 0:
  1735. l = 4 - rs->index;
  1736. if (l > size) {
  1737. l = size;
  1738. }
  1739. memcpy(rs->buf + rs->index, buf, l);
  1740. buf += l;
  1741. size -= l;
  1742. rs->index += l;
  1743. if (rs->index == 4) {
  1744. /* got length */
  1745. rs->packet_len = ntohl(*(uint32_t *)rs->buf);
  1746. rs->index = 0;
  1747. if (rs->vnet_hdr) {
  1748. rs->state = 1;
  1749. } else {
  1750. rs->state = 2;
  1751. rs->vnet_hdr_len = 0;
  1752. }
  1753. }
  1754. break;
  1755. case 1:
  1756. l = 4 - rs->index;
  1757. if (l > size) {
  1758. l = size;
  1759. }
  1760. memcpy(rs->buf + rs->index, buf, l);
  1761. buf += l;
  1762. size -= l;
  1763. rs->index += l;
  1764. if (rs->index == 4) {
  1765. /* got vnet header length */
  1766. rs->vnet_hdr_len = ntohl(*(uint32_t *)rs->buf);
  1767. rs->index = 0;
  1768. rs->state = 2;
  1769. }
  1770. break;
  1771. case 2:
  1772. l = rs->packet_len - rs->index;
  1773. if (l > size) {
  1774. l = size;
  1775. }
  1776. if (rs->index + l <= sizeof(rs->buf)) {
  1777. memcpy(rs->buf + rs->index, buf, l);
  1778. } else {
  1779. fprintf(stderr, "serious error: oversized packet received,"
  1780. "connection terminated.\n");
  1781. rs->index = rs->state = 0;
  1782. return -1;
  1783. }
  1784. rs->index += l;
  1785. buf += l;
  1786. size -= l;
  1787. if (rs->index >= rs->packet_len) {
  1788. rs->index = 0;
  1789. rs->state = 0;
  1790. assert(rs->finalize);
  1791. rs->finalize(rs);
  1792. }
  1793. break;
  1794. }
  1795. }
  1796. assert(size == 0);
  1797. return 0;
  1798. }