commands-posix.c 95 KB

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