commands-posix.c 92 KB

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