commands-posix.c 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427
  1. /*
  2. * QEMU Guest Agent POSIX-specific command implementations
  3. *
  4. * Copyright IBM Corp. 2011
  5. *
  6. * Authors:
  7. * Michael Roth <mdroth@linux.vnet.ibm.com>
  8. * Michal Privoznik <mprivozn@redhat.com>
  9. *
  10. * This work is licensed under the terms of the GNU GPL, version 2 or later.
  11. * See the COPYING file in the top-level directory.
  12. */
  13. #include "qemu/osdep.h"
  14. #include <sys/ioctl.h>
  15. #include <sys/utsname.h>
  16. #include <sys/wait.h>
  17. #include <dirent.h>
  18. #include "qga-qapi-commands.h"
  19. #include "qapi/error.h"
  20. #include "qapi/qmp/qerror.h"
  21. #include "qemu/host-utils.h"
  22. #include "qemu/sockets.h"
  23. #include "qemu/base64.h"
  24. #include "qemu/cutils.h"
  25. #include "commands-common.h"
  26. #include "block/nvme.h"
  27. #include "cutils.h"
  28. #ifdef HAVE_UTMPX
  29. #include <utmpx.h>
  30. #endif
  31. #if defined(__linux__)
  32. #include <mntent.h>
  33. #include <sys/statvfs.h>
  34. #include <linux/nvme_ioctl.h>
  35. #ifdef CONFIG_LIBUDEV
  36. #include <libudev.h>
  37. #endif
  38. #endif
  39. #ifdef HAVE_GETIFADDRS
  40. #include <arpa/inet.h>
  41. #include <sys/socket.h>
  42. #include <net/if.h>
  43. #if defined(__NetBSD__) || defined(__OpenBSD__)
  44. #include <net/if_arp.h>
  45. #include <netinet/if_ether.h>
  46. #else
  47. #include <net/ethernet.h>
  48. #endif
  49. #ifdef CONFIG_SOLARIS
  50. #include <sys/sockio.h>
  51. #endif
  52. #endif
  53. static void ga_wait_child(pid_t pid, int *status, Error **errp)
  54. {
  55. pid_t rpid;
  56. *status = 0;
  57. rpid = RETRY_ON_EINTR(waitpid(pid, status, 0));
  58. if (rpid == -1) {
  59. error_setg_errno(errp, errno, "failed to wait for child (pid: %d)",
  60. pid);
  61. return;
  62. }
  63. g_assert(rpid == pid);
  64. }
  65. void qmp_guest_shutdown(const char *mode, Error **errp)
  66. {
  67. const char *shutdown_flag;
  68. Error *local_err = NULL;
  69. pid_t pid;
  70. int status;
  71. #ifdef CONFIG_SOLARIS
  72. const char *powerdown_flag = "-i5";
  73. const char *halt_flag = "-i0";
  74. const char *reboot_flag = "-i6";
  75. #elif defined(CONFIG_BSD)
  76. const char *powerdown_flag = "-p";
  77. const char *halt_flag = "-h";
  78. const char *reboot_flag = "-r";
  79. #else
  80. const char *powerdown_flag = "-P";
  81. const char *halt_flag = "-H";
  82. const char *reboot_flag = "-r";
  83. #endif
  84. slog("guest-shutdown called, mode: %s", mode);
  85. if (!mode || strcmp(mode, "powerdown") == 0) {
  86. shutdown_flag = powerdown_flag;
  87. } else if (strcmp(mode, "halt") == 0) {
  88. shutdown_flag = halt_flag;
  89. } else if (strcmp(mode, "reboot") == 0) {
  90. shutdown_flag = reboot_flag;
  91. } else {
  92. error_setg(errp,
  93. "mode is invalid (valid values are: halt|powerdown|reboot");
  94. return;
  95. }
  96. pid = fork();
  97. if (pid == 0) {
  98. /* child, start the shutdown */
  99. setsid();
  100. reopen_fd_to_null(0);
  101. reopen_fd_to_null(1);
  102. reopen_fd_to_null(2);
  103. #ifdef CONFIG_SOLARIS
  104. execl("/sbin/shutdown", "shutdown", shutdown_flag, "-g0", "-y",
  105. "hypervisor initiated shutdown", (char *)NULL);
  106. #elif defined(CONFIG_BSD)
  107. execl("/sbin/shutdown", "shutdown", shutdown_flag, "+0",
  108. "hypervisor initiated shutdown", (char *)NULL);
  109. #else
  110. execl("/sbin/shutdown", "shutdown", "-h", shutdown_flag, "+0",
  111. "hypervisor initiated shutdown", (char *)NULL);
  112. #endif
  113. _exit(EXIT_FAILURE);
  114. } else if (pid < 0) {
  115. error_setg_errno(errp, errno, "failed to create child process");
  116. return;
  117. }
  118. ga_wait_child(pid, &status, &local_err);
  119. if (local_err) {
  120. error_propagate(errp, local_err);
  121. return;
  122. }
  123. if (!WIFEXITED(status)) {
  124. error_setg(errp, "child process has terminated abnormally");
  125. return;
  126. }
  127. if (WEXITSTATUS(status)) {
  128. error_setg(errp, "child process has failed to shutdown");
  129. return;
  130. }
  131. /* succeeded */
  132. }
  133. void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
  134. {
  135. int ret;
  136. int status;
  137. pid_t pid;
  138. Error *local_err = NULL;
  139. struct timeval tv;
  140. static const char hwclock_path[] = "/sbin/hwclock";
  141. static int hwclock_available = -1;
  142. if (hwclock_available < 0) {
  143. hwclock_available = (access(hwclock_path, X_OK) == 0);
  144. }
  145. if (!hwclock_available) {
  146. error_setg(errp, QERR_UNSUPPORTED);
  147. return;
  148. }
  149. /* If user has passed a time, validate and set it. */
  150. if (has_time) {
  151. GDate date = { 0, };
  152. /* year-2038 will overflow in case time_t is 32bit */
  153. if (time_ns / 1000000000 != (time_t)(time_ns / 1000000000)) {
  154. error_setg(errp, "Time %" PRId64 " is too large", time_ns);
  155. return;
  156. }
  157. tv.tv_sec = time_ns / 1000000000;
  158. tv.tv_usec = (time_ns % 1000000000) / 1000;
  159. g_date_set_time_t(&date, tv.tv_sec);
  160. if (date.year < 1970 || date.year >= 2070) {
  161. error_setg_errno(errp, errno, "Invalid time");
  162. return;
  163. }
  164. ret = settimeofday(&tv, NULL);
  165. if (ret < 0) {
  166. error_setg_errno(errp, errno, "Failed to set time to guest");
  167. return;
  168. }
  169. }
  170. /* Now, if user has passed a time to set and the system time is set, we
  171. * just need to synchronize the hardware clock. However, if no time was
  172. * passed, user is requesting the opposite: set the system time from the
  173. * hardware clock (RTC). */
  174. pid = fork();
  175. if (pid == 0) {
  176. setsid();
  177. reopen_fd_to_null(0);
  178. reopen_fd_to_null(1);
  179. reopen_fd_to_null(2);
  180. /* Use '/sbin/hwclock -w' to set RTC from the system time,
  181. * or '/sbin/hwclock -s' to set the system time from RTC. */
  182. execl(hwclock_path, "hwclock", has_time ? "-w" : "-s", NULL);
  183. _exit(EXIT_FAILURE);
  184. } else if (pid < 0) {
  185. error_setg_errno(errp, errno, "failed to create child process");
  186. return;
  187. }
  188. ga_wait_child(pid, &status, &local_err);
  189. if (local_err) {
  190. error_propagate(errp, local_err);
  191. return;
  192. }
  193. if (!WIFEXITED(status)) {
  194. error_setg(errp, "child process has terminated abnormally");
  195. return;
  196. }
  197. if (WEXITSTATUS(status)) {
  198. error_setg(errp, "hwclock failed to set hardware clock to system time");
  199. return;
  200. }
  201. }
  202. typedef enum {
  203. RW_STATE_NEW,
  204. RW_STATE_READING,
  205. RW_STATE_WRITING,
  206. } RwState;
  207. struct GuestFileHandle {
  208. uint64_t id;
  209. FILE *fh;
  210. RwState state;
  211. QTAILQ_ENTRY(GuestFileHandle) next;
  212. };
  213. static struct {
  214. QTAILQ_HEAD(, GuestFileHandle) filehandles;
  215. } guest_file_state = {
  216. .filehandles = QTAILQ_HEAD_INITIALIZER(guest_file_state.filehandles),
  217. };
  218. static int64_t guest_file_handle_add(FILE *fh, Error **errp)
  219. {
  220. GuestFileHandle *gfh;
  221. int64_t handle;
  222. handle = ga_get_fd_handle(ga_state, errp);
  223. if (handle < 0) {
  224. return -1;
  225. }
  226. gfh = g_new0(GuestFileHandle, 1);
  227. gfh->id = handle;
  228. gfh->fh = fh;
  229. QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
  230. return handle;
  231. }
  232. GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
  233. {
  234. GuestFileHandle *gfh;
  235. QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next)
  236. {
  237. if (gfh->id == id) {
  238. return gfh;
  239. }
  240. }
  241. error_setg(errp, "handle '%" PRId64 "' has not been found", id);
  242. return NULL;
  243. }
  244. typedef const char * const ccpc;
  245. #ifndef O_BINARY
  246. #define O_BINARY 0
  247. #endif
  248. /* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
  249. static const struct {
  250. ccpc *forms;
  251. int oflag_base;
  252. } guest_file_open_modes[] = {
  253. { (ccpc[]){ "r", NULL }, O_RDONLY },
  254. { (ccpc[]){ "rb", NULL }, O_RDONLY | O_BINARY },
  255. { (ccpc[]){ "w", NULL }, O_WRONLY | O_CREAT | O_TRUNC },
  256. { (ccpc[]){ "wb", NULL }, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY },
  257. { (ccpc[]){ "a", NULL }, O_WRONLY | O_CREAT | O_APPEND },
  258. { (ccpc[]){ "ab", NULL }, O_WRONLY | O_CREAT | O_APPEND | O_BINARY },
  259. { (ccpc[]){ "r+", NULL }, O_RDWR },
  260. { (ccpc[]){ "rb+", "r+b", NULL }, O_RDWR | O_BINARY },
  261. { (ccpc[]){ "w+", NULL }, O_RDWR | O_CREAT | O_TRUNC },
  262. { (ccpc[]){ "wb+", "w+b", NULL }, O_RDWR | O_CREAT | O_TRUNC | O_BINARY },
  263. { (ccpc[]){ "a+", NULL }, O_RDWR | O_CREAT | O_APPEND },
  264. { (ccpc[]){ "ab+", "a+b", NULL }, O_RDWR | O_CREAT | O_APPEND | O_BINARY }
  265. };
  266. static int
  267. find_open_flag(const char *mode_str, Error **errp)
  268. {
  269. unsigned mode;
  270. for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
  271. ccpc *form;
  272. form = guest_file_open_modes[mode].forms;
  273. while (*form != NULL && strcmp(*form, mode_str) != 0) {
  274. ++form;
  275. }
  276. if (*form != NULL) {
  277. break;
  278. }
  279. }
  280. if (mode == ARRAY_SIZE(guest_file_open_modes)) {
  281. error_setg(errp, "invalid file open mode '%s'", mode_str);
  282. return -1;
  283. }
  284. return guest_file_open_modes[mode].oflag_base | O_NOCTTY | O_NONBLOCK;
  285. }
  286. #define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
  287. S_IRGRP | S_IWGRP | \
  288. S_IROTH | S_IWOTH)
  289. static FILE *
  290. safe_open_or_create(const char *path, const char *mode, Error **errp)
  291. {
  292. int oflag;
  293. int fd = -1;
  294. FILE *f = NULL;
  295. oflag = find_open_flag(mode, errp);
  296. if (oflag < 0) {
  297. goto end;
  298. }
  299. /* If the caller wants / allows creation of a new file, we implement it
  300. * with a two step process: open() + (open() / fchmod()).
  301. *
  302. * First we insist on creating the file exclusively as a new file. If
  303. * that succeeds, we're free to set any file-mode bits on it. (The
  304. * motivation is that we want to set those file-mode bits independently
  305. * of the current umask.)
  306. *
  307. * If the exclusive creation fails because the file already exists
  308. * (EEXIST is not possible for any other reason), we just attempt to
  309. * open the file, but in this case we won't be allowed to change the
  310. * file-mode bits on the preexistent file.
  311. *
  312. * The pathname should never disappear between the two open()s in
  313. * practice. If it happens, then someone very likely tried to race us.
  314. * In this case just go ahead and report the ENOENT from the second
  315. * open() to the caller.
  316. *
  317. * If the caller wants to open a preexistent file, then the first
  318. * open() is decisive and its third argument is ignored, and the second
  319. * open() and the fchmod() are never called.
  320. */
  321. fd = qga_open_cloexec(path, oflag | ((oflag & O_CREAT) ? O_EXCL : 0), 0);
  322. if (fd == -1 && errno == EEXIST) {
  323. oflag &= ~(unsigned)O_CREAT;
  324. fd = qga_open_cloexec(path, oflag, 0);
  325. }
  326. if (fd == -1) {
  327. error_setg_errno(errp, errno,
  328. "failed to open file '%s' (mode: '%s')",
  329. path, mode);
  330. goto end;
  331. }
  332. if ((oflag & O_CREAT) && fchmod(fd, DEFAULT_NEW_FILE_MODE) == -1) {
  333. error_setg_errno(errp, errno, "failed to set permission "
  334. "0%03o on new file '%s' (mode: '%s')",
  335. (unsigned)DEFAULT_NEW_FILE_MODE, path, mode);
  336. goto end;
  337. }
  338. f = fdopen(fd, mode);
  339. if (f == NULL) {
  340. error_setg_errno(errp, errno, "failed to associate stdio stream with "
  341. "file descriptor %d, file '%s' (mode: '%s')",
  342. fd, path, mode);
  343. }
  344. end:
  345. if (f == NULL && fd != -1) {
  346. close(fd);
  347. if (oflag & O_CREAT) {
  348. unlink(path);
  349. }
  350. }
  351. return f;
  352. }
  353. int64_t qmp_guest_file_open(const char *path, const char *mode,
  354. Error **errp)
  355. {
  356. FILE *fh;
  357. Error *local_err = NULL;
  358. int64_t handle;
  359. if (!mode) {
  360. mode = "r";
  361. }
  362. slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
  363. fh = safe_open_or_create(path, mode, &local_err);
  364. if (local_err != NULL) {
  365. error_propagate(errp, local_err);
  366. return -1;
  367. }
  368. /* set fd non-blocking to avoid common use cases (like reading from a
  369. * named pipe) from hanging the agent
  370. */
  371. if (!g_unix_set_fd_nonblocking(fileno(fh), true, NULL)) {
  372. fclose(fh);
  373. error_setg_errno(errp, errno, "Failed to set FD nonblocking");
  374. return -1;
  375. }
  376. handle = guest_file_handle_add(fh, errp);
  377. if (handle < 0) {
  378. fclose(fh);
  379. return -1;
  380. }
  381. slog("guest-file-open, handle: %" PRId64, handle);
  382. return handle;
  383. }
  384. void qmp_guest_file_close(int64_t handle, Error **errp)
  385. {
  386. GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
  387. int ret;
  388. slog("guest-file-close called, handle: %" PRId64, handle);
  389. if (!gfh) {
  390. return;
  391. }
  392. ret = fclose(gfh->fh);
  393. if (ret == EOF) {
  394. error_setg_errno(errp, errno, "failed to close handle");
  395. return;
  396. }
  397. QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
  398. g_free(gfh);
  399. }
  400. GuestFileRead *guest_file_read_unsafe(GuestFileHandle *gfh,
  401. int64_t count, Error **errp)
  402. {
  403. GuestFileRead *read_data = NULL;
  404. guchar *buf;
  405. FILE *fh = gfh->fh;
  406. size_t read_count;
  407. /* explicitly flush when switching from writing to reading */
  408. if (gfh->state == RW_STATE_WRITING) {
  409. int ret = fflush(fh);
  410. if (ret == EOF) {
  411. error_setg_errno(errp, errno, "failed to flush file");
  412. return NULL;
  413. }
  414. gfh->state = RW_STATE_NEW;
  415. }
  416. buf = g_malloc0(count + 1);
  417. read_count = fread(buf, 1, count, fh);
  418. if (ferror(fh)) {
  419. error_setg_errno(errp, errno, "failed to read file");
  420. } else {
  421. buf[read_count] = 0;
  422. read_data = g_new0(GuestFileRead, 1);
  423. read_data->count = read_count;
  424. read_data->eof = feof(fh);
  425. if (read_count) {
  426. read_data->buf_b64 = g_base64_encode(buf, read_count);
  427. }
  428. gfh->state = RW_STATE_READING;
  429. }
  430. g_free(buf);
  431. clearerr(fh);
  432. return read_data;
  433. }
  434. GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
  435. bool has_count, int64_t count,
  436. Error **errp)
  437. {
  438. GuestFileWrite *write_data = NULL;
  439. guchar *buf;
  440. gsize buf_len;
  441. int write_count;
  442. GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
  443. FILE *fh;
  444. if (!gfh) {
  445. return NULL;
  446. }
  447. fh = gfh->fh;
  448. if (gfh->state == RW_STATE_READING) {
  449. int ret = fseek(fh, 0, SEEK_CUR);
  450. if (ret == -1) {
  451. error_setg_errno(errp, errno, "failed to seek file");
  452. return NULL;
  453. }
  454. gfh->state = RW_STATE_NEW;
  455. }
  456. buf = qbase64_decode(buf_b64, -1, &buf_len, errp);
  457. if (!buf) {
  458. return NULL;
  459. }
  460. if (!has_count) {
  461. count = buf_len;
  462. } else if (count < 0 || count > buf_len) {
  463. error_setg(errp, "value '%" PRId64 "' is invalid for argument count",
  464. count);
  465. g_free(buf);
  466. return NULL;
  467. }
  468. write_count = fwrite(buf, 1, count, fh);
  469. if (ferror(fh)) {
  470. error_setg_errno(errp, errno, "failed to write to file");
  471. slog("guest-file-write failed, handle: %" PRId64, handle);
  472. } else {
  473. write_data = g_new0(GuestFileWrite, 1);
  474. write_data->count = write_count;
  475. write_data->eof = feof(fh);
  476. gfh->state = RW_STATE_WRITING;
  477. }
  478. g_free(buf);
  479. clearerr(fh);
  480. return write_data;
  481. }
  482. struct GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
  483. GuestFileWhence *whence_code,
  484. Error **errp)
  485. {
  486. GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
  487. GuestFileSeek *seek_data = NULL;
  488. FILE *fh;
  489. int ret;
  490. int whence;
  491. Error *err = NULL;
  492. if (!gfh) {
  493. return NULL;
  494. }
  495. /* We stupidly exposed 'whence':'int' in our qapi */
  496. whence = ga_parse_whence(whence_code, &err);
  497. if (err) {
  498. error_propagate(errp, err);
  499. return NULL;
  500. }
  501. fh = gfh->fh;
  502. ret = fseek(fh, offset, whence);
  503. if (ret == -1) {
  504. error_setg_errno(errp, errno, "failed to seek file");
  505. if (errno == ESPIPE) {
  506. /* file is non-seekable, stdio shouldn't be buffering anyways */
  507. gfh->state = RW_STATE_NEW;
  508. }
  509. } else {
  510. seek_data = g_new0(GuestFileSeek, 1);
  511. seek_data->position = ftell(fh);
  512. seek_data->eof = feof(fh);
  513. gfh->state = RW_STATE_NEW;
  514. }
  515. clearerr(fh);
  516. return seek_data;
  517. }
  518. void qmp_guest_file_flush(int64_t handle, Error **errp)
  519. {
  520. GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
  521. FILE *fh;
  522. int ret;
  523. if (!gfh) {
  524. return;
  525. }
  526. fh = gfh->fh;
  527. ret = fflush(fh);
  528. if (ret == EOF) {
  529. error_setg_errno(errp, errno, "failed to flush file");
  530. } else {
  531. gfh->state = RW_STATE_NEW;
  532. }
  533. }
  534. #if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
  535. void free_fs_mount_list(FsMountList *mounts)
  536. {
  537. FsMount *mount, *temp;
  538. if (!mounts) {
  539. return;
  540. }
  541. QTAILQ_FOREACH_SAFE(mount, mounts, next, temp) {
  542. QTAILQ_REMOVE(mounts, mount, next);
  543. g_free(mount->dirname);
  544. g_free(mount->devtype);
  545. g_free(mount);
  546. }
  547. }
  548. #endif
  549. #if defined(CONFIG_FSFREEZE)
  550. typedef enum {
  551. FSFREEZE_HOOK_THAW = 0,
  552. FSFREEZE_HOOK_FREEZE,
  553. } FsfreezeHookArg;
  554. static const char *fsfreeze_hook_arg_string[] = {
  555. "thaw",
  556. "freeze",
  557. };
  558. static void execute_fsfreeze_hook(FsfreezeHookArg arg, Error **errp)
  559. {
  560. int status;
  561. pid_t pid;
  562. const char *hook;
  563. const char *arg_str = fsfreeze_hook_arg_string[arg];
  564. Error *local_err = NULL;
  565. hook = ga_fsfreeze_hook(ga_state);
  566. if (!hook) {
  567. return;
  568. }
  569. if (access(hook, X_OK) != 0) {
  570. error_setg_errno(errp, errno, "can't access fsfreeze hook '%s'", hook);
  571. return;
  572. }
  573. slog("executing fsfreeze hook with arg '%s'", arg_str);
  574. pid = fork();
  575. if (pid == 0) {
  576. setsid();
  577. reopen_fd_to_null(0);
  578. reopen_fd_to_null(1);
  579. reopen_fd_to_null(2);
  580. execl(hook, hook, arg_str, NULL);
  581. _exit(EXIT_FAILURE);
  582. } else if (pid < 0) {
  583. error_setg_errno(errp, errno, "failed to create child process");
  584. return;
  585. }
  586. ga_wait_child(pid, &status, &local_err);
  587. if (local_err) {
  588. error_propagate(errp, local_err);
  589. return;
  590. }
  591. if (!WIFEXITED(status)) {
  592. error_setg(errp, "fsfreeze hook has terminated abnormally");
  593. return;
  594. }
  595. status = WEXITSTATUS(status);
  596. if (status) {
  597. error_setg(errp, "fsfreeze hook has failed with status %d", status);
  598. return;
  599. }
  600. }
  601. /*
  602. * Return status of freeze/thaw
  603. */
  604. GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
  605. {
  606. if (ga_is_frozen(ga_state)) {
  607. return GUEST_FSFREEZE_STATUS_FROZEN;
  608. }
  609. return GUEST_FSFREEZE_STATUS_THAWED;
  610. }
  611. int64_t qmp_guest_fsfreeze_freeze(Error **errp)
  612. {
  613. return qmp_guest_fsfreeze_freeze_list(false, NULL, errp);
  614. }
  615. int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
  616. strList *mountpoints,
  617. Error **errp)
  618. {
  619. int ret;
  620. FsMountList mounts;
  621. Error *local_err = NULL;
  622. slog("guest-fsfreeze called");
  623. execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE, &local_err);
  624. if (local_err) {
  625. error_propagate(errp, local_err);
  626. return -1;
  627. }
  628. QTAILQ_INIT(&mounts);
  629. if (!build_fs_mount_list(&mounts, &local_err)) {
  630. error_propagate(errp, local_err);
  631. return -1;
  632. }
  633. /* cannot risk guest agent blocking itself on a write in this state */
  634. ga_set_frozen(ga_state);
  635. ret = qmp_guest_fsfreeze_do_freeze_list(has_mountpoints, mountpoints,
  636. mounts, errp);
  637. free_fs_mount_list(&mounts);
  638. /* We may not issue any FIFREEZE here.
  639. * Just unset ga_state here and ready for the next call.
  640. */
  641. if (ret == 0) {
  642. ga_unset_frozen(ga_state);
  643. } else if (ret < 0) {
  644. qmp_guest_fsfreeze_thaw(NULL);
  645. }
  646. return ret;
  647. }
  648. int64_t qmp_guest_fsfreeze_thaw(Error **errp)
  649. {
  650. int ret;
  651. ret = qmp_guest_fsfreeze_do_thaw(errp);
  652. if (ret >= 0) {
  653. ga_unset_frozen(ga_state);
  654. execute_fsfreeze_hook(FSFREEZE_HOOK_THAW, errp);
  655. } else {
  656. ret = 0;
  657. }
  658. return ret;
  659. }
  660. static void guest_fsfreeze_cleanup(void)
  661. {
  662. Error *err = NULL;
  663. if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
  664. qmp_guest_fsfreeze_thaw(&err);
  665. if (err) {
  666. slog("failed to clean up frozen filesystems: %s",
  667. error_get_pretty(err));
  668. error_free(err);
  669. }
  670. }
  671. }
  672. #endif
  673. /* linux-specific implementations. avoid this if at all possible. */
  674. #if defined(__linux__)
  675. #if defined(CONFIG_FSFREEZE)
  676. static char *get_pci_driver(char const *syspath, int pathlen, Error **errp)
  677. {
  678. char *path;
  679. char *dpath;
  680. char *driver = NULL;
  681. char buf[PATH_MAX];
  682. ssize_t len;
  683. path = g_strndup(syspath, pathlen);
  684. dpath = g_strdup_printf("%s/driver", path);
  685. len = readlink(dpath, buf, sizeof(buf) - 1);
  686. if (len != -1) {
  687. buf[len] = 0;
  688. driver = g_path_get_basename(buf);
  689. }
  690. g_free(dpath);
  691. g_free(path);
  692. return driver;
  693. }
  694. static int compare_uint(const void *_a, const void *_b)
  695. {
  696. unsigned int a = *(unsigned int *)_a;
  697. unsigned int b = *(unsigned int *)_b;
  698. return a < b ? -1 : a > b ? 1 : 0;
  699. }
  700. /* Walk the specified sysfs and build a sorted list of host or ata numbers */
  701. static int build_hosts(char const *syspath, char const *host, bool ata,
  702. unsigned int *hosts, int hosts_max, Error **errp)
  703. {
  704. char *path;
  705. DIR *dir;
  706. struct dirent *entry;
  707. int i = 0;
  708. path = g_strndup(syspath, host - syspath);
  709. dir = opendir(path);
  710. if (!dir) {
  711. error_setg_errno(errp, errno, "opendir(\"%s\")", path);
  712. g_free(path);
  713. return -1;
  714. }
  715. while (i < hosts_max) {
  716. entry = readdir(dir);
  717. if (!entry) {
  718. break;
  719. }
  720. if (ata && sscanf(entry->d_name, "ata%d", hosts + i) == 1) {
  721. ++i;
  722. } else if (!ata && sscanf(entry->d_name, "host%d", hosts + i) == 1) {
  723. ++i;
  724. }
  725. }
  726. qsort(hosts, i, sizeof(hosts[0]), compare_uint);
  727. g_free(path);
  728. closedir(dir);
  729. return i;
  730. }
  731. /*
  732. * Store disk device info for devices on the PCI bus.
  733. * Returns true if information has been stored, or false for failure.
  734. */
  735. static bool build_guest_fsinfo_for_pci_dev(char const *syspath,
  736. GuestDiskAddress *disk,
  737. Error **errp)
  738. {
  739. unsigned int pci[4], host, hosts[8], tgt[3];
  740. int i, nhosts = 0, pcilen;
  741. GuestPCIAddress *pciaddr = disk->pci_controller;
  742. bool has_ata = false, has_host = false, has_tgt = false;
  743. char *p, *q, *driver = NULL;
  744. bool ret = false;
  745. p = strstr(syspath, "/devices/pci");
  746. if (!p || sscanf(p + 12, "%*x:%*x/%x:%x:%x.%x%n",
  747. pci, pci + 1, pci + 2, pci + 3, &pcilen) < 4) {
  748. g_debug("only pci device is supported: sysfs path '%s'", syspath);
  749. return false;
  750. }
  751. p += 12 + pcilen;
  752. while (true) {
  753. driver = get_pci_driver(syspath, p - syspath, errp);
  754. if (driver && (g_str_equal(driver, "ata_piix") ||
  755. g_str_equal(driver, "sym53c8xx") ||
  756. g_str_equal(driver, "virtio-pci") ||
  757. g_str_equal(driver, "ahci") ||
  758. g_str_equal(driver, "nvme") ||
  759. g_str_equal(driver, "xhci_hcd") ||
  760. g_str_equal(driver, "ehci-pci"))) {
  761. break;
  762. }
  763. g_free(driver);
  764. if (sscanf(p, "/%x:%x:%x.%x%n",
  765. pci, pci + 1, pci + 2, pci + 3, &pcilen) == 4) {
  766. p += pcilen;
  767. continue;
  768. }
  769. g_debug("unsupported driver or sysfs path '%s'", syspath);
  770. return false;
  771. }
  772. p = strstr(syspath, "/target");
  773. if (p && sscanf(p + 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
  774. tgt, tgt + 1, tgt + 2) == 3) {
  775. has_tgt = true;
  776. }
  777. p = strstr(syspath, "/ata");
  778. if (p) {
  779. q = p + 4;
  780. has_ata = true;
  781. } else {
  782. p = strstr(syspath, "/host");
  783. q = p + 5;
  784. }
  785. if (p && sscanf(q, "%u", &host) == 1) {
  786. has_host = true;
  787. nhosts = build_hosts(syspath, p, has_ata, hosts,
  788. ARRAY_SIZE(hosts), errp);
  789. if (nhosts < 0) {
  790. goto cleanup;
  791. }
  792. }
  793. pciaddr->domain = pci[0];
  794. pciaddr->bus = pci[1];
  795. pciaddr->slot = pci[2];
  796. pciaddr->function = pci[3];
  797. if (strcmp(driver, "ata_piix") == 0) {
  798. /* a host per ide bus, target*:0:<unit>:0 */
  799. if (!has_host || !has_tgt) {
  800. g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
  801. goto cleanup;
  802. }
  803. for (i = 0; i < nhosts; i++) {
  804. if (host == hosts[i]) {
  805. disk->bus_type = GUEST_DISK_BUS_TYPE_IDE;
  806. disk->bus = i;
  807. disk->unit = tgt[1];
  808. break;
  809. }
  810. }
  811. if (i >= nhosts) {
  812. g_debug("no host for '%s' (driver '%s')", syspath, driver);
  813. goto cleanup;
  814. }
  815. } else if (strcmp(driver, "sym53c8xx") == 0) {
  816. /* scsi(LSI Logic): target*:0:<unit>:0 */
  817. if (!has_tgt) {
  818. g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
  819. goto cleanup;
  820. }
  821. disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
  822. disk->unit = tgt[1];
  823. } else if (strcmp(driver, "virtio-pci") == 0) {
  824. if (has_tgt) {
  825. /* virtio-scsi: target*:0:0:<unit> */
  826. disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
  827. disk->unit = tgt[2];
  828. } else {
  829. /* virtio-blk: 1 disk per 1 device */
  830. disk->bus_type = GUEST_DISK_BUS_TYPE_VIRTIO;
  831. }
  832. } else if (strcmp(driver, "ahci") == 0) {
  833. /* ahci: 1 host per 1 unit */
  834. if (!has_host || !has_tgt) {
  835. g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
  836. goto cleanup;
  837. }
  838. for (i = 0; i < nhosts; i++) {
  839. if (host == hosts[i]) {
  840. disk->unit = i;
  841. disk->bus_type = GUEST_DISK_BUS_TYPE_SATA;
  842. break;
  843. }
  844. }
  845. if (i >= nhosts) {
  846. g_debug("no host for '%s' (driver '%s')", syspath, driver);
  847. goto cleanup;
  848. }
  849. } else if (strcmp(driver, "nvme") == 0) {
  850. disk->bus_type = GUEST_DISK_BUS_TYPE_NVME;
  851. } else if (strcmp(driver, "ehci-pci") == 0 || strcmp(driver, "xhci_hcd") == 0) {
  852. disk->bus_type = GUEST_DISK_BUS_TYPE_USB;
  853. } else {
  854. g_debug("unknown driver '%s' (sysfs path '%s')", driver, syspath);
  855. goto cleanup;
  856. }
  857. ret = true;
  858. cleanup:
  859. g_free(driver);
  860. return ret;
  861. }
  862. /*
  863. * Store disk device info for non-PCI virtio devices (for example s390x
  864. * channel I/O devices). Returns true if information has been stored, or
  865. * false for failure.
  866. */
  867. static bool build_guest_fsinfo_for_nonpci_virtio(char const *syspath,
  868. GuestDiskAddress *disk,
  869. Error **errp)
  870. {
  871. unsigned int tgt[3];
  872. char *p;
  873. if (!strstr(syspath, "/virtio") || !strstr(syspath, "/block")) {
  874. g_debug("Unsupported virtio device '%s'", syspath);
  875. return false;
  876. }
  877. p = strstr(syspath, "/target");
  878. if (p && sscanf(p + 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
  879. &tgt[0], &tgt[1], &tgt[2]) == 3) {
  880. /* virtio-scsi: target*:0:<target>:<unit> */
  881. disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
  882. disk->bus = tgt[0];
  883. disk->target = tgt[1];
  884. disk->unit = tgt[2];
  885. } else {
  886. /* virtio-blk: 1 disk per 1 device */
  887. disk->bus_type = GUEST_DISK_BUS_TYPE_VIRTIO;
  888. }
  889. return true;
  890. }
  891. /*
  892. * Store disk device info for CCW devices (s390x channel I/O devices).
  893. * Returns true if information has been stored, or false for failure.
  894. */
  895. static bool build_guest_fsinfo_for_ccw_dev(char const *syspath,
  896. GuestDiskAddress *disk,
  897. Error **errp)
  898. {
  899. unsigned int cssid, ssid, subchno, devno;
  900. char *p;
  901. p = strstr(syspath, "/devices/css");
  902. if (!p || sscanf(p + 12, "%*x/%x.%x.%x/%*x.%*x.%x/",
  903. &cssid, &ssid, &subchno, &devno) < 4) {
  904. g_debug("could not parse ccw device sysfs path: %s", syspath);
  905. return false;
  906. }
  907. disk->ccw_address = g_new0(GuestCCWAddress, 1);
  908. disk->ccw_address->cssid = cssid;
  909. disk->ccw_address->ssid = ssid;
  910. disk->ccw_address->subchno = subchno;
  911. disk->ccw_address->devno = devno;
  912. if (strstr(p, "/virtio")) {
  913. build_guest_fsinfo_for_nonpci_virtio(syspath, disk, errp);
  914. }
  915. return true;
  916. }
  917. /* Store disk device info specified by @sysfs into @fs */
  918. static void build_guest_fsinfo_for_real_device(char const *syspath,
  919. GuestFilesystemInfo *fs,
  920. Error **errp)
  921. {
  922. GuestDiskAddress *disk;
  923. GuestPCIAddress *pciaddr;
  924. bool has_hwinf;
  925. #ifdef CONFIG_LIBUDEV
  926. struct udev *udev = NULL;
  927. struct udev_device *udevice = NULL;
  928. #endif
  929. pciaddr = g_new0(GuestPCIAddress, 1);
  930. pciaddr->domain = -1; /* -1 means field is invalid */
  931. pciaddr->bus = -1;
  932. pciaddr->slot = -1;
  933. pciaddr->function = -1;
  934. disk = g_new0(GuestDiskAddress, 1);
  935. disk->pci_controller = pciaddr;
  936. disk->bus_type = GUEST_DISK_BUS_TYPE_UNKNOWN;
  937. #ifdef CONFIG_LIBUDEV
  938. udev = udev_new();
  939. udevice = udev_device_new_from_syspath(udev, syspath);
  940. if (udev == NULL || udevice == NULL) {
  941. g_debug("failed to query udev");
  942. } else {
  943. const char *devnode, *serial;
  944. devnode = udev_device_get_devnode(udevice);
  945. if (devnode != NULL) {
  946. disk->dev = g_strdup(devnode);
  947. }
  948. serial = udev_device_get_property_value(udevice, "ID_SERIAL");
  949. if (serial != NULL && *serial != 0) {
  950. disk->serial = g_strdup(serial);
  951. }
  952. }
  953. udev_unref(udev);
  954. udev_device_unref(udevice);
  955. #endif
  956. if (strstr(syspath, "/devices/pci")) {
  957. has_hwinf = build_guest_fsinfo_for_pci_dev(syspath, disk, errp);
  958. } else if (strstr(syspath, "/devices/css")) {
  959. has_hwinf = build_guest_fsinfo_for_ccw_dev(syspath, disk, errp);
  960. } else if (strstr(syspath, "/virtio")) {
  961. has_hwinf = build_guest_fsinfo_for_nonpci_virtio(syspath, disk, errp);
  962. } else {
  963. g_debug("Unsupported device type for '%s'", syspath);
  964. has_hwinf = false;
  965. }
  966. if (has_hwinf || disk->dev || disk->serial) {
  967. QAPI_LIST_PREPEND(fs->disk, disk);
  968. } else {
  969. qapi_free_GuestDiskAddress(disk);
  970. }
  971. }
  972. static void build_guest_fsinfo_for_device(char const *devpath,
  973. GuestFilesystemInfo *fs,
  974. Error **errp);
  975. /* Store a list of slave devices of virtual volume specified by @syspath into
  976. * @fs */
  977. static void build_guest_fsinfo_for_virtual_device(char const *syspath,
  978. GuestFilesystemInfo *fs,
  979. Error **errp)
  980. {
  981. Error *err = NULL;
  982. DIR *dir;
  983. char *dirpath;
  984. struct dirent *entry;
  985. dirpath = g_strdup_printf("%s/slaves", syspath);
  986. dir = opendir(dirpath);
  987. if (!dir) {
  988. if (errno != ENOENT) {
  989. error_setg_errno(errp, errno, "opendir(\"%s\")", dirpath);
  990. }
  991. g_free(dirpath);
  992. return;
  993. }
  994. for (;;) {
  995. errno = 0;
  996. entry = readdir(dir);
  997. if (entry == NULL) {
  998. if (errno) {
  999. error_setg_errno(errp, errno, "readdir(\"%s\")", dirpath);
  1000. }
  1001. break;
  1002. }
  1003. if (entry->d_type == DT_LNK) {
  1004. char *path;
  1005. g_debug(" slave device '%s'", entry->d_name);
  1006. path = g_strdup_printf("%s/slaves/%s", syspath, entry->d_name);
  1007. build_guest_fsinfo_for_device(path, fs, &err);
  1008. g_free(path);
  1009. if (err) {
  1010. error_propagate(errp, err);
  1011. break;
  1012. }
  1013. }
  1014. }
  1015. g_free(dirpath);
  1016. closedir(dir);
  1017. }
  1018. static bool is_disk_virtual(const char *devpath, Error **errp)
  1019. {
  1020. g_autofree char *syspath = realpath(devpath, NULL);
  1021. if (!syspath) {
  1022. error_setg_errno(errp, errno, "realpath(\"%s\")", devpath);
  1023. return false;
  1024. }
  1025. return strstr(syspath, "/devices/virtual/block/") != NULL;
  1026. }
  1027. /* Dispatch to functions for virtual/real device */
  1028. static void build_guest_fsinfo_for_device(char const *devpath,
  1029. GuestFilesystemInfo *fs,
  1030. Error **errp)
  1031. {
  1032. ERRP_GUARD();
  1033. g_autofree char *syspath = NULL;
  1034. bool is_virtual = false;
  1035. syspath = realpath(devpath, NULL);
  1036. if (!syspath) {
  1037. if (errno != ENOENT) {
  1038. error_setg_errno(errp, errno, "realpath(\"%s\")", devpath);
  1039. return;
  1040. }
  1041. /* ENOENT: This devpath may not exist because of container config */
  1042. if (!fs->name) {
  1043. fs->name = g_path_get_basename(devpath);
  1044. }
  1045. return;
  1046. }
  1047. if (!fs->name) {
  1048. fs->name = g_path_get_basename(syspath);
  1049. }
  1050. g_debug(" parse sysfs path '%s'", syspath);
  1051. is_virtual = is_disk_virtual(syspath, errp);
  1052. if (*errp != NULL) {
  1053. return;
  1054. }
  1055. if (is_virtual) {
  1056. build_guest_fsinfo_for_virtual_device(syspath, fs, errp);
  1057. } else {
  1058. build_guest_fsinfo_for_real_device(syspath, fs, errp);
  1059. }
  1060. }
  1061. #ifdef CONFIG_LIBUDEV
  1062. /*
  1063. * Wrapper around build_guest_fsinfo_for_device() for getting just
  1064. * the disk address.
  1065. */
  1066. static GuestDiskAddress *get_disk_address(const char *syspath, Error **errp)
  1067. {
  1068. g_autoptr(GuestFilesystemInfo) fs = NULL;
  1069. fs = g_new0(GuestFilesystemInfo, 1);
  1070. build_guest_fsinfo_for_device(syspath, fs, errp);
  1071. if (fs->disk != NULL) {
  1072. return g_steal_pointer(&fs->disk->value);
  1073. }
  1074. return NULL;
  1075. }
  1076. static char *get_alias_for_syspath(const char *syspath)
  1077. {
  1078. struct udev *udev = NULL;
  1079. struct udev_device *udevice = NULL;
  1080. char *ret = NULL;
  1081. udev = udev_new();
  1082. if (udev == NULL) {
  1083. g_debug("failed to query udev");
  1084. goto out;
  1085. }
  1086. udevice = udev_device_new_from_syspath(udev, syspath);
  1087. if (udevice == NULL) {
  1088. g_debug("failed to query udev for path: %s", syspath);
  1089. goto out;
  1090. } else {
  1091. const char *alias = udev_device_get_property_value(
  1092. udevice, "DM_NAME");
  1093. /*
  1094. * NULL means there was an error and empty string means there is no
  1095. * alias. In case of no alias we return NULL instead of empty string.
  1096. */
  1097. if (alias == NULL) {
  1098. g_debug("failed to query udev for device alias for: %s",
  1099. syspath);
  1100. } else if (*alias != 0) {
  1101. ret = g_strdup(alias);
  1102. }
  1103. }
  1104. out:
  1105. udev_unref(udev);
  1106. udev_device_unref(udevice);
  1107. return ret;
  1108. }
  1109. static char *get_device_for_syspath(const char *syspath)
  1110. {
  1111. struct udev *udev = NULL;
  1112. struct udev_device *udevice = NULL;
  1113. char *ret = NULL;
  1114. udev = udev_new();
  1115. if (udev == NULL) {
  1116. g_debug("failed to query udev");
  1117. goto out;
  1118. }
  1119. udevice = udev_device_new_from_syspath(udev, syspath);
  1120. if (udevice == NULL) {
  1121. g_debug("failed to query udev for path: %s", syspath);
  1122. goto out;
  1123. } else {
  1124. ret = g_strdup(udev_device_get_devnode(udevice));
  1125. }
  1126. out:
  1127. udev_unref(udev);
  1128. udev_device_unref(udevice);
  1129. return ret;
  1130. }
  1131. static void get_disk_deps(const char *disk_dir, GuestDiskInfo *disk)
  1132. {
  1133. g_autofree char *deps_dir = NULL;
  1134. const gchar *dep;
  1135. GDir *dp_deps = NULL;
  1136. /* List dependent disks */
  1137. deps_dir = g_strdup_printf("%s/slaves", disk_dir);
  1138. g_debug(" listing entries in: %s", deps_dir);
  1139. dp_deps = g_dir_open(deps_dir, 0, NULL);
  1140. if (dp_deps == NULL) {
  1141. g_debug("failed to list entries in %s", deps_dir);
  1142. return;
  1143. }
  1144. disk->has_dependencies = true;
  1145. while ((dep = g_dir_read_name(dp_deps)) != NULL) {
  1146. g_autofree char *dep_dir = NULL;
  1147. char *dev_name;
  1148. /* Add dependent disks */
  1149. dep_dir = g_strdup_printf("%s/%s", deps_dir, dep);
  1150. dev_name = get_device_for_syspath(dep_dir);
  1151. if (dev_name != NULL) {
  1152. g_debug(" adding dependent device: %s", dev_name);
  1153. QAPI_LIST_PREPEND(disk->dependencies, dev_name);
  1154. }
  1155. }
  1156. g_dir_close(dp_deps);
  1157. }
  1158. /*
  1159. * Detect partitions subdirectory, name is "<disk_name><number>" or
  1160. * "<disk_name>p<number>"
  1161. *
  1162. * @disk_name -- last component of /sys path (e.g. sda)
  1163. * @disk_dir -- sys path of the disk (e.g. /sys/block/sda)
  1164. * @disk_dev -- device node of the disk (e.g. /dev/sda)
  1165. */
  1166. static GuestDiskInfoList *get_disk_partitions(
  1167. GuestDiskInfoList *list,
  1168. const char *disk_name, const char *disk_dir,
  1169. const char *disk_dev)
  1170. {
  1171. GuestDiskInfoList *ret = list;
  1172. struct dirent *de_disk;
  1173. DIR *dp_disk = NULL;
  1174. size_t len = strlen(disk_name);
  1175. dp_disk = opendir(disk_dir);
  1176. while ((de_disk = readdir(dp_disk)) != NULL) {
  1177. g_autofree char *partition_dir = NULL;
  1178. char *dev_name;
  1179. GuestDiskInfo *partition;
  1180. if (!(de_disk->d_type & DT_DIR)) {
  1181. continue;
  1182. }
  1183. if (!(strncmp(disk_name, de_disk->d_name, len) == 0 &&
  1184. ((*(de_disk->d_name + len) == 'p' &&
  1185. isdigit(*(de_disk->d_name + len + 1))) ||
  1186. isdigit(*(de_disk->d_name + len))))) {
  1187. continue;
  1188. }
  1189. partition_dir = g_strdup_printf("%s/%s",
  1190. disk_dir, de_disk->d_name);
  1191. dev_name = get_device_for_syspath(partition_dir);
  1192. if (dev_name == NULL) {
  1193. g_debug("Failed to get device name for syspath: %s",
  1194. disk_dir);
  1195. continue;
  1196. }
  1197. partition = g_new0(GuestDiskInfo, 1);
  1198. partition->name = dev_name;
  1199. partition->partition = true;
  1200. partition->has_dependencies = true;
  1201. /* Add parent disk as dependent for easier tracking of hierarchy */
  1202. QAPI_LIST_PREPEND(partition->dependencies, g_strdup(disk_dev));
  1203. QAPI_LIST_PREPEND(ret, partition);
  1204. }
  1205. closedir(dp_disk);
  1206. return ret;
  1207. }
  1208. static void get_nvme_smart(GuestDiskInfo *disk)
  1209. {
  1210. int fd;
  1211. GuestNVMeSmart *smart;
  1212. NvmeSmartLog log = {0};
  1213. struct nvme_admin_cmd cmd = {
  1214. .opcode = NVME_ADM_CMD_GET_LOG_PAGE,
  1215. .nsid = NVME_NSID_BROADCAST,
  1216. .addr = (uintptr_t)&log,
  1217. .data_len = sizeof(log),
  1218. .cdw10 = NVME_LOG_SMART_INFO | (1 << 15) /* RAE bit */
  1219. | (((sizeof(log) >> 2) - 1) << 16)
  1220. };
  1221. fd = qga_open_cloexec(disk->name, O_RDONLY, 0);
  1222. if (fd == -1) {
  1223. g_debug("Failed to open device: %s: %s", disk->name, g_strerror(errno));
  1224. return;
  1225. }
  1226. if (ioctl(fd, NVME_IOCTL_ADMIN_CMD, &cmd)) {
  1227. g_debug("Failed to get smart: %s: %s", disk->name, g_strerror(errno));
  1228. close(fd);
  1229. return;
  1230. }
  1231. disk->smart = g_new0(GuestDiskSmart, 1);
  1232. disk->smart->type = GUEST_DISK_BUS_TYPE_NVME;
  1233. smart = &disk->smart->u.nvme;
  1234. smart->critical_warning = log.critical_warning;
  1235. smart->temperature = lduw_le_p(&log.temperature); /* unaligned field */
  1236. smart->available_spare = log.available_spare;
  1237. smart->available_spare_threshold = log.available_spare_threshold;
  1238. smart->percentage_used = log.percentage_used;
  1239. smart->data_units_read_lo = le64_to_cpu(log.data_units_read[0]);
  1240. smart->data_units_read_hi = le64_to_cpu(log.data_units_read[1]);
  1241. smart->data_units_written_lo = le64_to_cpu(log.data_units_written[0]);
  1242. smart->data_units_written_hi = le64_to_cpu(log.data_units_written[1]);
  1243. smart->host_read_commands_lo = le64_to_cpu(log.host_read_commands[0]);
  1244. smart->host_read_commands_hi = le64_to_cpu(log.host_read_commands[1]);
  1245. smart->host_write_commands_lo = le64_to_cpu(log.host_write_commands[0]);
  1246. smart->host_write_commands_hi = le64_to_cpu(log.host_write_commands[1]);
  1247. smart->controller_busy_time_lo = le64_to_cpu(log.controller_busy_time[0]);
  1248. smart->controller_busy_time_hi = le64_to_cpu(log.controller_busy_time[1]);
  1249. smart->power_cycles_lo = le64_to_cpu(log.power_cycles[0]);
  1250. smart->power_cycles_hi = le64_to_cpu(log.power_cycles[1]);
  1251. smart->power_on_hours_lo = le64_to_cpu(log.power_on_hours[0]);
  1252. smart->power_on_hours_hi = le64_to_cpu(log.power_on_hours[1]);
  1253. smart->unsafe_shutdowns_lo = le64_to_cpu(log.unsafe_shutdowns[0]);
  1254. smart->unsafe_shutdowns_hi = le64_to_cpu(log.unsafe_shutdowns[1]);
  1255. smart->media_errors_lo = le64_to_cpu(log.media_errors[0]);
  1256. smart->media_errors_hi = le64_to_cpu(log.media_errors[1]);
  1257. smart->number_of_error_log_entries_lo =
  1258. le64_to_cpu(log.number_of_error_log_entries[0]);
  1259. smart->number_of_error_log_entries_hi =
  1260. le64_to_cpu(log.number_of_error_log_entries[1]);
  1261. close(fd);
  1262. }
  1263. static void get_disk_smart(GuestDiskInfo *disk)
  1264. {
  1265. if (disk->address
  1266. && (disk->address->bus_type == GUEST_DISK_BUS_TYPE_NVME)) {
  1267. get_nvme_smart(disk);
  1268. }
  1269. }
  1270. GuestDiskInfoList *qmp_guest_get_disks(Error **errp)
  1271. {
  1272. GuestDiskInfoList *ret = NULL;
  1273. GuestDiskInfo *disk;
  1274. DIR *dp = NULL;
  1275. struct dirent *de = NULL;
  1276. g_debug("listing /sys/block directory");
  1277. dp = opendir("/sys/block");
  1278. if (dp == NULL) {
  1279. error_setg_errno(errp, errno, "Can't open directory \"/sys/block\"");
  1280. return NULL;
  1281. }
  1282. while ((de = readdir(dp)) != NULL) {
  1283. g_autofree char *disk_dir = NULL, *line = NULL,
  1284. *size_path = NULL;
  1285. char *dev_name;
  1286. Error *local_err = NULL;
  1287. if (de->d_type != DT_LNK) {
  1288. g_debug(" skipping entry: %s", de->d_name);
  1289. continue;
  1290. }
  1291. /* Check size and skip zero-sized disks */
  1292. g_debug(" checking disk size");
  1293. size_path = g_strdup_printf("/sys/block/%s/size", de->d_name);
  1294. if (!g_file_get_contents(size_path, &line, NULL, NULL)) {
  1295. g_debug(" failed to read disk size");
  1296. continue;
  1297. }
  1298. if (g_strcmp0(line, "0\n") == 0) {
  1299. g_debug(" skipping zero-sized disk");
  1300. continue;
  1301. }
  1302. g_debug(" adding %s", de->d_name);
  1303. disk_dir = g_strdup_printf("/sys/block/%s", de->d_name);
  1304. dev_name = get_device_for_syspath(disk_dir);
  1305. if (dev_name == NULL) {
  1306. g_debug("Failed to get device name for syspath: %s",
  1307. disk_dir);
  1308. continue;
  1309. }
  1310. disk = g_new0(GuestDiskInfo, 1);
  1311. disk->name = dev_name;
  1312. disk->partition = false;
  1313. disk->alias = get_alias_for_syspath(disk_dir);
  1314. QAPI_LIST_PREPEND(ret, disk);
  1315. /* Get address for non-virtual devices */
  1316. bool is_virtual = is_disk_virtual(disk_dir, &local_err);
  1317. if (local_err != NULL) {
  1318. g_debug(" failed to check disk path, ignoring error: %s",
  1319. error_get_pretty(local_err));
  1320. error_free(local_err);
  1321. local_err = NULL;
  1322. /* Don't try to get the address */
  1323. is_virtual = true;
  1324. }
  1325. if (!is_virtual) {
  1326. disk->address = get_disk_address(disk_dir, &local_err);
  1327. if (local_err != NULL) {
  1328. g_debug(" failed to get device info, ignoring error: %s",
  1329. error_get_pretty(local_err));
  1330. error_free(local_err);
  1331. local_err = NULL;
  1332. }
  1333. }
  1334. get_disk_deps(disk_dir, disk);
  1335. get_disk_smart(disk);
  1336. ret = get_disk_partitions(ret, de->d_name, disk_dir, dev_name);
  1337. }
  1338. closedir(dp);
  1339. return ret;
  1340. }
  1341. #else
  1342. GuestDiskInfoList *qmp_guest_get_disks(Error **errp)
  1343. {
  1344. error_setg(errp, QERR_UNSUPPORTED);
  1345. return NULL;
  1346. }
  1347. #endif
  1348. /* Return a list of the disk device(s)' info which @mount lies on */
  1349. static GuestFilesystemInfo *build_guest_fsinfo(struct FsMount *mount,
  1350. Error **errp)
  1351. {
  1352. GuestFilesystemInfo *fs = g_malloc0(sizeof(*fs));
  1353. struct statvfs buf;
  1354. unsigned long used, nonroot_total, fr_size;
  1355. char *devpath = g_strdup_printf("/sys/dev/block/%u:%u",
  1356. mount->devmajor, mount->devminor);
  1357. fs->mountpoint = g_strdup(mount->dirname);
  1358. fs->type = g_strdup(mount->devtype);
  1359. build_guest_fsinfo_for_device(devpath, fs, errp);
  1360. if (statvfs(fs->mountpoint, &buf) == 0) {
  1361. fr_size = buf.f_frsize;
  1362. used = buf.f_blocks - buf.f_bfree;
  1363. nonroot_total = used + buf.f_bavail;
  1364. fs->used_bytes = used * fr_size;
  1365. fs->total_bytes = nonroot_total * fr_size;
  1366. fs->has_total_bytes = true;
  1367. fs->has_used_bytes = true;
  1368. }
  1369. g_free(devpath);
  1370. return fs;
  1371. }
  1372. GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
  1373. {
  1374. FsMountList mounts;
  1375. struct FsMount *mount;
  1376. GuestFilesystemInfoList *ret = NULL;
  1377. Error *local_err = NULL;
  1378. QTAILQ_INIT(&mounts);
  1379. if (!build_fs_mount_list(&mounts, &local_err)) {
  1380. error_propagate(errp, local_err);
  1381. return NULL;
  1382. }
  1383. QTAILQ_FOREACH(mount, &mounts, next) {
  1384. g_debug("Building guest fsinfo for '%s'", mount->dirname);
  1385. QAPI_LIST_PREPEND(ret, build_guest_fsinfo(mount, &local_err));
  1386. if (local_err) {
  1387. error_propagate(errp, local_err);
  1388. qapi_free_GuestFilesystemInfoList(ret);
  1389. ret = NULL;
  1390. break;
  1391. }
  1392. }
  1393. free_fs_mount_list(&mounts);
  1394. return ret;
  1395. }
  1396. #endif /* CONFIG_FSFREEZE */
  1397. #if defined(CONFIG_FSTRIM)
  1398. /*
  1399. * Walk list of mounted file systems in the guest, and trim them.
  1400. */
  1401. GuestFilesystemTrimResponse *
  1402. qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
  1403. {
  1404. GuestFilesystemTrimResponse *response;
  1405. GuestFilesystemTrimResult *result;
  1406. int ret = 0;
  1407. FsMountList mounts;
  1408. struct FsMount *mount;
  1409. int fd;
  1410. struct fstrim_range r;
  1411. slog("guest-fstrim called");
  1412. QTAILQ_INIT(&mounts);
  1413. if (!build_fs_mount_list(&mounts, errp)) {
  1414. return NULL;
  1415. }
  1416. response = g_malloc0(sizeof(*response));
  1417. QTAILQ_FOREACH(mount, &mounts, next) {
  1418. result = g_malloc0(sizeof(*result));
  1419. result->path = g_strdup(mount->dirname);
  1420. QAPI_LIST_PREPEND(response->paths, result);
  1421. fd = qga_open_cloexec(mount->dirname, O_RDONLY, 0);
  1422. if (fd == -1) {
  1423. result->error = g_strdup_printf("failed to open: %s",
  1424. strerror(errno));
  1425. continue;
  1426. }
  1427. /* We try to cull filesystems we know won't work in advance, but other
  1428. * filesystems may not implement fstrim for less obvious reasons.
  1429. * These will report EOPNOTSUPP; while in some other cases ENOTTY
  1430. * will be reported (e.g. CD-ROMs).
  1431. * Any other error means an unexpected error.
  1432. */
  1433. r.start = 0;
  1434. r.len = -1;
  1435. r.minlen = has_minimum ? minimum : 0;
  1436. ret = ioctl(fd, FITRIM, &r);
  1437. if (ret == -1) {
  1438. if (errno == ENOTTY || errno == EOPNOTSUPP) {
  1439. result->error = g_strdup("trim not supported");
  1440. } else {
  1441. result->error = g_strdup_printf("failed to trim: %s",
  1442. strerror(errno));
  1443. }
  1444. close(fd);
  1445. continue;
  1446. }
  1447. result->has_minimum = true;
  1448. result->minimum = r.minlen;
  1449. result->has_trimmed = true;
  1450. result->trimmed = r.len;
  1451. close(fd);
  1452. }
  1453. free_fs_mount_list(&mounts);
  1454. return response;
  1455. }
  1456. #endif /* CONFIG_FSTRIM */
  1457. #define LINUX_SYS_STATE_FILE "/sys/power/state"
  1458. #define SUSPEND_SUPPORTED 0
  1459. #define SUSPEND_NOT_SUPPORTED 1
  1460. typedef enum {
  1461. SUSPEND_MODE_DISK = 0,
  1462. SUSPEND_MODE_RAM = 1,
  1463. SUSPEND_MODE_HYBRID = 2,
  1464. } SuspendMode;
  1465. /*
  1466. * Executes a command in a child process using g_spawn_sync,
  1467. * returning an int >= 0 representing the exit status of the
  1468. * process.
  1469. *
  1470. * If the program wasn't found in path, returns -1.
  1471. *
  1472. * If a problem happened when creating the child process,
  1473. * returns -1 and errp is set.
  1474. */
  1475. static int run_process_child(const char *command[], Error **errp)
  1476. {
  1477. int exit_status, spawn_flag;
  1478. GError *g_err = NULL;
  1479. bool success;
  1480. spawn_flag = G_SPAWN_SEARCH_PATH | G_SPAWN_STDOUT_TO_DEV_NULL |
  1481. G_SPAWN_STDERR_TO_DEV_NULL;
  1482. success = g_spawn_sync(NULL, (char **)command, NULL, spawn_flag,
  1483. NULL, NULL, NULL, NULL,
  1484. &exit_status, &g_err);
  1485. if (success) {
  1486. return WEXITSTATUS(exit_status);
  1487. }
  1488. if (g_err && (g_err->code != G_SPAWN_ERROR_NOENT)) {
  1489. error_setg(errp, "failed to create child process, error '%s'",
  1490. g_err->message);
  1491. }
  1492. g_error_free(g_err);
  1493. return -1;
  1494. }
  1495. static bool systemd_supports_mode(SuspendMode mode, Error **errp)
  1496. {
  1497. const char *systemctl_args[3] = {"systemd-hibernate", "systemd-suspend",
  1498. "systemd-hybrid-sleep"};
  1499. const char *cmd[4] = {"systemctl", "status", systemctl_args[mode], NULL};
  1500. int status;
  1501. status = run_process_child(cmd, errp);
  1502. /*
  1503. * systemctl status uses LSB return codes so we can expect
  1504. * status > 0 and be ok. To assert if the guest has support
  1505. * for the selected suspend mode, status should be < 4. 4 is
  1506. * the code for unknown service status, the return value when
  1507. * the service does not exist. A common value is status = 3
  1508. * (program is not running).
  1509. */
  1510. if (status > 0 && status < 4) {
  1511. return true;
  1512. }
  1513. return false;
  1514. }
  1515. static void systemd_suspend(SuspendMode mode, Error **errp)
  1516. {
  1517. Error *local_err = NULL;
  1518. const char *systemctl_args[3] = {"hibernate", "suspend", "hybrid-sleep"};
  1519. const char *cmd[3] = {"systemctl", systemctl_args[mode], NULL};
  1520. int status;
  1521. status = run_process_child(cmd, &local_err);
  1522. if (status == 0) {
  1523. return;
  1524. }
  1525. if ((status == -1) && !local_err) {
  1526. error_setg(errp, "the helper program 'systemctl %s' was not found",
  1527. systemctl_args[mode]);
  1528. return;
  1529. }
  1530. if (local_err) {
  1531. error_propagate(errp, local_err);
  1532. } else {
  1533. error_setg(errp, "the helper program 'systemctl %s' returned an "
  1534. "unexpected exit status code (%d)",
  1535. systemctl_args[mode], status);
  1536. }
  1537. }
  1538. static bool pmutils_supports_mode(SuspendMode mode, Error **errp)
  1539. {
  1540. Error *local_err = NULL;
  1541. const char *pmutils_args[3] = {"--hibernate", "--suspend",
  1542. "--suspend-hybrid"};
  1543. const char *cmd[3] = {"pm-is-supported", pmutils_args[mode], NULL};
  1544. int status;
  1545. status = run_process_child(cmd, &local_err);
  1546. if (status == SUSPEND_SUPPORTED) {
  1547. return true;
  1548. }
  1549. if ((status == -1) && !local_err) {
  1550. return false;
  1551. }
  1552. if (local_err) {
  1553. error_propagate(errp, local_err);
  1554. } else {
  1555. error_setg(errp,
  1556. "the helper program '%s' returned an unexpected exit"
  1557. " status code (%d)", "pm-is-supported", status);
  1558. }
  1559. return false;
  1560. }
  1561. static void pmutils_suspend(SuspendMode mode, Error **errp)
  1562. {
  1563. Error *local_err = NULL;
  1564. const char *pmutils_binaries[3] = {"pm-hibernate", "pm-suspend",
  1565. "pm-suspend-hybrid"};
  1566. const char *cmd[2] = {pmutils_binaries[mode], NULL};
  1567. int status;
  1568. status = run_process_child(cmd, &local_err);
  1569. if (status == 0) {
  1570. return;
  1571. }
  1572. if ((status == -1) && !local_err) {
  1573. error_setg(errp, "the helper program '%s' was not found",
  1574. pmutils_binaries[mode]);
  1575. return;
  1576. }
  1577. if (local_err) {
  1578. error_propagate(errp, local_err);
  1579. } else {
  1580. error_setg(errp,
  1581. "the helper program '%s' returned an unexpected exit"
  1582. " status code (%d)", pmutils_binaries[mode], status);
  1583. }
  1584. }
  1585. static bool linux_sys_state_supports_mode(SuspendMode mode, Error **errp)
  1586. {
  1587. const char *sysfile_strs[3] = {"disk", "mem", NULL};
  1588. const char *sysfile_str = sysfile_strs[mode];
  1589. char buf[32]; /* hopefully big enough */
  1590. int fd;
  1591. ssize_t ret;
  1592. if (!sysfile_str) {
  1593. error_setg(errp, "unknown guest suspend mode");
  1594. return false;
  1595. }
  1596. fd = open(LINUX_SYS_STATE_FILE, O_RDONLY);
  1597. if (fd < 0) {
  1598. return false;
  1599. }
  1600. ret = read(fd, buf, sizeof(buf) - 1);
  1601. close(fd);
  1602. if (ret <= 0) {
  1603. return false;
  1604. }
  1605. buf[ret] = '\0';
  1606. if (strstr(buf, sysfile_str)) {
  1607. return true;
  1608. }
  1609. return false;
  1610. }
  1611. static void linux_sys_state_suspend(SuspendMode mode, Error **errp)
  1612. {
  1613. Error *local_err = NULL;
  1614. const char *sysfile_strs[3] = {"disk", "mem", NULL};
  1615. const char *sysfile_str = sysfile_strs[mode];
  1616. pid_t pid;
  1617. int status;
  1618. if (!sysfile_str) {
  1619. error_setg(errp, "unknown guest suspend mode");
  1620. return;
  1621. }
  1622. pid = fork();
  1623. if (!pid) {
  1624. /* child */
  1625. int fd;
  1626. setsid();
  1627. reopen_fd_to_null(0);
  1628. reopen_fd_to_null(1);
  1629. reopen_fd_to_null(2);
  1630. fd = open(LINUX_SYS_STATE_FILE, O_WRONLY);
  1631. if (fd < 0) {
  1632. _exit(EXIT_FAILURE);
  1633. }
  1634. if (write(fd, sysfile_str, strlen(sysfile_str)) < 0) {
  1635. _exit(EXIT_FAILURE);
  1636. }
  1637. _exit(EXIT_SUCCESS);
  1638. } else if (pid < 0) {
  1639. error_setg_errno(errp, errno, "failed to create child process");
  1640. return;
  1641. }
  1642. ga_wait_child(pid, &status, &local_err);
  1643. if (local_err) {
  1644. error_propagate(errp, local_err);
  1645. return;
  1646. }
  1647. if (WEXITSTATUS(status)) {
  1648. error_setg(errp, "child process has failed to suspend");
  1649. }
  1650. }
  1651. static void guest_suspend(SuspendMode mode, Error **errp)
  1652. {
  1653. Error *local_err = NULL;
  1654. bool mode_supported = false;
  1655. if (systemd_supports_mode(mode, &local_err)) {
  1656. mode_supported = true;
  1657. systemd_suspend(mode, &local_err);
  1658. if (!local_err) {
  1659. return;
  1660. }
  1661. }
  1662. error_free(local_err);
  1663. local_err = NULL;
  1664. if (pmutils_supports_mode(mode, &local_err)) {
  1665. mode_supported = true;
  1666. pmutils_suspend(mode, &local_err);
  1667. if (!local_err) {
  1668. return;
  1669. }
  1670. }
  1671. error_free(local_err);
  1672. local_err = NULL;
  1673. if (linux_sys_state_supports_mode(mode, &local_err)) {
  1674. mode_supported = true;
  1675. linux_sys_state_suspend(mode, &local_err);
  1676. }
  1677. if (!mode_supported) {
  1678. error_free(local_err);
  1679. error_setg(errp,
  1680. "the requested suspend mode is not supported by the guest");
  1681. } else {
  1682. error_propagate(errp, local_err);
  1683. }
  1684. }
  1685. void qmp_guest_suspend_disk(Error **errp)
  1686. {
  1687. guest_suspend(SUSPEND_MODE_DISK, errp);
  1688. }
  1689. void qmp_guest_suspend_ram(Error **errp)
  1690. {
  1691. guest_suspend(SUSPEND_MODE_RAM, errp);
  1692. }
  1693. void qmp_guest_suspend_hybrid(Error **errp)
  1694. {
  1695. guest_suspend(SUSPEND_MODE_HYBRID, errp);
  1696. }
  1697. /* Transfer online/offline status between @vcpu and the guest system.
  1698. *
  1699. * On input either @errp or *@errp must be NULL.
  1700. *
  1701. * In system-to-@vcpu direction, the following @vcpu fields are accessed:
  1702. * - R: vcpu->logical_id
  1703. * - W: vcpu->online
  1704. * - W: vcpu->can_offline
  1705. *
  1706. * In @vcpu-to-system direction, the following @vcpu fields are accessed:
  1707. * - R: vcpu->logical_id
  1708. * - R: vcpu->online
  1709. *
  1710. * Written members remain unmodified on error.
  1711. */
  1712. static void transfer_vcpu(GuestLogicalProcessor *vcpu, bool sys2vcpu,
  1713. char *dirpath, Error **errp)
  1714. {
  1715. int fd;
  1716. int res;
  1717. int dirfd;
  1718. static const char fn[] = "online";
  1719. dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
  1720. if (dirfd == -1) {
  1721. error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
  1722. return;
  1723. }
  1724. fd = openat(dirfd, fn, sys2vcpu ? O_RDONLY : O_RDWR);
  1725. if (fd == -1) {
  1726. if (errno != ENOENT) {
  1727. error_setg_errno(errp, errno, "open(\"%s/%s\")", dirpath, fn);
  1728. } else if (sys2vcpu) {
  1729. vcpu->online = true;
  1730. vcpu->can_offline = false;
  1731. } else if (!vcpu->online) {
  1732. error_setg(errp, "logical processor #%" PRId64 " can't be "
  1733. "offlined", vcpu->logical_id);
  1734. } /* otherwise pretend successful re-onlining */
  1735. } else {
  1736. unsigned char status;
  1737. res = pread(fd, &status, 1, 0);
  1738. if (res == -1) {
  1739. error_setg_errno(errp, errno, "pread(\"%s/%s\")", dirpath, fn);
  1740. } else if (res == 0) {
  1741. error_setg(errp, "pread(\"%s/%s\"): unexpected EOF", dirpath,
  1742. fn);
  1743. } else if (sys2vcpu) {
  1744. vcpu->online = (status != '0');
  1745. vcpu->can_offline = true;
  1746. } else if (vcpu->online != (status != '0')) {
  1747. status = '0' + vcpu->online;
  1748. if (pwrite(fd, &status, 1, 0) == -1) {
  1749. error_setg_errno(errp, errno, "pwrite(\"%s/%s\")", dirpath,
  1750. fn);
  1751. }
  1752. } /* otherwise pretend successful re-(on|off)-lining */
  1753. res = close(fd);
  1754. g_assert(res == 0);
  1755. }
  1756. res = close(dirfd);
  1757. g_assert(res == 0);
  1758. }
  1759. GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
  1760. {
  1761. GuestLogicalProcessorList *head, **tail;
  1762. const char *cpu_dir = "/sys/devices/system/cpu";
  1763. const gchar *line;
  1764. g_autoptr(GDir) cpu_gdir = NULL;
  1765. Error *local_err = NULL;
  1766. head = NULL;
  1767. tail = &head;
  1768. cpu_gdir = g_dir_open(cpu_dir, 0, NULL);
  1769. if (cpu_gdir == NULL) {
  1770. error_setg_errno(errp, errno, "failed to list entries: %s", cpu_dir);
  1771. return NULL;
  1772. }
  1773. while (local_err == NULL && (line = g_dir_read_name(cpu_gdir)) != NULL) {
  1774. GuestLogicalProcessor *vcpu;
  1775. int64_t id;
  1776. if (sscanf(line, "cpu%" PRId64, &id)) {
  1777. g_autofree char *path = g_strdup_printf("/sys/devices/system/cpu/"
  1778. "cpu%" PRId64 "/", id);
  1779. vcpu = g_malloc0(sizeof *vcpu);
  1780. vcpu->logical_id = id;
  1781. vcpu->has_can_offline = true; /* lolspeak ftw */
  1782. transfer_vcpu(vcpu, true, path, &local_err);
  1783. QAPI_LIST_APPEND(tail, vcpu);
  1784. }
  1785. }
  1786. if (local_err == NULL) {
  1787. /* there's no guest with zero VCPUs */
  1788. g_assert(head != NULL);
  1789. return head;
  1790. }
  1791. qapi_free_GuestLogicalProcessorList(head);
  1792. error_propagate(errp, local_err);
  1793. return NULL;
  1794. }
  1795. int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
  1796. {
  1797. int64_t processed;
  1798. Error *local_err = NULL;
  1799. processed = 0;
  1800. while (vcpus != NULL) {
  1801. char *path = g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64 "/",
  1802. vcpus->value->logical_id);
  1803. transfer_vcpu(vcpus->value, false, path, &local_err);
  1804. g_free(path);
  1805. if (local_err != NULL) {
  1806. break;
  1807. }
  1808. ++processed;
  1809. vcpus = vcpus->next;
  1810. }
  1811. if (local_err != NULL) {
  1812. if (processed == 0) {
  1813. error_propagate(errp, local_err);
  1814. } else {
  1815. error_free(local_err);
  1816. }
  1817. }
  1818. return processed;
  1819. }
  1820. #endif /* __linux__ */
  1821. #if defined(__linux__) || defined(__FreeBSD__)
  1822. void qmp_guest_set_user_password(const char *username,
  1823. const char *password,
  1824. bool crypted,
  1825. Error **errp)
  1826. {
  1827. Error *local_err = NULL;
  1828. char *passwd_path = NULL;
  1829. pid_t pid;
  1830. int status;
  1831. int datafd[2] = { -1, -1 };
  1832. char *rawpasswddata = NULL;
  1833. size_t rawpasswdlen;
  1834. char *chpasswddata = NULL;
  1835. size_t chpasswdlen;
  1836. rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
  1837. if (!rawpasswddata) {
  1838. return;
  1839. }
  1840. rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
  1841. rawpasswddata[rawpasswdlen] = '\0';
  1842. if (strchr(rawpasswddata, '\n')) {
  1843. error_setg(errp, "forbidden characters in raw password");
  1844. goto out;
  1845. }
  1846. if (strchr(username, '\n') ||
  1847. strchr(username, ':')) {
  1848. error_setg(errp, "forbidden characters in username");
  1849. goto out;
  1850. }
  1851. #ifdef __FreeBSD__
  1852. chpasswddata = g_strdup(rawpasswddata);
  1853. passwd_path = g_find_program_in_path("pw");
  1854. #else
  1855. chpasswddata = g_strdup_printf("%s:%s\n", username, rawpasswddata);
  1856. passwd_path = g_find_program_in_path("chpasswd");
  1857. #endif
  1858. chpasswdlen = strlen(chpasswddata);
  1859. if (!passwd_path) {
  1860. error_setg(errp, "cannot find 'passwd' program in PATH");
  1861. goto out;
  1862. }
  1863. if (!g_unix_open_pipe(datafd, FD_CLOEXEC, NULL)) {
  1864. error_setg(errp, "cannot create pipe FDs");
  1865. goto out;
  1866. }
  1867. pid = fork();
  1868. if (pid == 0) {
  1869. close(datafd[1]);
  1870. /* child */
  1871. setsid();
  1872. dup2(datafd[0], 0);
  1873. reopen_fd_to_null(1);
  1874. reopen_fd_to_null(2);
  1875. #ifdef __FreeBSD__
  1876. const char *h_arg;
  1877. h_arg = (crypted) ? "-H" : "-h";
  1878. execl(passwd_path, "pw", "usermod", "-n", username, h_arg, "0", NULL);
  1879. #else
  1880. if (crypted) {
  1881. execl(passwd_path, "chpasswd", "-e", NULL);
  1882. } else {
  1883. execl(passwd_path, "chpasswd", NULL);
  1884. }
  1885. #endif
  1886. _exit(EXIT_FAILURE);
  1887. } else if (pid < 0) {
  1888. error_setg_errno(errp, errno, "failed to create child process");
  1889. goto out;
  1890. }
  1891. close(datafd[0]);
  1892. datafd[0] = -1;
  1893. if (qemu_write_full(datafd[1], chpasswddata, chpasswdlen) != chpasswdlen) {
  1894. error_setg_errno(errp, errno, "cannot write new account password");
  1895. goto out;
  1896. }
  1897. close(datafd[1]);
  1898. datafd[1] = -1;
  1899. ga_wait_child(pid, &status, &local_err);
  1900. if (local_err) {
  1901. error_propagate(errp, local_err);
  1902. goto out;
  1903. }
  1904. if (!WIFEXITED(status)) {
  1905. error_setg(errp, "child process has terminated abnormally");
  1906. goto out;
  1907. }
  1908. if (WEXITSTATUS(status)) {
  1909. error_setg(errp, "child process has failed to set user password");
  1910. goto out;
  1911. }
  1912. out:
  1913. g_free(chpasswddata);
  1914. g_free(rawpasswddata);
  1915. g_free(passwd_path);
  1916. if (datafd[0] != -1) {
  1917. close(datafd[0]);
  1918. }
  1919. if (datafd[1] != -1) {
  1920. close(datafd[1]);
  1921. }
  1922. }
  1923. #else /* __linux__ || __FreeBSD__ */
  1924. void qmp_guest_set_user_password(const char *username,
  1925. const char *password,
  1926. bool crypted,
  1927. Error **errp)
  1928. {
  1929. error_setg(errp, QERR_UNSUPPORTED);
  1930. }
  1931. #endif /* __linux__ || __FreeBSD__ */
  1932. #ifdef __linux__
  1933. static void ga_read_sysfs_file(int dirfd, const char *pathname, char *buf,
  1934. int size, Error **errp)
  1935. {
  1936. int fd;
  1937. int res;
  1938. errno = 0;
  1939. fd = openat(dirfd, pathname, O_RDONLY);
  1940. if (fd == -1) {
  1941. error_setg_errno(errp, errno, "open sysfs file \"%s\"", pathname);
  1942. return;
  1943. }
  1944. res = pread(fd, buf, size, 0);
  1945. if (res == -1) {
  1946. error_setg_errno(errp, errno, "pread sysfs file \"%s\"", pathname);
  1947. } else if (res == 0) {
  1948. error_setg(errp, "pread sysfs file \"%s\": unexpected EOF", pathname);
  1949. }
  1950. close(fd);
  1951. }
  1952. static void ga_write_sysfs_file(int dirfd, const char *pathname,
  1953. const char *buf, int size, Error **errp)
  1954. {
  1955. int fd;
  1956. errno = 0;
  1957. fd = openat(dirfd, pathname, O_WRONLY);
  1958. if (fd == -1) {
  1959. error_setg_errno(errp, errno, "open sysfs file \"%s\"", pathname);
  1960. return;
  1961. }
  1962. if (pwrite(fd, buf, size, 0) == -1) {
  1963. error_setg_errno(errp, errno, "pwrite sysfs file \"%s\"", pathname);
  1964. }
  1965. close(fd);
  1966. }
  1967. /* Transfer online/offline status between @mem_blk and the guest system.
  1968. *
  1969. * On input either @errp or *@errp must be NULL.
  1970. *
  1971. * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
  1972. * - R: mem_blk->phys_index
  1973. * - W: mem_blk->online
  1974. * - W: mem_blk->can_offline
  1975. *
  1976. * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
  1977. * - R: mem_blk->phys_index
  1978. * - R: mem_blk->online
  1979. *- R: mem_blk->can_offline
  1980. * Written members remain unmodified on error.
  1981. */
  1982. static void transfer_memory_block(GuestMemoryBlock *mem_blk, bool sys2memblk,
  1983. GuestMemoryBlockResponse *result,
  1984. Error **errp)
  1985. {
  1986. char *dirpath;
  1987. int dirfd;
  1988. char *status;
  1989. Error *local_err = NULL;
  1990. if (!sys2memblk) {
  1991. DIR *dp;
  1992. if (!result) {
  1993. error_setg(errp, "Internal error, 'result' should not be NULL");
  1994. return;
  1995. }
  1996. errno = 0;
  1997. dp = opendir("/sys/devices/system/memory/");
  1998. /* if there is no 'memory' directory in sysfs,
  1999. * we think this VM does not support online/offline memory block,
  2000. * any other solution?
  2001. */
  2002. if (!dp) {
  2003. if (errno == ENOENT) {
  2004. result->response =
  2005. GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED;
  2006. }
  2007. goto out1;
  2008. }
  2009. closedir(dp);
  2010. }
  2011. dirpath = g_strdup_printf("/sys/devices/system/memory/memory%" PRId64 "/",
  2012. mem_blk->phys_index);
  2013. dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
  2014. if (dirfd == -1) {
  2015. if (sys2memblk) {
  2016. error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
  2017. } else {
  2018. if (errno == ENOENT) {
  2019. result->response = GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND;
  2020. } else {
  2021. result->response =
  2022. GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
  2023. }
  2024. }
  2025. g_free(dirpath);
  2026. goto out1;
  2027. }
  2028. g_free(dirpath);
  2029. status = g_malloc0(10);
  2030. ga_read_sysfs_file(dirfd, "state", status, 10, &local_err);
  2031. if (local_err) {
  2032. /* treat with sysfs file that not exist in old kernel */
  2033. if (errno == ENOENT) {
  2034. error_free(local_err);
  2035. if (sys2memblk) {
  2036. mem_blk->online = true;
  2037. mem_blk->can_offline = false;
  2038. } else if (!mem_blk->online) {
  2039. result->response =
  2040. GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED;
  2041. }
  2042. } else {
  2043. if (sys2memblk) {
  2044. error_propagate(errp, local_err);
  2045. } else {
  2046. error_free(local_err);
  2047. result->response =
  2048. GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
  2049. }
  2050. }
  2051. goto out2;
  2052. }
  2053. if (sys2memblk) {
  2054. char removable = '0';
  2055. mem_blk->online = (strncmp(status, "online", 6) == 0);
  2056. ga_read_sysfs_file(dirfd, "removable", &removable, 1, &local_err);
  2057. if (local_err) {
  2058. /* if no 'removable' file, it doesn't support offline mem blk */
  2059. if (errno == ENOENT) {
  2060. error_free(local_err);
  2061. mem_blk->can_offline = false;
  2062. } else {
  2063. error_propagate(errp, local_err);
  2064. }
  2065. } else {
  2066. mem_blk->can_offline = (removable != '0');
  2067. }
  2068. } else {
  2069. if (mem_blk->online != (strncmp(status, "online", 6) == 0)) {
  2070. const char *new_state = mem_blk->online ? "online" : "offline";
  2071. ga_write_sysfs_file(dirfd, "state", new_state, strlen(new_state),
  2072. &local_err);
  2073. if (local_err) {
  2074. error_free(local_err);
  2075. result->response =
  2076. GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
  2077. goto out2;
  2078. }
  2079. result->response = GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS;
  2080. result->has_error_code = false;
  2081. } /* otherwise pretend successful re-(on|off)-lining */
  2082. }
  2083. g_free(status);
  2084. close(dirfd);
  2085. return;
  2086. out2:
  2087. g_free(status);
  2088. close(dirfd);
  2089. out1:
  2090. if (!sys2memblk) {
  2091. result->has_error_code = true;
  2092. result->error_code = errno;
  2093. }
  2094. }
  2095. GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
  2096. {
  2097. GuestMemoryBlockList *head, **tail;
  2098. Error *local_err = NULL;
  2099. struct dirent *de;
  2100. DIR *dp;
  2101. head = NULL;
  2102. tail = &head;
  2103. dp = opendir("/sys/devices/system/memory/");
  2104. if (!dp) {
  2105. /* it's ok if this happens to be a system that doesn't expose
  2106. * memory blocks via sysfs, but otherwise we should report
  2107. * an error
  2108. */
  2109. if (errno != ENOENT) {
  2110. error_setg_errno(errp, errno, "Can't open directory"
  2111. "\"/sys/devices/system/memory/\"");
  2112. }
  2113. return NULL;
  2114. }
  2115. /* Note: the phys_index of memory block may be discontinuous,
  2116. * this is because a memblk is the unit of the Sparse Memory design, which
  2117. * allows discontinuous memory ranges (ex. NUMA), so here we should
  2118. * traverse the memory block directory.
  2119. */
  2120. while ((de = readdir(dp)) != NULL) {
  2121. GuestMemoryBlock *mem_blk;
  2122. if ((strncmp(de->d_name, "memory", 6) != 0) ||
  2123. !(de->d_type & DT_DIR)) {
  2124. continue;
  2125. }
  2126. mem_blk = g_malloc0(sizeof *mem_blk);
  2127. /* The d_name is "memoryXXX", phys_index is block id, same as XXX */
  2128. mem_blk->phys_index = strtoul(&de->d_name[6], NULL, 10);
  2129. mem_blk->has_can_offline = true; /* lolspeak ftw */
  2130. transfer_memory_block(mem_blk, true, NULL, &local_err);
  2131. if (local_err) {
  2132. break;
  2133. }
  2134. QAPI_LIST_APPEND(tail, mem_blk);
  2135. }
  2136. closedir(dp);
  2137. if (local_err == NULL) {
  2138. /* there's no guest with zero memory blocks */
  2139. if (head == NULL) {
  2140. error_setg(errp, "guest reported zero memory blocks!");
  2141. }
  2142. return head;
  2143. }
  2144. qapi_free_GuestMemoryBlockList(head);
  2145. error_propagate(errp, local_err);
  2146. return NULL;
  2147. }
  2148. GuestMemoryBlockResponseList *
  2149. qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
  2150. {
  2151. GuestMemoryBlockResponseList *head, **tail;
  2152. Error *local_err = NULL;
  2153. head = NULL;
  2154. tail = &head;
  2155. while (mem_blks != NULL) {
  2156. GuestMemoryBlockResponse *result;
  2157. GuestMemoryBlock *current_mem_blk = mem_blks->value;
  2158. result = g_malloc0(sizeof(*result));
  2159. result->phys_index = current_mem_blk->phys_index;
  2160. transfer_memory_block(current_mem_blk, false, result, &local_err);
  2161. if (local_err) { /* should never happen */
  2162. goto err;
  2163. }
  2164. QAPI_LIST_APPEND(tail, result);
  2165. mem_blks = mem_blks->next;
  2166. }
  2167. return head;
  2168. err:
  2169. qapi_free_GuestMemoryBlockResponseList(head);
  2170. error_propagate(errp, local_err);
  2171. return NULL;
  2172. }
  2173. GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
  2174. {
  2175. Error *local_err = NULL;
  2176. char *dirpath;
  2177. int dirfd;
  2178. char *buf;
  2179. GuestMemoryBlockInfo *info;
  2180. dirpath = g_strdup_printf("/sys/devices/system/memory/");
  2181. dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
  2182. if (dirfd == -1) {
  2183. error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
  2184. g_free(dirpath);
  2185. return NULL;
  2186. }
  2187. g_free(dirpath);
  2188. buf = g_malloc0(20);
  2189. ga_read_sysfs_file(dirfd, "block_size_bytes", buf, 20, &local_err);
  2190. close(dirfd);
  2191. if (local_err) {
  2192. g_free(buf);
  2193. error_propagate(errp, local_err);
  2194. return NULL;
  2195. }
  2196. info = g_new0(GuestMemoryBlockInfo, 1);
  2197. info->size = strtol(buf, NULL, 16); /* the unit is bytes */
  2198. g_free(buf);
  2199. return info;
  2200. }
  2201. #define MAX_NAME_LEN 128
  2202. static GuestDiskStatsInfoList *guest_get_diskstats(Error **errp)
  2203. {
  2204. #ifdef CONFIG_LINUX
  2205. GuestDiskStatsInfoList *head = NULL, **tail = &head;
  2206. const char *diskstats = "/proc/diskstats";
  2207. FILE *fp;
  2208. size_t n;
  2209. char *line = NULL;
  2210. fp = fopen(diskstats, "r");
  2211. if (fp == NULL) {
  2212. error_setg_errno(errp, errno, "open(\"%s\")", diskstats);
  2213. return NULL;
  2214. }
  2215. while (getline(&line, &n, fp) != -1) {
  2216. g_autofree GuestDiskStatsInfo *diskstatinfo = NULL;
  2217. g_autofree GuestDiskStats *diskstat = NULL;
  2218. char dev_name[MAX_NAME_LEN];
  2219. unsigned int ios_pgr, tot_ticks, rq_ticks, wr_ticks, dc_ticks, fl_ticks;
  2220. unsigned long rd_ios, rd_merges_or_rd_sec, rd_ticks_or_wr_sec, wr_ios;
  2221. unsigned long wr_merges, rd_sec_or_wr_ios, wr_sec;
  2222. unsigned long dc_ios, dc_merges, dc_sec, fl_ios;
  2223. unsigned int major, minor;
  2224. int i;
  2225. i = sscanf(line, "%u %u %s %lu %lu %lu"
  2226. "%lu %lu %lu %lu %u %u %u %u"
  2227. "%lu %lu %lu %u %lu %u",
  2228. &major, &minor, dev_name,
  2229. &rd_ios, &rd_merges_or_rd_sec, &rd_sec_or_wr_ios,
  2230. &rd_ticks_or_wr_sec, &wr_ios, &wr_merges, &wr_sec,
  2231. &wr_ticks, &ios_pgr, &tot_ticks, &rq_ticks,
  2232. &dc_ios, &dc_merges, &dc_sec, &dc_ticks,
  2233. &fl_ios, &fl_ticks);
  2234. if (i < 7) {
  2235. continue;
  2236. }
  2237. diskstatinfo = g_new0(GuestDiskStatsInfo, 1);
  2238. diskstatinfo->name = g_strdup(dev_name);
  2239. diskstatinfo->major = major;
  2240. diskstatinfo->minor = minor;
  2241. diskstat = g_new0(GuestDiskStats, 1);
  2242. if (i == 7) {
  2243. diskstat->has_read_ios = true;
  2244. diskstat->read_ios = rd_ios;
  2245. diskstat->has_read_sectors = true;
  2246. diskstat->read_sectors = rd_merges_or_rd_sec;
  2247. diskstat->has_write_ios = true;
  2248. diskstat->write_ios = rd_sec_or_wr_ios;
  2249. diskstat->has_write_sectors = true;
  2250. diskstat->write_sectors = rd_ticks_or_wr_sec;
  2251. }
  2252. if (i >= 14) {
  2253. diskstat->has_read_ios = true;
  2254. diskstat->read_ios = rd_ios;
  2255. diskstat->has_read_sectors = true;
  2256. diskstat->read_sectors = rd_sec_or_wr_ios;
  2257. diskstat->has_read_merges = true;
  2258. diskstat->read_merges = rd_merges_or_rd_sec;
  2259. diskstat->has_read_ticks = true;
  2260. diskstat->read_ticks = rd_ticks_or_wr_sec;
  2261. diskstat->has_write_ios = true;
  2262. diskstat->write_ios = wr_ios;
  2263. diskstat->has_write_sectors = true;
  2264. diskstat->write_sectors = wr_sec;
  2265. diskstat->has_write_merges = true;
  2266. diskstat->write_merges = wr_merges;
  2267. diskstat->has_write_ticks = true;
  2268. diskstat->write_ticks = wr_ticks;
  2269. diskstat->has_ios_pgr = true;
  2270. diskstat->ios_pgr = ios_pgr;
  2271. diskstat->has_total_ticks = true;
  2272. diskstat->total_ticks = tot_ticks;
  2273. diskstat->has_weight_ticks = true;
  2274. diskstat->weight_ticks = rq_ticks;
  2275. }
  2276. if (i >= 18) {
  2277. diskstat->has_discard_ios = true;
  2278. diskstat->discard_ios = dc_ios;
  2279. diskstat->has_discard_merges = true;
  2280. diskstat->discard_merges = dc_merges;
  2281. diskstat->has_discard_sectors = true;
  2282. diskstat->discard_sectors = dc_sec;
  2283. diskstat->has_discard_ticks = true;
  2284. diskstat->discard_ticks = dc_ticks;
  2285. }
  2286. if (i >= 20) {
  2287. diskstat->has_flush_ios = true;
  2288. diskstat->flush_ios = fl_ios;
  2289. diskstat->has_flush_ticks = true;
  2290. diskstat->flush_ticks = fl_ticks;
  2291. }
  2292. diskstatinfo->stats = g_steal_pointer(&diskstat);
  2293. QAPI_LIST_APPEND(tail, diskstatinfo);
  2294. diskstatinfo = NULL;
  2295. }
  2296. free(line);
  2297. fclose(fp);
  2298. return head;
  2299. #else
  2300. g_debug("disk stats reporting available only for Linux");
  2301. return NULL;
  2302. #endif
  2303. }
  2304. GuestDiskStatsInfoList *qmp_guest_get_diskstats(Error **errp)
  2305. {
  2306. return guest_get_diskstats(errp);
  2307. }
  2308. GuestCpuStatsList *qmp_guest_get_cpustats(Error **errp)
  2309. {
  2310. GuestCpuStatsList *head = NULL, **tail = &head;
  2311. const char *cpustats = "/proc/stat";
  2312. int clk_tck = sysconf(_SC_CLK_TCK);
  2313. FILE *fp;
  2314. size_t n;
  2315. char *line = NULL;
  2316. fp = fopen(cpustats, "r");
  2317. if (fp == NULL) {
  2318. error_setg_errno(errp, errno, "open(\"%s\")", cpustats);
  2319. return NULL;
  2320. }
  2321. while (getline(&line, &n, fp) != -1) {
  2322. GuestCpuStats *cpustat = NULL;
  2323. GuestLinuxCpuStats *linuxcpustat;
  2324. int i;
  2325. unsigned long user, system, idle, iowait, irq, softirq, steal, guest;
  2326. unsigned long nice, guest_nice;
  2327. char name[64];
  2328. i = sscanf(line, "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
  2329. name, &user, &nice, &system, &idle, &iowait, &irq, &softirq,
  2330. &steal, &guest, &guest_nice);
  2331. /* drop "cpu 1 2 3 ...", get "cpuX 1 2 3 ..." only */
  2332. if ((i == EOF) || strncmp(name, "cpu", 3) || (name[3] == '\0')) {
  2333. continue;
  2334. }
  2335. if (i < 5) {
  2336. slog("Parsing cpu stat from %s failed, see \"man proc\"", cpustats);
  2337. break;
  2338. }
  2339. cpustat = g_new0(GuestCpuStats, 1);
  2340. cpustat->type = GUEST_CPU_STATS_TYPE_LINUX;
  2341. linuxcpustat = &cpustat->u.q_linux;
  2342. linuxcpustat->cpu = atoi(&name[3]);
  2343. linuxcpustat->user = user * 1000 / clk_tck;
  2344. linuxcpustat->nice = nice * 1000 / clk_tck;
  2345. linuxcpustat->system = system * 1000 / clk_tck;
  2346. linuxcpustat->idle = idle * 1000 / clk_tck;
  2347. if (i > 5) {
  2348. linuxcpustat->has_iowait = true;
  2349. linuxcpustat->iowait = iowait * 1000 / clk_tck;
  2350. }
  2351. if (i > 6) {
  2352. linuxcpustat->has_irq = true;
  2353. linuxcpustat->irq = irq * 1000 / clk_tck;
  2354. linuxcpustat->has_softirq = true;
  2355. linuxcpustat->softirq = softirq * 1000 / clk_tck;
  2356. }
  2357. if (i > 8) {
  2358. linuxcpustat->has_steal = true;
  2359. linuxcpustat->steal = steal * 1000 / clk_tck;
  2360. }
  2361. if (i > 9) {
  2362. linuxcpustat->has_guest = true;
  2363. linuxcpustat->guest = guest * 1000 / clk_tck;
  2364. }
  2365. if (i > 10) {
  2366. linuxcpustat->has_guest = true;
  2367. linuxcpustat->guest = guest * 1000 / clk_tck;
  2368. linuxcpustat->has_guestnice = true;
  2369. linuxcpustat->guestnice = guest_nice * 1000 / clk_tck;
  2370. }
  2371. QAPI_LIST_APPEND(tail, cpustat);
  2372. }
  2373. free(line);
  2374. fclose(fp);
  2375. return head;
  2376. }
  2377. #else /* defined(__linux__) */
  2378. void qmp_guest_suspend_disk(Error **errp)
  2379. {
  2380. error_setg(errp, QERR_UNSUPPORTED);
  2381. }
  2382. void qmp_guest_suspend_ram(Error **errp)
  2383. {
  2384. error_setg(errp, QERR_UNSUPPORTED);
  2385. }
  2386. void qmp_guest_suspend_hybrid(Error **errp)
  2387. {
  2388. error_setg(errp, QERR_UNSUPPORTED);
  2389. }
  2390. GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
  2391. {
  2392. error_setg(errp, QERR_UNSUPPORTED);
  2393. return NULL;
  2394. }
  2395. int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
  2396. {
  2397. error_setg(errp, QERR_UNSUPPORTED);
  2398. return -1;
  2399. }
  2400. GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
  2401. {
  2402. error_setg(errp, QERR_UNSUPPORTED);
  2403. return NULL;
  2404. }
  2405. GuestMemoryBlockResponseList *
  2406. qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
  2407. {
  2408. error_setg(errp, QERR_UNSUPPORTED);
  2409. return NULL;
  2410. }
  2411. GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
  2412. {
  2413. error_setg(errp, QERR_UNSUPPORTED);
  2414. return NULL;
  2415. }
  2416. #endif
  2417. #ifdef HAVE_GETIFADDRS
  2418. static GuestNetworkInterface *
  2419. guest_find_interface(GuestNetworkInterfaceList *head,
  2420. const char *name)
  2421. {
  2422. for (; head; head = head->next) {
  2423. if (strcmp(head->value->name, name) == 0) {
  2424. return head->value;
  2425. }
  2426. }
  2427. return NULL;
  2428. }
  2429. static int guest_get_network_stats(const char *name,
  2430. GuestNetworkInterfaceStat *stats)
  2431. {
  2432. #ifdef CONFIG_LINUX
  2433. int name_len;
  2434. char const *devinfo = "/proc/net/dev";
  2435. FILE *fp;
  2436. char *line = NULL, *colon;
  2437. size_t n = 0;
  2438. fp = fopen(devinfo, "r");
  2439. if (!fp) {
  2440. g_debug("failed to open network stats %s: %s", devinfo,
  2441. g_strerror(errno));
  2442. return -1;
  2443. }
  2444. name_len = strlen(name);
  2445. while (getline(&line, &n, fp) != -1) {
  2446. long long dummy;
  2447. long long rx_bytes;
  2448. long long rx_packets;
  2449. long long rx_errs;
  2450. long long rx_dropped;
  2451. long long tx_bytes;
  2452. long long tx_packets;
  2453. long long tx_errs;
  2454. long long tx_dropped;
  2455. char *trim_line;
  2456. trim_line = g_strchug(line);
  2457. if (trim_line[0] == '\0') {
  2458. continue;
  2459. }
  2460. colon = strchr(trim_line, ':');
  2461. if (!colon) {
  2462. continue;
  2463. }
  2464. if (colon - name_len == trim_line &&
  2465. strncmp(trim_line, name, name_len) == 0) {
  2466. if (sscanf(colon + 1,
  2467. "%lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld",
  2468. &rx_bytes, &rx_packets, &rx_errs, &rx_dropped,
  2469. &dummy, &dummy, &dummy, &dummy,
  2470. &tx_bytes, &tx_packets, &tx_errs, &tx_dropped,
  2471. &dummy, &dummy, &dummy, &dummy) != 16) {
  2472. continue;
  2473. }
  2474. stats->rx_bytes = rx_bytes;
  2475. stats->rx_packets = rx_packets;
  2476. stats->rx_errs = rx_errs;
  2477. stats->rx_dropped = rx_dropped;
  2478. stats->tx_bytes = tx_bytes;
  2479. stats->tx_packets = tx_packets;
  2480. stats->tx_errs = tx_errs;
  2481. stats->tx_dropped = tx_dropped;
  2482. fclose(fp);
  2483. g_free(line);
  2484. return 0;
  2485. }
  2486. }
  2487. fclose(fp);
  2488. g_free(line);
  2489. g_debug("/proc/net/dev: Interface '%s' not found", name);
  2490. #else /* !CONFIG_LINUX */
  2491. g_debug("Network stats reporting available only for Linux");
  2492. #endif /* !CONFIG_LINUX */
  2493. return -1;
  2494. }
  2495. #ifndef CONFIG_BSD
  2496. /*
  2497. * Fill "buf" with MAC address by ifaddrs. Pointer buf must point to a
  2498. * buffer with ETHER_ADDR_LEN length at least.
  2499. *
  2500. * Returns false in case of an error, otherwise true. "obtained" argument
  2501. * is true if a MAC address was obtained successful, otherwise false.
  2502. */
  2503. bool guest_get_hw_addr(struct ifaddrs *ifa, unsigned char *buf,
  2504. bool *obtained, Error **errp)
  2505. {
  2506. struct ifreq ifr;
  2507. int sock;
  2508. *obtained = false;
  2509. /* we haven't obtained HW address yet */
  2510. sock = socket(PF_INET, SOCK_STREAM, 0);
  2511. if (sock == -1) {
  2512. error_setg_errno(errp, errno, "failed to create socket");
  2513. return false;
  2514. }
  2515. memset(&ifr, 0, sizeof(ifr));
  2516. pstrcpy(ifr.ifr_name, IF_NAMESIZE, ifa->ifa_name);
  2517. if (ioctl(sock, SIOCGIFHWADDR, &ifr) == -1) {
  2518. /*
  2519. * We can't get the hw addr of this interface, but that's not a
  2520. * fatal error.
  2521. */
  2522. if (errno == EADDRNOTAVAIL) {
  2523. /* The interface doesn't have a hw addr (e.g. loopback). */
  2524. g_debug("failed to get MAC address of %s: %s",
  2525. ifa->ifa_name, strerror(errno));
  2526. } else{
  2527. g_warning("failed to get MAC address of %s: %s",
  2528. ifa->ifa_name, strerror(errno));
  2529. }
  2530. } else {
  2531. #ifdef CONFIG_SOLARIS
  2532. memcpy(buf, &ifr.ifr_addr.sa_data, ETHER_ADDR_LEN);
  2533. #else
  2534. memcpy(buf, &ifr.ifr_hwaddr.sa_data, ETHER_ADDR_LEN);
  2535. #endif
  2536. *obtained = true;
  2537. }
  2538. close(sock);
  2539. return true;
  2540. }
  2541. #endif /* CONFIG_BSD */
  2542. /*
  2543. * Build information about guest interfaces
  2544. */
  2545. GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
  2546. {
  2547. GuestNetworkInterfaceList *head = NULL, **tail = &head;
  2548. struct ifaddrs *ifap, *ifa;
  2549. if (getifaddrs(&ifap) < 0) {
  2550. error_setg_errno(errp, errno, "getifaddrs failed");
  2551. goto error;
  2552. }
  2553. for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
  2554. GuestNetworkInterface *info;
  2555. GuestIpAddressList **address_tail;
  2556. GuestIpAddress *address_item = NULL;
  2557. GuestNetworkInterfaceStat *interface_stat = NULL;
  2558. char addr4[INET_ADDRSTRLEN];
  2559. char addr6[INET6_ADDRSTRLEN];
  2560. unsigned char mac_addr[ETHER_ADDR_LEN];
  2561. bool obtained;
  2562. void *p;
  2563. g_debug("Processing %s interface", ifa->ifa_name);
  2564. info = guest_find_interface(head, ifa->ifa_name);
  2565. if (!info) {
  2566. info = g_malloc0(sizeof(*info));
  2567. info->name = g_strdup(ifa->ifa_name);
  2568. QAPI_LIST_APPEND(tail, info);
  2569. }
  2570. if (!info->hardware_address) {
  2571. if (!guest_get_hw_addr(ifa, mac_addr, &obtained, errp)) {
  2572. goto error;
  2573. }
  2574. if (obtained) {
  2575. info->hardware_address =
  2576. g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
  2577. (int) mac_addr[0], (int) mac_addr[1],
  2578. (int) mac_addr[2], (int) mac_addr[3],
  2579. (int) mac_addr[4], (int) mac_addr[5]);
  2580. }
  2581. }
  2582. if (ifa->ifa_addr &&
  2583. ifa->ifa_addr->sa_family == AF_INET) {
  2584. /* interface with IPv4 address */
  2585. p = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
  2586. if (!inet_ntop(AF_INET, p, addr4, sizeof(addr4))) {
  2587. error_setg_errno(errp, errno, "inet_ntop failed");
  2588. goto error;
  2589. }
  2590. address_item = g_malloc0(sizeof(*address_item));
  2591. address_item->ip_address = g_strdup(addr4);
  2592. address_item->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV4;
  2593. if (ifa->ifa_netmask) {
  2594. /* Count the number of set bits in netmask.
  2595. * This is safe as '1' and '0' cannot be shuffled in netmask. */
  2596. p = &((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr;
  2597. address_item->prefix = ctpop32(((uint32_t *) p)[0]);
  2598. }
  2599. } else if (ifa->ifa_addr &&
  2600. ifa->ifa_addr->sa_family == AF_INET6) {
  2601. /* interface with IPv6 address */
  2602. p = &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
  2603. if (!inet_ntop(AF_INET6, p, addr6, sizeof(addr6))) {
  2604. error_setg_errno(errp, errno, "inet_ntop failed");
  2605. goto error;
  2606. }
  2607. address_item = g_malloc0(sizeof(*address_item));
  2608. address_item->ip_address = g_strdup(addr6);
  2609. address_item->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV6;
  2610. if (ifa->ifa_netmask) {
  2611. /* Count the number of set bits in netmask.
  2612. * This is safe as '1' and '0' cannot be shuffled in netmask. */
  2613. p = &((struct sockaddr_in6 *)ifa->ifa_netmask)->sin6_addr;
  2614. address_item->prefix =
  2615. ctpop32(((uint32_t *) p)[0]) +
  2616. ctpop32(((uint32_t *) p)[1]) +
  2617. ctpop32(((uint32_t *) p)[2]) +
  2618. ctpop32(((uint32_t *) p)[3]);
  2619. }
  2620. }
  2621. if (!address_item) {
  2622. continue;
  2623. }
  2624. address_tail = &info->ip_addresses;
  2625. while (*address_tail) {
  2626. address_tail = &(*address_tail)->next;
  2627. }
  2628. QAPI_LIST_APPEND(address_tail, address_item);
  2629. info->has_ip_addresses = true;
  2630. if (!info->statistics) {
  2631. interface_stat = g_malloc0(sizeof(*interface_stat));
  2632. if (guest_get_network_stats(info->name, interface_stat) == -1) {
  2633. g_free(interface_stat);
  2634. } else {
  2635. info->statistics = interface_stat;
  2636. }
  2637. }
  2638. }
  2639. freeifaddrs(ifap);
  2640. return head;
  2641. error:
  2642. freeifaddrs(ifap);
  2643. qapi_free_GuestNetworkInterfaceList(head);
  2644. return NULL;
  2645. }
  2646. #else
  2647. GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
  2648. {
  2649. error_setg(errp, QERR_UNSUPPORTED);
  2650. return NULL;
  2651. }
  2652. #endif /* HAVE_GETIFADDRS */
  2653. #if !defined(CONFIG_FSFREEZE)
  2654. GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
  2655. {
  2656. error_setg(errp, QERR_UNSUPPORTED);
  2657. return NULL;
  2658. }
  2659. GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
  2660. {
  2661. error_setg(errp, QERR_UNSUPPORTED);
  2662. return 0;
  2663. }
  2664. int64_t qmp_guest_fsfreeze_freeze(Error **errp)
  2665. {
  2666. error_setg(errp, QERR_UNSUPPORTED);
  2667. return 0;
  2668. }
  2669. int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
  2670. strList *mountpoints,
  2671. Error **errp)
  2672. {
  2673. error_setg(errp, QERR_UNSUPPORTED);
  2674. return 0;
  2675. }
  2676. int64_t qmp_guest_fsfreeze_thaw(Error **errp)
  2677. {
  2678. error_setg(errp, QERR_UNSUPPORTED);
  2679. return 0;
  2680. }
  2681. GuestDiskInfoList *qmp_guest_get_disks(Error **errp)
  2682. {
  2683. error_setg(errp, QERR_UNSUPPORTED);
  2684. return NULL;
  2685. }
  2686. GuestDiskStatsInfoList *qmp_guest_get_diskstats(Error **errp)
  2687. {
  2688. error_setg(errp, QERR_UNSUPPORTED);
  2689. return NULL;
  2690. }
  2691. GuestCpuStatsList *qmp_guest_get_cpustats(Error **errp)
  2692. {
  2693. error_setg(errp, QERR_UNSUPPORTED);
  2694. return NULL;
  2695. }
  2696. #endif /* CONFIG_FSFREEZE */
  2697. #if !defined(CONFIG_FSTRIM)
  2698. GuestFilesystemTrimResponse *
  2699. qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
  2700. {
  2701. error_setg(errp, QERR_UNSUPPORTED);
  2702. return NULL;
  2703. }
  2704. #endif
  2705. /* add unsupported commands to the list of blocked RPCs */
  2706. GList *ga_command_init_blockedrpcs(GList *blockedrpcs)
  2707. {
  2708. #if !defined(__linux__)
  2709. {
  2710. const char *list[] = {
  2711. "guest-suspend-disk", "guest-suspend-ram",
  2712. "guest-suspend-hybrid", "guest-get-vcpus", "guest-set-vcpus",
  2713. "guest-get-memory-blocks", "guest-set-memory-blocks",
  2714. "guest-get-memory-block-size", "guest-get-memory-block-info",
  2715. NULL};
  2716. char **p = (char **)list;
  2717. while (*p) {
  2718. blockedrpcs = g_list_append(blockedrpcs, g_strdup(*p++));
  2719. }
  2720. }
  2721. #endif
  2722. #if !defined(HAVE_GETIFADDRS)
  2723. blockedrpcs = g_list_append(blockedrpcs,
  2724. g_strdup("guest-network-get-interfaces"));
  2725. #endif
  2726. #if !defined(CONFIG_FSFREEZE)
  2727. {
  2728. const char *list[] = {
  2729. "guest-get-fsinfo", "guest-fsfreeze-status",
  2730. "guest-fsfreeze-freeze", "guest-fsfreeze-freeze-list",
  2731. "guest-fsfreeze-thaw", "guest-get-fsinfo",
  2732. "guest-get-disks", NULL};
  2733. char **p = (char **)list;
  2734. while (*p) {
  2735. blockedrpcs = g_list_append(blockedrpcs, g_strdup(*p++));
  2736. }
  2737. }
  2738. #endif
  2739. #if !defined(CONFIG_FSTRIM)
  2740. blockedrpcs = g_list_append(blockedrpcs, g_strdup("guest-fstrim"));
  2741. #endif
  2742. blockedrpcs = g_list_append(blockedrpcs, g_strdup("guest-get-devices"));
  2743. return blockedrpcs;
  2744. }
  2745. /* register init/cleanup routines for stateful command groups */
  2746. void ga_command_state_init(GAState *s, GACommandState *cs)
  2747. {
  2748. #if defined(CONFIG_FSFREEZE)
  2749. ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
  2750. #endif
  2751. }
  2752. #ifdef HAVE_UTMPX
  2753. #define QGA_MICRO_SECOND_TO_SECOND 1000000
  2754. static double ga_get_login_time(struct utmpx *user_info)
  2755. {
  2756. double seconds = (double)user_info->ut_tv.tv_sec;
  2757. double useconds = (double)user_info->ut_tv.tv_usec;
  2758. useconds /= QGA_MICRO_SECOND_TO_SECOND;
  2759. return seconds + useconds;
  2760. }
  2761. GuestUserList *qmp_guest_get_users(Error **errp)
  2762. {
  2763. GHashTable *cache = NULL;
  2764. GuestUserList *head = NULL, **tail = &head;
  2765. struct utmpx *user_info = NULL;
  2766. gpointer value = NULL;
  2767. GuestUser *user = NULL;
  2768. double login_time = 0;
  2769. cache = g_hash_table_new(g_str_hash, g_str_equal);
  2770. setutxent();
  2771. for (;;) {
  2772. user_info = getutxent();
  2773. if (user_info == NULL) {
  2774. break;
  2775. } else if (user_info->ut_type != USER_PROCESS) {
  2776. continue;
  2777. } else if (g_hash_table_contains(cache, user_info->ut_user)) {
  2778. value = g_hash_table_lookup(cache, user_info->ut_user);
  2779. user = (GuestUser *)value;
  2780. login_time = ga_get_login_time(user_info);
  2781. /* We're ensuring the earliest login time to be sent */
  2782. if (login_time < user->login_time) {
  2783. user->login_time = login_time;
  2784. }
  2785. continue;
  2786. }
  2787. user = g_new0(GuestUser, 1);
  2788. user->user = g_strdup(user_info->ut_user);
  2789. user->login_time = ga_get_login_time(user_info);
  2790. g_hash_table_insert(cache, user->user, user);
  2791. QAPI_LIST_APPEND(tail, user);
  2792. }
  2793. endutxent();
  2794. g_hash_table_destroy(cache);
  2795. return head;
  2796. }
  2797. #else
  2798. GuestUserList *qmp_guest_get_users(Error **errp)
  2799. {
  2800. error_setg(errp, QERR_UNSUPPORTED);
  2801. return NULL;
  2802. }
  2803. #endif
  2804. /* Replace escaped special characters with their real values. The replacement
  2805. * is done in place -- returned value is in the original string.
  2806. */
  2807. static void ga_osrelease_replace_special(gchar *value)
  2808. {
  2809. gchar *p, *p2, quote;
  2810. /* Trim the string at first space or semicolon if it is not enclosed in
  2811. * single or double quotes. */
  2812. if ((value[0] != '"') || (value[0] == '\'')) {
  2813. p = strchr(value, ' ');
  2814. if (p != NULL) {
  2815. *p = 0;
  2816. }
  2817. p = strchr(value, ';');
  2818. if (p != NULL) {
  2819. *p = 0;
  2820. }
  2821. return;
  2822. }
  2823. quote = value[0];
  2824. p2 = value;
  2825. p = value + 1;
  2826. while (*p != 0) {
  2827. if (*p == '\\') {
  2828. p++;
  2829. switch (*p) {
  2830. case '$':
  2831. case '\'':
  2832. case '"':
  2833. case '\\':
  2834. case '`':
  2835. break;
  2836. default:
  2837. /* Keep literal backslash followed by whatever is there */
  2838. p--;
  2839. break;
  2840. }
  2841. } else if (*p == quote) {
  2842. *p2 = 0;
  2843. break;
  2844. }
  2845. *(p2++) = *(p++);
  2846. }
  2847. }
  2848. static GKeyFile *ga_parse_osrelease(const char *fname)
  2849. {
  2850. gchar *content = NULL;
  2851. gchar *content2 = NULL;
  2852. GError *err = NULL;
  2853. GKeyFile *keys = g_key_file_new();
  2854. const char *group = "[os-release]\n";
  2855. if (!g_file_get_contents(fname, &content, NULL, &err)) {
  2856. slog("failed to read '%s', error: %s", fname, err->message);
  2857. goto fail;
  2858. }
  2859. if (!g_utf8_validate(content, -1, NULL)) {
  2860. slog("file is not utf-8 encoded: %s", fname);
  2861. goto fail;
  2862. }
  2863. content2 = g_strdup_printf("%s%s", group, content);
  2864. if (!g_key_file_load_from_data(keys, content2, -1, G_KEY_FILE_NONE,
  2865. &err)) {
  2866. slog("failed to parse file '%s', error: %s", fname, err->message);
  2867. goto fail;
  2868. }
  2869. g_free(content);
  2870. g_free(content2);
  2871. return keys;
  2872. fail:
  2873. g_error_free(err);
  2874. g_free(content);
  2875. g_free(content2);
  2876. g_key_file_free(keys);
  2877. return NULL;
  2878. }
  2879. GuestOSInfo *qmp_guest_get_osinfo(Error **errp)
  2880. {
  2881. GuestOSInfo *info = NULL;
  2882. struct utsname kinfo;
  2883. GKeyFile *osrelease = NULL;
  2884. const char *qga_os_release = g_getenv("QGA_OS_RELEASE");
  2885. info = g_new0(GuestOSInfo, 1);
  2886. if (uname(&kinfo) != 0) {
  2887. error_setg_errno(errp, errno, "uname failed");
  2888. } else {
  2889. info->kernel_version = g_strdup(kinfo.version);
  2890. info->kernel_release = g_strdup(kinfo.release);
  2891. info->machine = g_strdup(kinfo.machine);
  2892. }
  2893. if (qga_os_release != NULL) {
  2894. osrelease = ga_parse_osrelease(qga_os_release);
  2895. } else {
  2896. osrelease = ga_parse_osrelease("/etc/os-release");
  2897. if (osrelease == NULL) {
  2898. osrelease = ga_parse_osrelease("/usr/lib/os-release");
  2899. }
  2900. }
  2901. if (osrelease != NULL) {
  2902. char *value;
  2903. #define GET_FIELD(field, osfield) do { \
  2904. value = g_key_file_get_value(osrelease, "os-release", osfield, NULL); \
  2905. if (value != NULL) { \
  2906. ga_osrelease_replace_special(value); \
  2907. info->field = value; \
  2908. } \
  2909. } while (0)
  2910. GET_FIELD(id, "ID");
  2911. GET_FIELD(name, "NAME");
  2912. GET_FIELD(pretty_name, "PRETTY_NAME");
  2913. GET_FIELD(version, "VERSION");
  2914. GET_FIELD(version_id, "VERSION_ID");
  2915. GET_FIELD(variant, "VARIANT");
  2916. GET_FIELD(variant_id, "VARIANT_ID");
  2917. #undef GET_FIELD
  2918. g_key_file_free(osrelease);
  2919. }
  2920. return info;
  2921. }
  2922. GuestDeviceInfoList *qmp_guest_get_devices(Error **errp)
  2923. {
  2924. error_setg(errp, QERR_UNSUPPORTED);
  2925. return NULL;
  2926. }
  2927. #ifndef HOST_NAME_MAX
  2928. # ifdef _POSIX_HOST_NAME_MAX
  2929. # define HOST_NAME_MAX _POSIX_HOST_NAME_MAX
  2930. # else
  2931. # define HOST_NAME_MAX 255
  2932. # endif
  2933. #endif
  2934. char *qga_get_host_name(Error **errp)
  2935. {
  2936. long len = -1;
  2937. g_autofree char *hostname = NULL;
  2938. #ifdef _SC_HOST_NAME_MAX
  2939. len = sysconf(_SC_HOST_NAME_MAX);
  2940. #endif /* _SC_HOST_NAME_MAX */
  2941. if (len < 0) {
  2942. len = HOST_NAME_MAX;
  2943. }
  2944. /* Unfortunately, gethostname() below does not guarantee a
  2945. * NULL terminated string. Therefore, allocate one byte more
  2946. * to be sure. */
  2947. hostname = g_new0(char, len + 1);
  2948. if (gethostname(hostname, len) < 0) {
  2949. error_setg_errno(errp, errno,
  2950. "cannot get hostname");
  2951. return NULL;
  2952. }
  2953. return g_steal_pointer(&hostname);
  2954. }