2
0

commands-posix.c 91 KB

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