net.c 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110
  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 "qobject/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 "system/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. if (!nc) {
  454. return 0;
  455. }
  456. return nc->vnet_hdr_len;
  457. }
  458. void qemu_set_vnet_hdr_len(NetClientState *nc, int len)
  459. {
  460. if (!nc || !nc->info->set_vnet_hdr_len) {
  461. return;
  462. }
  463. assert(len == sizeof(struct virtio_net_hdr_mrg_rxbuf) ||
  464. len == sizeof(struct virtio_net_hdr) ||
  465. len == sizeof(struct virtio_net_hdr_v1_hash));
  466. nc->vnet_hdr_len = len;
  467. nc->info->set_vnet_hdr_len(nc, len);
  468. }
  469. int qemu_set_vnet_le(NetClientState *nc, bool is_le)
  470. {
  471. #if HOST_BIG_ENDIAN
  472. if (!nc || !nc->info->set_vnet_le) {
  473. return -ENOSYS;
  474. }
  475. return nc->info->set_vnet_le(nc, is_le);
  476. #else
  477. return 0;
  478. #endif
  479. }
  480. int qemu_set_vnet_be(NetClientState *nc, bool is_be)
  481. {
  482. #if HOST_BIG_ENDIAN
  483. return 0;
  484. #else
  485. if (!nc || !nc->info->set_vnet_be) {
  486. return -ENOSYS;
  487. }
  488. return nc->info->set_vnet_be(nc, is_be);
  489. #endif
  490. }
  491. int qemu_can_receive_packet(NetClientState *nc)
  492. {
  493. if (nc->receive_disabled) {
  494. return 0;
  495. } else if (nc->info->can_receive &&
  496. !nc->info->can_receive(nc)) {
  497. return 0;
  498. }
  499. return 1;
  500. }
  501. int qemu_can_send_packet(NetClientState *sender)
  502. {
  503. int vm_running = runstate_is_running();
  504. if (!vm_running) {
  505. return 0;
  506. }
  507. if (!sender->peer) {
  508. return 1;
  509. }
  510. return qemu_can_receive_packet(sender->peer);
  511. }
  512. static ssize_t filter_receive_iov(NetClientState *nc,
  513. NetFilterDirection direction,
  514. NetClientState *sender,
  515. unsigned flags,
  516. const struct iovec *iov,
  517. int iovcnt,
  518. NetPacketSent *sent_cb)
  519. {
  520. ssize_t ret = 0;
  521. NetFilterState *nf = NULL;
  522. if (direction == NET_FILTER_DIRECTION_TX) {
  523. QTAILQ_FOREACH(nf, &nc->filters, next) {
  524. ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
  525. iovcnt, sent_cb);
  526. if (ret) {
  527. return ret;
  528. }
  529. }
  530. } else {
  531. QTAILQ_FOREACH_REVERSE(nf, &nc->filters, next) {
  532. ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
  533. iovcnt, sent_cb);
  534. if (ret) {
  535. return ret;
  536. }
  537. }
  538. }
  539. return ret;
  540. }
  541. static ssize_t filter_receive(NetClientState *nc,
  542. NetFilterDirection direction,
  543. NetClientState *sender,
  544. unsigned flags,
  545. const uint8_t *data,
  546. size_t size,
  547. NetPacketSent *sent_cb)
  548. {
  549. struct iovec iov = {
  550. .iov_base = (void *)data,
  551. .iov_len = size
  552. };
  553. return filter_receive_iov(nc, direction, sender, flags, &iov, 1, sent_cb);
  554. }
  555. void qemu_purge_queued_packets(NetClientState *nc)
  556. {
  557. if (!nc->peer) {
  558. return;
  559. }
  560. qemu_net_queue_purge(nc->peer->incoming_queue, nc);
  561. }
  562. void qemu_flush_or_purge_queued_packets(NetClientState *nc, bool purge)
  563. {
  564. nc->receive_disabled = 0;
  565. if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_HUBPORT) {
  566. if (net_hub_flush(nc->peer)) {
  567. qemu_notify_event();
  568. }
  569. }
  570. if (qemu_net_queue_flush(nc->incoming_queue)) {
  571. /* We emptied the queue successfully, signal to the IO thread to repoll
  572. * the file descriptor (for tap, for example).
  573. */
  574. qemu_notify_event();
  575. } else if (purge) {
  576. /* Unable to empty the queue, purge remaining packets */
  577. qemu_net_queue_purge(nc->incoming_queue, nc->peer);
  578. }
  579. }
  580. void qemu_flush_queued_packets(NetClientState *nc)
  581. {
  582. qemu_flush_or_purge_queued_packets(nc, false);
  583. }
  584. static ssize_t qemu_send_packet_async_with_flags(NetClientState *sender,
  585. unsigned flags,
  586. const uint8_t *buf, int size,
  587. NetPacketSent *sent_cb)
  588. {
  589. NetQueue *queue;
  590. int ret;
  591. #ifdef DEBUG_NET
  592. printf("qemu_send_packet_async:\n");
  593. qemu_hexdump(stdout, "net", buf, size);
  594. #endif
  595. if (sender->link_down || !sender->peer) {
  596. return size;
  597. }
  598. /* Let filters handle the packet first */
  599. ret = filter_receive(sender, NET_FILTER_DIRECTION_TX,
  600. sender, flags, buf, size, sent_cb);
  601. if (ret) {
  602. return ret;
  603. }
  604. ret = filter_receive(sender->peer, NET_FILTER_DIRECTION_RX,
  605. sender, flags, buf, size, sent_cb);
  606. if (ret) {
  607. return ret;
  608. }
  609. queue = sender->peer->incoming_queue;
  610. return qemu_net_queue_send(queue, sender, flags, buf, size, sent_cb);
  611. }
  612. ssize_t qemu_send_packet_async(NetClientState *sender,
  613. const uint8_t *buf, int size,
  614. NetPacketSent *sent_cb)
  615. {
  616. return qemu_send_packet_async_with_flags(sender, QEMU_NET_PACKET_FLAG_NONE,
  617. buf, size, sent_cb);
  618. }
  619. ssize_t qemu_send_packet(NetClientState *nc, const uint8_t *buf, int size)
  620. {
  621. return qemu_send_packet_async(nc, buf, size, NULL);
  622. }
  623. ssize_t qemu_receive_packet(NetClientState *nc, const uint8_t *buf, int size)
  624. {
  625. if (!qemu_can_receive_packet(nc)) {
  626. return 0;
  627. }
  628. return qemu_net_queue_receive(nc->incoming_queue, buf, size);
  629. }
  630. ssize_t qemu_send_packet_raw(NetClientState *nc, const uint8_t *buf, int size)
  631. {
  632. return qemu_send_packet_async_with_flags(nc, QEMU_NET_PACKET_FLAG_RAW,
  633. buf, size, NULL);
  634. }
  635. static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov,
  636. int iovcnt, unsigned flags)
  637. {
  638. uint8_t *buf = NULL;
  639. uint8_t *buffer;
  640. size_t offset;
  641. ssize_t ret;
  642. if (iovcnt == 1) {
  643. buffer = iov[0].iov_base;
  644. offset = iov[0].iov_len;
  645. } else {
  646. offset = iov_size(iov, iovcnt);
  647. if (offset > NET_BUFSIZE) {
  648. return -1;
  649. }
  650. buf = g_malloc(offset);
  651. buffer = buf;
  652. offset = iov_to_buf(iov, iovcnt, 0, buf, offset);
  653. }
  654. ret = nc->info->receive(nc, buffer, offset);
  655. g_free(buf);
  656. return ret;
  657. }
  658. static ssize_t qemu_deliver_packet_iov(NetClientState *sender,
  659. unsigned flags,
  660. const struct iovec *iov,
  661. int iovcnt,
  662. void *opaque)
  663. {
  664. MemReentrancyGuard *owned_reentrancy_guard;
  665. NetClientState *nc = opaque;
  666. int ret;
  667. struct virtio_net_hdr_v1_hash vnet_hdr = { };
  668. g_autofree struct iovec *iov_copy = NULL;
  669. if (nc->link_down) {
  670. return iov_size(iov, iovcnt);
  671. }
  672. if (nc->receive_disabled) {
  673. return 0;
  674. }
  675. if (nc->info->type != NET_CLIENT_DRIVER_NIC ||
  676. qemu_get_nic(nc)->reentrancy_guard->engaged_in_io) {
  677. owned_reentrancy_guard = NULL;
  678. } else {
  679. owned_reentrancy_guard = qemu_get_nic(nc)->reentrancy_guard;
  680. owned_reentrancy_guard->engaged_in_io = true;
  681. }
  682. if ((flags & QEMU_NET_PACKET_FLAG_RAW) && nc->vnet_hdr_len) {
  683. iov_copy = g_new(struct iovec, iovcnt + 1);
  684. iov_copy[0].iov_base = &vnet_hdr;
  685. iov_copy[0].iov_len = nc->vnet_hdr_len;
  686. memcpy(&iov_copy[1], iov, iovcnt * sizeof(*iov));
  687. iov = iov_copy;
  688. iovcnt++;
  689. }
  690. if (nc->info->receive_iov) {
  691. ret = nc->info->receive_iov(nc, iov, iovcnt);
  692. } else {
  693. ret = nc_sendv_compat(nc, iov, iovcnt, flags);
  694. }
  695. if (owned_reentrancy_guard) {
  696. owned_reentrancy_guard->engaged_in_io = false;
  697. }
  698. if (ret == 0) {
  699. nc->receive_disabled = 1;
  700. }
  701. return ret;
  702. }
  703. ssize_t qemu_sendv_packet_async(NetClientState *sender,
  704. const struct iovec *iov, int iovcnt,
  705. NetPacketSent *sent_cb)
  706. {
  707. NetQueue *queue;
  708. size_t size = iov_size(iov, iovcnt);
  709. int ret;
  710. if (size > NET_BUFSIZE) {
  711. return size;
  712. }
  713. if (sender->link_down || !sender->peer) {
  714. return size;
  715. }
  716. /* Let filters handle the packet first */
  717. ret = filter_receive_iov(sender, NET_FILTER_DIRECTION_TX, sender,
  718. QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
  719. if (ret) {
  720. return ret;
  721. }
  722. ret = filter_receive_iov(sender->peer, NET_FILTER_DIRECTION_RX, sender,
  723. QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
  724. if (ret) {
  725. return ret;
  726. }
  727. queue = sender->peer->incoming_queue;
  728. return qemu_net_queue_send_iov(queue, sender,
  729. QEMU_NET_PACKET_FLAG_NONE,
  730. iov, iovcnt, sent_cb);
  731. }
  732. ssize_t
  733. qemu_sendv_packet(NetClientState *nc, const struct iovec *iov, int iovcnt)
  734. {
  735. return qemu_sendv_packet_async(nc, iov, iovcnt, NULL);
  736. }
  737. NetClientState *qemu_find_netdev(const char *id)
  738. {
  739. NetClientState *nc;
  740. QTAILQ_FOREACH(nc, &net_clients, next) {
  741. if (nc->info->type == NET_CLIENT_DRIVER_NIC)
  742. continue;
  743. if (!strcmp(nc->name, id)) {
  744. return nc;
  745. }
  746. }
  747. return NULL;
  748. }
  749. int qemu_find_net_clients_except(const char *id, NetClientState **ncs,
  750. NetClientDriver type, int max)
  751. {
  752. NetClientState *nc;
  753. int ret = 0;
  754. QTAILQ_FOREACH(nc, &net_clients, next) {
  755. if (nc->info->type == type) {
  756. continue;
  757. }
  758. if (!id || !strcmp(nc->name, id)) {
  759. if (ret < max) {
  760. ncs[ret] = nc;
  761. }
  762. ret++;
  763. }
  764. }
  765. return ret;
  766. }
  767. static int nic_get_free_idx(void)
  768. {
  769. int index;
  770. for (index = 0; index < MAX_NICS; index++)
  771. if (!nd_table[index].used)
  772. return index;
  773. return -1;
  774. }
  775. GPtrArray *qemu_get_nic_models(const char *device_type)
  776. {
  777. GPtrArray *nic_models = g_ptr_array_new();
  778. GSList *list = object_class_get_list_sorted(device_type, false);
  779. while (list) {
  780. DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, list->data,
  781. TYPE_DEVICE);
  782. GSList *next;
  783. if (test_bit(DEVICE_CATEGORY_NETWORK, dc->categories) &&
  784. dc->user_creatable) {
  785. const char *name = object_class_get_name(list->data);
  786. /*
  787. * A network device might also be something else than a NIC, see
  788. * e.g. the "rocker" device. Thus we have to look for the "netdev"
  789. * property, too. Unfortunately, some devices like virtio-net only
  790. * create this property during instance_init, so we have to create
  791. * a temporary instance here to be able to check it.
  792. */
  793. Object *obj = object_new_with_class(OBJECT_CLASS(dc));
  794. if (object_property_find(obj, "netdev")) {
  795. g_ptr_array_add(nic_models, (gpointer)name);
  796. }
  797. object_unref(obj);
  798. }
  799. next = list->next;
  800. g_slist_free_1(list);
  801. list = next;
  802. }
  803. g_ptr_array_add(nic_models, NULL);
  804. return nic_models;
  805. }
  806. static int net_init_nic(const Netdev *netdev, const char *name,
  807. NetClientState *peer, Error **errp)
  808. {
  809. int idx;
  810. NICInfo *nd;
  811. const NetLegacyNicOptions *nic;
  812. assert(netdev->type == NET_CLIENT_DRIVER_NIC);
  813. nic = &netdev->u.nic;
  814. idx = nic_get_free_idx();
  815. if (idx == -1 || nb_nics >= MAX_NICS) {
  816. error_setg(errp, "too many NICs");
  817. return -1;
  818. }
  819. nd = &nd_table[idx];
  820. memset(nd, 0, sizeof(*nd));
  821. if (nic->netdev) {
  822. nd->netdev = qemu_find_netdev(nic->netdev);
  823. if (!nd->netdev) {
  824. error_setg(errp, "netdev '%s' not found", nic->netdev);
  825. return -1;
  826. }
  827. } else {
  828. assert(peer);
  829. nd->netdev = peer;
  830. }
  831. nd->name = g_strdup(name);
  832. if (nic->model) {
  833. nd->model = g_strdup(nic->model);
  834. }
  835. if (nic->addr) {
  836. nd->devaddr = g_strdup(nic->addr);
  837. }
  838. if (nic->macaddr &&
  839. net_parse_macaddr(nd->macaddr.a, nic->macaddr) < 0) {
  840. error_setg(errp, "invalid syntax for ethernet address");
  841. return -1;
  842. }
  843. if (nic->macaddr &&
  844. is_multicast_ether_addr(nd->macaddr.a)) {
  845. error_setg(errp,
  846. "NIC cannot have multicast MAC address (odd 1st byte)");
  847. return -1;
  848. }
  849. qemu_macaddr_default_if_unset(&nd->macaddr);
  850. if (nic->has_vectors) {
  851. if (nic->vectors > 0x7ffffff) {
  852. error_setg(errp, "invalid # of vectors: %"PRIu32, nic->vectors);
  853. return -1;
  854. }
  855. nd->nvectors = nic->vectors;
  856. } else {
  857. nd->nvectors = DEV_NVECTORS_UNSPECIFIED;
  858. }
  859. nd->used = 1;
  860. nb_nics++;
  861. return idx;
  862. }
  863. static gboolean add_nic_result(gpointer key, gpointer value, gpointer user_data)
  864. {
  865. GPtrArray *results = user_data;
  866. GPtrArray *alias_list = value;
  867. const char *model = key;
  868. char *result;
  869. if (!alias_list) {
  870. result = g_strdup(model);
  871. } else {
  872. GString *result_str = g_string_new(model);
  873. int i;
  874. g_string_append(result_str, " (aka ");
  875. for (i = 0; i < alias_list->len; i++) {
  876. if (i) {
  877. g_string_append(result_str, ", ");
  878. }
  879. g_string_append(result_str, alias_list->pdata[i]);
  880. }
  881. g_string_append(result_str, ")");
  882. result = result_str->str;
  883. g_string_free(result_str, false);
  884. g_ptr_array_unref(alias_list);
  885. }
  886. g_ptr_array_add(results, result);
  887. return true;
  888. }
  889. static int model_cmp(char **a, char **b)
  890. {
  891. return strcmp(*a, *b);
  892. }
  893. static void show_nic_models(void)
  894. {
  895. GPtrArray *results = g_ptr_array_new();
  896. int i;
  897. g_hash_table_foreach_remove(nic_model_help, add_nic_result, results);
  898. g_ptr_array_sort(results, (GCompareFunc)model_cmp);
  899. printf("Available NIC models for this configuration:\n");
  900. for (i = 0 ; i < results->len; i++) {
  901. printf("%s\n", (char *)results->pdata[i]);
  902. }
  903. g_hash_table_unref(nic_model_help);
  904. nic_model_help = NULL;
  905. }
  906. static void add_nic_model_help(const char *model, const char *alias)
  907. {
  908. GPtrArray *alias_list = NULL;
  909. if (g_hash_table_lookup_extended(nic_model_help, model, NULL,
  910. (gpointer *)&alias_list)) {
  911. /* Already exists, no alias to add: return */
  912. if (!alias) {
  913. return;
  914. }
  915. if (alias_list) {
  916. /* Check if this alias is already in the list. Add if not. */
  917. if (!g_ptr_array_find_with_equal_func(alias_list, alias,
  918. g_str_equal, NULL)) {
  919. g_ptr_array_add(alias_list, g_strdup(alias));
  920. }
  921. return;
  922. }
  923. }
  924. /* Either this model wasn't in the list already, or a first alias added */
  925. if (alias) {
  926. alias_list = g_ptr_array_new();
  927. g_ptr_array_set_free_func(alias_list, g_free);
  928. g_ptr_array_add(alias_list, g_strdup(alias));
  929. }
  930. g_hash_table_replace(nic_model_help, g_strdup(model), alias_list);
  931. }
  932. NICInfo *qemu_find_nic_info(const char *typename, bool match_default,
  933. const char *alias)
  934. {
  935. NICInfo *nd;
  936. int i;
  937. if (nic_model_help) {
  938. add_nic_model_help(typename, alias);
  939. }
  940. for (i = 0; i < nb_nics; i++) {
  941. nd = &nd_table[i];
  942. if (!nd->used || nd->instantiated) {
  943. continue;
  944. }
  945. if ((match_default && !nd->model) || !g_strcmp0(nd->model, typename)
  946. || (alias && !g_strcmp0(nd->model, alias))) {
  947. return nd;
  948. }
  949. }
  950. return NULL;
  951. }
  952. static bool is_nic_model_help_option(const char *model)
  953. {
  954. if (model && is_help_option(model)) {
  955. /*
  956. * Trigger the help output by instantiating the hash table which
  957. * will gather tha available models as they get registered.
  958. */
  959. if (!nic_model_help) {
  960. nic_model_help = g_hash_table_new_full(g_str_hash, g_str_equal,
  961. g_free, NULL);
  962. }
  963. return true;
  964. }
  965. return false;
  966. }
  967. /* "I have created a device. Please configure it if you can" */
  968. bool qemu_configure_nic_device(DeviceState *dev, bool match_default,
  969. const char *alias)
  970. {
  971. NICInfo *nd = qemu_find_nic_info(object_get_typename(OBJECT(dev)),
  972. match_default, alias);
  973. if (nd) {
  974. qdev_set_nic_properties(dev, nd);
  975. return true;
  976. }
  977. return false;
  978. }
  979. /* "Please create a device, if you have a configuration for it" */
  980. DeviceState *qemu_create_nic_device(const char *typename, bool match_default,
  981. const char *alias)
  982. {
  983. NICInfo *nd = qemu_find_nic_info(typename, match_default, alias);
  984. DeviceState *dev;
  985. if (!nd) {
  986. return NULL;
  987. }
  988. dev = qdev_new(typename);
  989. qdev_set_nic_properties(dev, nd);
  990. return dev;
  991. }
  992. void qemu_create_nic_bus_devices(BusState *bus, const char *parent_type,
  993. const char *default_model,
  994. const char *alias, const char *alias_target)
  995. {
  996. GPtrArray *nic_models = qemu_get_nic_models(parent_type);
  997. const char *model;
  998. DeviceState *dev;
  999. NICInfo *nd;
  1000. int i;
  1001. if (nic_model_help) {
  1002. if (alias_target) {
  1003. add_nic_model_help(alias_target, alias);
  1004. }
  1005. for (i = 0; i < nic_models->len - 1; i++) {
  1006. add_nic_model_help(nic_models->pdata[i], NULL);
  1007. }
  1008. }
  1009. /* Drop the NULL terminator which would make g_str_equal() unhappy */
  1010. nic_models->len--;
  1011. for (i = 0; i < nb_nics; i++) {
  1012. nd = &nd_table[i];
  1013. if (!nd->used || nd->instantiated) {
  1014. continue;
  1015. }
  1016. model = nd->model ? nd->model : default_model;
  1017. if (!model) {
  1018. continue;
  1019. }
  1020. /* Each bus type is allowed *one* substitution */
  1021. if (g_str_equal(model, alias)) {
  1022. model = alias_target;
  1023. }
  1024. if (!g_ptr_array_find_with_equal_func(nic_models, model,
  1025. g_str_equal, NULL)) {
  1026. /* This NIC does not live on this bus. */
  1027. continue;
  1028. }
  1029. dev = qdev_new(model);
  1030. qdev_set_nic_properties(dev, nd);
  1031. qdev_realize_and_unref(dev, bus, &error_fatal);
  1032. }
  1033. g_ptr_array_free(nic_models, true);
  1034. }
  1035. static int (* const net_client_init_fun[NET_CLIENT_DRIVER__MAX])(
  1036. const Netdev *netdev,
  1037. const char *name,
  1038. NetClientState *peer, Error **errp) = {
  1039. [NET_CLIENT_DRIVER_NIC] = net_init_nic,
  1040. #ifdef CONFIG_SLIRP
  1041. [NET_CLIENT_DRIVER_USER] = net_init_slirp,
  1042. #endif
  1043. [NET_CLIENT_DRIVER_TAP] = net_init_tap,
  1044. [NET_CLIENT_DRIVER_SOCKET] = net_init_socket,
  1045. [NET_CLIENT_DRIVER_STREAM] = net_init_stream,
  1046. [NET_CLIENT_DRIVER_DGRAM] = net_init_dgram,
  1047. #ifdef CONFIG_VDE
  1048. [NET_CLIENT_DRIVER_VDE] = net_init_vde,
  1049. #endif
  1050. #ifdef CONFIG_NETMAP
  1051. [NET_CLIENT_DRIVER_NETMAP] = net_init_netmap,
  1052. #endif
  1053. #ifdef CONFIG_AF_XDP
  1054. [NET_CLIENT_DRIVER_AF_XDP] = net_init_af_xdp,
  1055. #endif
  1056. #ifdef CONFIG_NET_BRIDGE
  1057. [NET_CLIENT_DRIVER_BRIDGE] = net_init_bridge,
  1058. #endif
  1059. [NET_CLIENT_DRIVER_HUBPORT] = net_init_hubport,
  1060. #ifdef CONFIG_VHOST_NET_USER
  1061. [NET_CLIENT_DRIVER_VHOST_USER] = net_init_vhost_user,
  1062. #endif
  1063. #ifdef CONFIG_VHOST_NET_VDPA
  1064. [NET_CLIENT_DRIVER_VHOST_VDPA] = net_init_vhost_vdpa,
  1065. #endif
  1066. #ifdef CONFIG_L2TPV3
  1067. [NET_CLIENT_DRIVER_L2TPV3] = net_init_l2tpv3,
  1068. #endif
  1069. #ifdef CONFIG_VMNET
  1070. [NET_CLIENT_DRIVER_VMNET_HOST] = net_init_vmnet_host,
  1071. [NET_CLIENT_DRIVER_VMNET_SHARED] = net_init_vmnet_shared,
  1072. [NET_CLIENT_DRIVER_VMNET_BRIDGED] = net_init_vmnet_bridged,
  1073. #endif /* CONFIG_VMNET */
  1074. };
  1075. static int net_client_init1(const Netdev *netdev, bool is_netdev, Error **errp)
  1076. {
  1077. NetClientState *peer = NULL;
  1078. NetClientState *nc;
  1079. if (is_netdev) {
  1080. if (netdev->type == NET_CLIENT_DRIVER_NIC ||
  1081. !net_client_init_fun[netdev->type]) {
  1082. error_setg(errp, "network backend '%s' is not compiled into this binary",
  1083. NetClientDriver_str(netdev->type));
  1084. return -1;
  1085. }
  1086. } else {
  1087. if (netdev->type == NET_CLIENT_DRIVER_NONE) {
  1088. return 0; /* nothing to do */
  1089. }
  1090. if (netdev->type == NET_CLIENT_DRIVER_HUBPORT) {
  1091. error_setg(errp, "network backend '%s' is only supported with -netdev/-nic",
  1092. NetClientDriver_str(netdev->type));
  1093. return -1;
  1094. }
  1095. if (!net_client_init_fun[netdev->type]) {
  1096. error_setg(errp, "network backend '%s' is not compiled into this binary",
  1097. NetClientDriver_str(netdev->type));
  1098. return -1;
  1099. }
  1100. /* Do not add to a hub if it's a nic with a netdev= parameter. */
  1101. if (netdev->type != NET_CLIENT_DRIVER_NIC ||
  1102. !netdev->u.nic.netdev) {
  1103. peer = net_hub_add_port(0, NULL, NULL);
  1104. }
  1105. }
  1106. nc = qemu_find_netdev(netdev->id);
  1107. if (nc) {
  1108. error_setg(errp, "Duplicate ID '%s'", netdev->id);
  1109. return -1;
  1110. }
  1111. if (net_client_init_fun[netdev->type](netdev, netdev->id, peer, errp) < 0) {
  1112. /* FIXME drop when all init functions store an Error */
  1113. if (errp && !*errp) {
  1114. error_setg(errp, "Device '%s' could not be initialized",
  1115. NetClientDriver_str(netdev->type));
  1116. }
  1117. return -1;
  1118. }
  1119. if (is_netdev) {
  1120. nc = qemu_find_netdev(netdev->id);
  1121. assert(nc);
  1122. nc->is_netdev = true;
  1123. }
  1124. return 0;
  1125. }
  1126. void show_netdevs(void)
  1127. {
  1128. int idx;
  1129. const char *available_netdevs[] = {
  1130. "socket",
  1131. "stream",
  1132. "dgram",
  1133. "hubport",
  1134. "tap",
  1135. #ifdef CONFIG_SLIRP
  1136. "user",
  1137. #endif
  1138. #ifdef CONFIG_L2TPV3
  1139. "l2tpv3",
  1140. #endif
  1141. #ifdef CONFIG_VDE
  1142. "vde",
  1143. #endif
  1144. #ifdef CONFIG_NET_BRIDGE
  1145. "bridge",
  1146. #endif
  1147. #ifdef CONFIG_NETMAP
  1148. "netmap",
  1149. #endif
  1150. #ifdef CONFIG_AF_XDP
  1151. "af-xdp",
  1152. #endif
  1153. #ifdef CONFIG_POSIX
  1154. "vhost-user",
  1155. #endif
  1156. #ifdef CONFIG_VHOST_VDPA
  1157. "vhost-vdpa",
  1158. #endif
  1159. #ifdef CONFIG_VMNET
  1160. "vmnet-host",
  1161. "vmnet-shared",
  1162. "vmnet-bridged",
  1163. #endif
  1164. };
  1165. qemu_printf("Available netdev backend types:\n");
  1166. for (idx = 0; idx < ARRAY_SIZE(available_netdevs); idx++) {
  1167. qemu_printf("%s\n", available_netdevs[idx]);
  1168. }
  1169. }
  1170. static int net_client_init(QemuOpts *opts, bool is_netdev, Error **errp)
  1171. {
  1172. gchar **substrings = NULL;
  1173. Netdev *object = NULL;
  1174. int ret = -1;
  1175. Visitor *v = opts_visitor_new(opts);
  1176. /* Parse convenience option format ipv6-net=fec0::0[/64] */
  1177. const char *ip6_net = qemu_opt_get(opts, "ipv6-net");
  1178. if (ip6_net) {
  1179. char *prefix_addr;
  1180. unsigned long prefix_len = 64; /* Default 64bit prefix length. */
  1181. substrings = g_strsplit(ip6_net, "/", 2);
  1182. if (!substrings || !substrings[0]) {
  1183. error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "ipv6-net",
  1184. "a valid IPv6 prefix");
  1185. goto out;
  1186. }
  1187. prefix_addr = substrings[0];
  1188. /* Handle user-specified prefix length. */
  1189. if (substrings[1] &&
  1190. qemu_strtoul(substrings[1], NULL, 10, &prefix_len))
  1191. {
  1192. error_setg(errp,
  1193. "parameter 'ipv6-net' expects a number after '/'");
  1194. goto out;
  1195. }
  1196. qemu_opt_set(opts, "ipv6-prefix", prefix_addr, &error_abort);
  1197. qemu_opt_set_number(opts, "ipv6-prefixlen", prefix_len,
  1198. &error_abort);
  1199. qemu_opt_unset(opts, "ipv6-net");
  1200. }
  1201. /* Create an ID for -net if the user did not specify one */
  1202. if (!is_netdev && !qemu_opts_id(opts)) {
  1203. qemu_opts_set_id(opts, id_generate(ID_NET));
  1204. }
  1205. if (visit_type_Netdev(v, NULL, &object, errp)) {
  1206. ret = net_client_init1(object, is_netdev, errp);
  1207. }
  1208. qapi_free_Netdev(object);
  1209. out:
  1210. g_strfreev(substrings);
  1211. visit_free(v);
  1212. return ret;
  1213. }
  1214. void netdev_add(QemuOpts *opts, Error **errp)
  1215. {
  1216. net_client_init(opts, true, errp);
  1217. }
  1218. void qmp_netdev_add(Netdev *netdev, Error **errp)
  1219. {
  1220. if (!id_wellformed(netdev->id)) {
  1221. error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "id", "an identifier");
  1222. return;
  1223. }
  1224. net_client_init1(netdev, true, errp);
  1225. }
  1226. void qmp_netdev_del(const char *id, Error **errp)
  1227. {
  1228. NetClientState *nc;
  1229. QemuOpts *opts;
  1230. nc = qemu_find_netdev(id);
  1231. if (!nc) {
  1232. error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
  1233. "Device '%s' not found", id);
  1234. return;
  1235. }
  1236. if (!nc->is_netdev) {
  1237. error_setg(errp, "Device '%s' is not a netdev", id);
  1238. return;
  1239. }
  1240. qemu_del_net_client(nc);
  1241. /*
  1242. * Wart: we need to delete the QemuOpts associated with netdevs
  1243. * created via CLI or HMP, to avoid bogus "Duplicate ID" errors in
  1244. * HMP netdev_add.
  1245. */
  1246. opts = qemu_opts_find(qemu_find_opts("netdev"), id);
  1247. if (opts) {
  1248. qemu_opts_del(opts);
  1249. }
  1250. }
  1251. static void netfilter_print_info(Monitor *mon, NetFilterState *nf)
  1252. {
  1253. char *str;
  1254. ObjectProperty *prop;
  1255. ObjectPropertyIterator iter;
  1256. Visitor *v;
  1257. /* generate info str */
  1258. object_property_iter_init(&iter, OBJECT(nf));
  1259. while ((prop = object_property_iter_next(&iter))) {
  1260. if (!strcmp(prop->name, "type")) {
  1261. continue;
  1262. }
  1263. v = string_output_visitor_new(false, &str);
  1264. object_property_get(OBJECT(nf), prop->name, v, NULL);
  1265. visit_complete(v, &str);
  1266. visit_free(v);
  1267. monitor_printf(mon, ",%s=%s", prop->name, str);
  1268. g_free(str);
  1269. }
  1270. monitor_printf(mon, "\n");
  1271. }
  1272. void print_net_client(Monitor *mon, NetClientState *nc)
  1273. {
  1274. NetFilterState *nf;
  1275. monitor_printf(mon, "%s: index=%d,type=%s,%s\n", nc->name,
  1276. nc->queue_index,
  1277. NetClientDriver_str(nc->info->type),
  1278. nc->info_str);
  1279. if (!QTAILQ_EMPTY(&nc->filters)) {
  1280. monitor_printf(mon, "filters:\n");
  1281. }
  1282. QTAILQ_FOREACH(nf, &nc->filters, next) {
  1283. monitor_printf(mon, " - %s: type=%s",
  1284. object_get_canonical_path_component(OBJECT(nf)),
  1285. object_get_typename(OBJECT(nf)));
  1286. netfilter_print_info(mon, nf);
  1287. }
  1288. }
  1289. RxFilterInfoList *qmp_query_rx_filter(const char *name, Error **errp)
  1290. {
  1291. NetClientState *nc;
  1292. RxFilterInfoList *filter_list = NULL, **tail = &filter_list;
  1293. QTAILQ_FOREACH(nc, &net_clients, next) {
  1294. RxFilterInfo *info;
  1295. if (name && strcmp(nc->name, name) != 0) {
  1296. continue;
  1297. }
  1298. /* only query rx-filter information of NIC */
  1299. if (nc->info->type != NET_CLIENT_DRIVER_NIC) {
  1300. if (name) {
  1301. error_setg(errp, "net client(%s) isn't a NIC", name);
  1302. assert(!filter_list);
  1303. return NULL;
  1304. }
  1305. continue;
  1306. }
  1307. /* only query information on queue 0 since the info is per nic,
  1308. * not per queue
  1309. */
  1310. if (nc->queue_index != 0)
  1311. continue;
  1312. if (nc->info->query_rx_filter) {
  1313. info = nc->info->query_rx_filter(nc);
  1314. QAPI_LIST_APPEND(tail, info);
  1315. } else if (name) {
  1316. error_setg(errp, "net client(%s) doesn't support"
  1317. " rx-filter querying", name);
  1318. assert(!filter_list);
  1319. return NULL;
  1320. }
  1321. if (name) {
  1322. break;
  1323. }
  1324. }
  1325. if (filter_list == NULL && name) {
  1326. error_setg(errp, "invalid net client name: %s", name);
  1327. }
  1328. return filter_list;
  1329. }
  1330. void colo_notify_filters_event(int event, Error **errp)
  1331. {
  1332. NetClientState *nc;
  1333. NetFilterState *nf;
  1334. NetFilterClass *nfc = NULL;
  1335. Error *local_err = NULL;
  1336. QTAILQ_FOREACH(nc, &net_clients, next) {
  1337. QTAILQ_FOREACH(nf, &nc->filters, next) {
  1338. nfc = NETFILTER_GET_CLASS(OBJECT(nf));
  1339. nfc->handle_event(nf, event, &local_err);
  1340. if (local_err) {
  1341. error_propagate(errp, local_err);
  1342. return;
  1343. }
  1344. }
  1345. }
  1346. }
  1347. void qmp_set_link(const char *name, bool up, Error **errp)
  1348. {
  1349. NetClientState *ncs[MAX_QUEUE_NUM];
  1350. NetClientState *nc;
  1351. int queues, i;
  1352. queues = qemu_find_net_clients_except(name, ncs,
  1353. NET_CLIENT_DRIVER__MAX,
  1354. MAX_QUEUE_NUM);
  1355. if (queues == 0) {
  1356. error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
  1357. "Device '%s' not found", name);
  1358. return;
  1359. }
  1360. nc = ncs[0];
  1361. for (i = 0; i < queues; i++) {
  1362. ncs[i]->link_down = !up;
  1363. }
  1364. if (nc->info->link_status_changed) {
  1365. nc->info->link_status_changed(nc);
  1366. }
  1367. if (nc->peer) {
  1368. /* Change peer link only if the peer is NIC and then notify peer.
  1369. * If the peer is a HUBPORT or a backend, we do not change the
  1370. * link status.
  1371. *
  1372. * This behavior is compatible with qemu hubs where there could be
  1373. * multiple clients that can still communicate with each other in
  1374. * disconnected mode. For now maintain this compatibility.
  1375. */
  1376. if (nc->peer->info->type == NET_CLIENT_DRIVER_NIC) {
  1377. for (i = 0; i < queues; i++) {
  1378. ncs[i]->peer->link_down = !up;
  1379. }
  1380. }
  1381. if (nc->peer->info->link_status_changed) {
  1382. nc->peer->info->link_status_changed(nc->peer);
  1383. }
  1384. }
  1385. }
  1386. static void net_vm_change_state_handler(void *opaque, bool running,
  1387. RunState state)
  1388. {
  1389. NetClientState *nc;
  1390. NetClientState *tmp;
  1391. QTAILQ_FOREACH_SAFE(nc, &net_clients, next, tmp) {
  1392. if (running) {
  1393. /* Flush queued packets and wake up backends. */
  1394. if (nc->peer && qemu_can_send_packet(nc)) {
  1395. qemu_flush_queued_packets(nc->peer);
  1396. }
  1397. } else {
  1398. /* Complete all queued packets, to guarantee we don't modify
  1399. * state later when VM is not running.
  1400. */
  1401. qemu_flush_or_purge_queued_packets(nc, true);
  1402. }
  1403. }
  1404. }
  1405. void net_cleanup(void)
  1406. {
  1407. NetClientState *nc, **p = &QTAILQ_FIRST(&net_clients);
  1408. /*cleanup colo compare module for COLO*/
  1409. colo_compare_cleanup();
  1410. /*
  1411. * Walk the net_clients list and remove the netdevs but *not* any
  1412. * NET_CLIENT_DRIVER_NIC entries. The latter are owned by the device
  1413. * model which created them, and in some cases (e.g. xen-net-device)
  1414. * the device itself may do cleanup at exit and will be upset if we
  1415. * just delete its NIC from underneath it.
  1416. *
  1417. * Since qemu_del_net_client() may delete multiple entries, using
  1418. * QTAILQ_FOREACH_SAFE() is not safe here. The only safe pointer
  1419. * to keep as a bookmark is a NET_CLIENT_DRIVER_NIC entry, so keep
  1420. * 'p' pointing to either the head of the list, or the 'next' field
  1421. * of the latest NET_CLIENT_DRIVER_NIC, and operate on *p as we walk
  1422. * the list.
  1423. *
  1424. * The 'nc' variable isn't part of the list traversal; it's purely
  1425. * for convenience as too much '(*p)->' has a tendency to make the
  1426. * readers' eyes bleed.
  1427. */
  1428. while (*p) {
  1429. nc = *p;
  1430. if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
  1431. /* Skip NET_CLIENT_DRIVER_NIC entries */
  1432. p = &QTAILQ_NEXT(nc, next);
  1433. } else {
  1434. qemu_del_net_client(nc);
  1435. }
  1436. }
  1437. qemu_del_vm_change_state_handler(net_change_state_entry);
  1438. }
  1439. void net_check_clients(void)
  1440. {
  1441. NetClientState *nc;
  1442. int i;
  1443. if (nic_model_help) {
  1444. show_nic_models();
  1445. exit(0);
  1446. }
  1447. net_hub_check_clients();
  1448. QTAILQ_FOREACH(nc, &net_clients, next) {
  1449. if (!nc->peer) {
  1450. warn_report("%s %s has no peer",
  1451. nc->info->type == NET_CLIENT_DRIVER_NIC
  1452. ? "nic" : "netdev",
  1453. nc->name);
  1454. }
  1455. }
  1456. /* Check that all NICs requested via -net nic actually got created.
  1457. * NICs created via -device don't need to be checked here because
  1458. * they are always instantiated.
  1459. */
  1460. for (i = 0; i < MAX_NICS; i++) {
  1461. NICInfo *nd = &nd_table[i];
  1462. if (nd->used && !nd->instantiated) {
  1463. warn_report("requested NIC (%s, model %s) "
  1464. "was not created (not supported by this machine?)",
  1465. nd->name ? nd->name : "anonymous",
  1466. nd->model ? nd->model : "unspecified");
  1467. }
  1468. }
  1469. }
  1470. static int net_init_client(void *dummy, QemuOpts *opts, Error **errp)
  1471. {
  1472. const char *model = qemu_opt_get(opts, "model");
  1473. if (is_nic_model_help_option(model)) {
  1474. return 0;
  1475. }
  1476. return net_client_init(opts, false, errp);
  1477. }
  1478. static int net_init_netdev(void *dummy, QemuOpts *opts, Error **errp)
  1479. {
  1480. const char *type = qemu_opt_get(opts, "type");
  1481. if (type && is_help_option(type)) {
  1482. show_netdevs();
  1483. exit(0);
  1484. }
  1485. return net_client_init(opts, true, errp);
  1486. }
  1487. /* For the convenience "--nic" parameter */
  1488. static int net_param_nic(void *dummy, QemuOpts *opts, Error **errp)
  1489. {
  1490. char *mac, *nd_id;
  1491. int idx, ret;
  1492. NICInfo *ni;
  1493. const char *type;
  1494. type = qemu_opt_get(opts, "type");
  1495. if (type) {
  1496. if (g_str_equal(type, "none")) {
  1497. return 0; /* Nothing to do, default_net is cleared in vl.c */
  1498. }
  1499. if (is_help_option(type)) {
  1500. GPtrArray *nic_models = qemu_get_nic_models(TYPE_DEVICE);
  1501. int i;
  1502. show_netdevs();
  1503. printf("\n");
  1504. printf("Available NIC models "
  1505. "(use -nic model=help for a filtered list):\n");
  1506. for (i = 0 ; nic_models->pdata[i]; i++) {
  1507. printf("%s\n", (char *)nic_models->pdata[i]);
  1508. }
  1509. g_ptr_array_free(nic_models, true);
  1510. exit(0);
  1511. }
  1512. }
  1513. idx = nic_get_free_idx();
  1514. if (idx == -1 || nb_nics >= MAX_NICS) {
  1515. error_setg(errp, "no more on-board/default NIC slots available");
  1516. return -1;
  1517. }
  1518. if (!type) {
  1519. qemu_opt_set(opts, "type", "user", &error_abort);
  1520. }
  1521. ni = &nd_table[idx];
  1522. memset(ni, 0, sizeof(*ni));
  1523. ni->model = qemu_opt_get_del(opts, "model");
  1524. if (is_nic_model_help_option(ni->model)) {
  1525. return 0;
  1526. }
  1527. /* Create an ID if the user did not specify one */
  1528. nd_id = g_strdup(qemu_opts_id(opts));
  1529. if (!nd_id) {
  1530. nd_id = id_generate(ID_NET);
  1531. qemu_opts_set_id(opts, nd_id);
  1532. }
  1533. /* Handle MAC address */
  1534. mac = qemu_opt_get_del(opts, "mac");
  1535. if (mac) {
  1536. ret = net_parse_macaddr(ni->macaddr.a, mac);
  1537. g_free(mac);
  1538. if (ret) {
  1539. error_setg(errp, "invalid syntax for ethernet address");
  1540. goto out;
  1541. }
  1542. if (is_multicast_ether_addr(ni->macaddr.a)) {
  1543. error_setg(errp, "NIC cannot have multicast MAC address");
  1544. ret = -1;
  1545. goto out;
  1546. }
  1547. }
  1548. qemu_macaddr_default_if_unset(&ni->macaddr);
  1549. ret = net_client_init(opts, true, errp);
  1550. if (ret == 0) {
  1551. ni->netdev = qemu_find_netdev(nd_id);
  1552. ni->used = true;
  1553. nb_nics++;
  1554. }
  1555. out:
  1556. g_free(nd_id);
  1557. return ret;
  1558. }
  1559. static void netdev_init_modern(void)
  1560. {
  1561. while (!QSIMPLEQ_EMPTY(&nd_queue)) {
  1562. NetdevQueueEntry *nd = QSIMPLEQ_FIRST(&nd_queue);
  1563. QSIMPLEQ_REMOVE_HEAD(&nd_queue, entry);
  1564. loc_push_restore(&nd->loc);
  1565. net_client_init1(nd->nd, true, &error_fatal);
  1566. loc_pop(&nd->loc);
  1567. qapi_free_Netdev(nd->nd);
  1568. g_free(nd);
  1569. }
  1570. }
  1571. void net_init_clients(void)
  1572. {
  1573. net_change_state_entry =
  1574. qemu_add_vm_change_state_handler(net_vm_change_state_handler, NULL);
  1575. QTAILQ_INIT(&net_clients);
  1576. netdev_init_modern();
  1577. qemu_opts_foreach(qemu_find_opts("netdev"), net_init_netdev, NULL,
  1578. &error_fatal);
  1579. qemu_opts_foreach(qemu_find_opts("nic"), net_param_nic, NULL,
  1580. &error_fatal);
  1581. qemu_opts_foreach(qemu_find_opts("net"), net_init_client, NULL,
  1582. &error_fatal);
  1583. }
  1584. /*
  1585. * Does this -netdev argument use modern rather than traditional syntax?
  1586. * Modern syntax is to be parsed with netdev_parse_modern().
  1587. * Traditional syntax is to be parsed with net_client_parse().
  1588. */
  1589. bool netdev_is_modern(const char *optstr)
  1590. {
  1591. QemuOpts *opts;
  1592. bool is_modern;
  1593. const char *type;
  1594. static QemuOptsList dummy_opts = {
  1595. .name = "netdev",
  1596. .implied_opt_name = "type",
  1597. .head = QTAILQ_HEAD_INITIALIZER(dummy_opts.head),
  1598. .desc = { { } },
  1599. };
  1600. if (optstr[0] == '{') {
  1601. /* This is JSON, which means it's modern syntax */
  1602. return true;
  1603. }
  1604. opts = qemu_opts_create(&dummy_opts, NULL, false, &error_abort);
  1605. qemu_opts_do_parse(opts, optstr, dummy_opts.implied_opt_name,
  1606. &error_abort);
  1607. type = qemu_opt_get(opts, "type");
  1608. is_modern = !g_strcmp0(type, "stream") || !g_strcmp0(type, "dgram");
  1609. qemu_opts_reset(&dummy_opts);
  1610. return is_modern;
  1611. }
  1612. /*
  1613. * netdev_parse_modern() uses modern, more expressive syntax than
  1614. * net_client_parse(), but supports only the -netdev option.
  1615. * netdev_parse_modern() appends to @nd_queue, whereas net_client_parse()
  1616. * appends to @qemu_netdev_opts.
  1617. */
  1618. void netdev_parse_modern(const char *optstr)
  1619. {
  1620. Visitor *v;
  1621. NetdevQueueEntry *nd;
  1622. v = qobject_input_visitor_new_str(optstr, "type", &error_fatal);
  1623. nd = g_new(NetdevQueueEntry, 1);
  1624. visit_type_Netdev(v, NULL, &nd->nd, &error_fatal);
  1625. visit_free(v);
  1626. loc_save(&nd->loc);
  1627. QSIMPLEQ_INSERT_TAIL(&nd_queue, nd, entry);
  1628. }
  1629. void net_client_parse(QemuOptsList *opts_list, const char *optstr)
  1630. {
  1631. if (!qemu_opts_parse_noisily(opts_list, optstr, true)) {
  1632. exit(1);
  1633. }
  1634. }
  1635. /* From FreeBSD */
  1636. /* XXX: optimize */
  1637. uint32_t net_crc32(const uint8_t *p, int len)
  1638. {
  1639. uint32_t crc;
  1640. int carry, i, j;
  1641. uint8_t b;
  1642. crc = 0xffffffff;
  1643. for (i = 0; i < len; i++) {
  1644. b = *p++;
  1645. for (j = 0; j < 8; j++) {
  1646. carry = ((crc & 0x80000000L) ? 1 : 0) ^ (b & 0x01);
  1647. crc <<= 1;
  1648. b >>= 1;
  1649. if (carry) {
  1650. crc = ((crc ^ POLYNOMIAL_BE) | carry);
  1651. }
  1652. }
  1653. }
  1654. return crc;
  1655. }
  1656. uint32_t net_crc32_le(const uint8_t *p, int len)
  1657. {
  1658. uint32_t crc;
  1659. int carry, i, j;
  1660. uint8_t b;
  1661. crc = 0xffffffff;
  1662. for (i = 0; i < len; i++) {
  1663. b = *p++;
  1664. for (j = 0; j < 8; j++) {
  1665. carry = (crc & 0x1) ^ (b & 0x01);
  1666. crc >>= 1;
  1667. b >>= 1;
  1668. if (carry) {
  1669. crc ^= POLYNOMIAL_LE;
  1670. }
  1671. }
  1672. }
  1673. return crc;
  1674. }
  1675. QemuOptsList qemu_netdev_opts = {
  1676. .name = "netdev",
  1677. .implied_opt_name = "type",
  1678. .head = QTAILQ_HEAD_INITIALIZER(qemu_netdev_opts.head),
  1679. .desc = {
  1680. /*
  1681. * no elements => accept any params
  1682. * validation will happen later
  1683. */
  1684. { /* end of list */ }
  1685. },
  1686. };
  1687. QemuOptsList qemu_nic_opts = {
  1688. .name = "nic",
  1689. .implied_opt_name = "type",
  1690. .head = QTAILQ_HEAD_INITIALIZER(qemu_nic_opts.head),
  1691. .desc = {
  1692. /*
  1693. * no elements => accept any params
  1694. * validation will happen later
  1695. */
  1696. { /* end of list */ }
  1697. },
  1698. };
  1699. QemuOptsList qemu_net_opts = {
  1700. .name = "net",
  1701. .implied_opt_name = "type",
  1702. .head = QTAILQ_HEAD_INITIALIZER(qemu_net_opts.head),
  1703. .desc = {
  1704. /*
  1705. * no elements => accept any params
  1706. * validation will happen later
  1707. */
  1708. { /* end of list */ }
  1709. },
  1710. };
  1711. void net_socket_rs_init(SocketReadState *rs,
  1712. SocketReadStateFinalize *finalize,
  1713. bool vnet_hdr)
  1714. {
  1715. rs->state = 0;
  1716. rs->vnet_hdr = vnet_hdr;
  1717. rs->index = 0;
  1718. rs->packet_len = 0;
  1719. rs->vnet_hdr_len = 0;
  1720. memset(rs->buf, 0, sizeof(rs->buf));
  1721. rs->finalize = finalize;
  1722. }
  1723. /*
  1724. * Returns
  1725. * 0: success
  1726. * -1: error occurs
  1727. */
  1728. int net_fill_rstate(SocketReadState *rs, const uint8_t *buf, int size)
  1729. {
  1730. unsigned int l;
  1731. while (size > 0) {
  1732. /* Reassemble a packet from the network.
  1733. * 0 = getting length.
  1734. * 1 = getting vnet header length.
  1735. * 2 = getting data.
  1736. */
  1737. switch (rs->state) {
  1738. case 0:
  1739. l = 4 - rs->index;
  1740. if (l > size) {
  1741. l = size;
  1742. }
  1743. memcpy(rs->buf + rs->index, buf, l);
  1744. buf += l;
  1745. size -= l;
  1746. rs->index += l;
  1747. if (rs->index == 4) {
  1748. /* got length */
  1749. rs->packet_len = ntohl(*(uint32_t *)rs->buf);
  1750. rs->index = 0;
  1751. if (rs->vnet_hdr) {
  1752. rs->state = 1;
  1753. } else {
  1754. rs->state = 2;
  1755. rs->vnet_hdr_len = 0;
  1756. }
  1757. }
  1758. break;
  1759. case 1:
  1760. l = 4 - rs->index;
  1761. if (l > size) {
  1762. l = size;
  1763. }
  1764. memcpy(rs->buf + rs->index, buf, l);
  1765. buf += l;
  1766. size -= l;
  1767. rs->index += l;
  1768. if (rs->index == 4) {
  1769. /* got vnet header length */
  1770. rs->vnet_hdr_len = ntohl(*(uint32_t *)rs->buf);
  1771. rs->index = 0;
  1772. rs->state = 2;
  1773. }
  1774. break;
  1775. case 2:
  1776. l = rs->packet_len - rs->index;
  1777. if (l > size) {
  1778. l = size;
  1779. }
  1780. if (rs->index + l <= sizeof(rs->buf)) {
  1781. memcpy(rs->buf + rs->index, buf, l);
  1782. } else {
  1783. fprintf(stderr, "serious error: oversized packet received,"
  1784. "connection terminated.\n");
  1785. rs->index = rs->state = 0;
  1786. return -1;
  1787. }
  1788. rs->index += l;
  1789. buf += l;
  1790. size -= l;
  1791. if (rs->index >= rs->packet_len) {
  1792. rs->index = 0;
  1793. rs->state = 0;
  1794. assert(rs->finalize);
  1795. rs->finalize(rs);
  1796. }
  1797. break;
  1798. }
  1799. }
  1800. assert(size == 0);
  1801. return 0;
  1802. }