net.c 55 KB

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