commands-posix.c 95 KB

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