net.c 56 KB

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