summaryrefslogtreecommitdiff
path: root/src/lib/launchpad-glib/util.cc
blob: b5861f61b708fa2e7d0aa81a81b5e4d6e8c6dc69 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
/*
 * Copyright (c) 2023 Samsung Electronics Co., Ltd All Rights Reserved
 *
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "launchpad-glib/util.hh"

#include <bundle_internal.h>
#include <dbus/dbus.h>
#include <stdlib.h>
#include <sys/mount.h>
#include <sys/personality.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <sys/types.h>
#include <tzplatform_config.h>
#include <unistd.h>

#include <algorithm>
#include <filesystem>
#include <fstream>
#include <memory>
#include <string>
#include <utility>
#include <vector>

#include <aul_keys.hh>
#include <exception.hh>
#include <parcel.hh>
#include <parcelable.hh>
#include <server_socket.hh>
#include <socket.hh>

#include "launchpad-glib/log_private.hh"

#define GLOBAL_USER tzplatform_getuid(TZ_SYS_GLOBALAPP_USER)

namespace fs = std::filesystem;

namespace launchpad {
namespace {

constexpr const char kDefaultLocale[] = "en_US.UTF-8";
constexpr const char kTepBusName[] = "org.tizen.system.deviced";
constexpr const char kTepObjectPath[] = "/Org/Tizen/System/DeviceD/Tzip";
constexpr const char kTepInterfaceName[] = "org.tizen.system.deviced.Tzip";
constexpr const char kTepIsMountedMethod[] = "IsMounted";
const int kMaxTepIsMountRetryCount = 100;
constexpr const char kApp2sdBusName[] = "org.tizen.app2sd";
constexpr const char kApp2sdObjectPath[] = "/org/tizen/app2sd";
constexpr const char kApp2sdInterfaceName[] = "org.tizen.app2sd";
constexpr const char kApp2sdOndemandSetupInitMethod[] = "OndemandSetupInit";
const int kApp2sdRetryMax = 5;
const int kApp2sdWaitUsec = 1000000 / 2;  // 0.5 sec

void SetLanguageEnvironments() {
  const char* lang = getenv("LANG");
  if (lang == nullptr) {
    lang = kDefaultLocale;
    setenv("LANG", lang, 1);
  }

  setenv("LANGUAGE", lang, 1);
  setenv("LC_MESSAGES", lang, 1);
  setenv("LC_ALL", lang, 1);
}

void SetRegionFormatEnvironments() {
  const char* region = getenv("LC_CTYPE");
  if (region == nullptr) {
    region = kDefaultLocale;
    setenv("LC_CTYPE", region, 1);
  }

  setenv("LC_NUMERIC", region, 1);
  setenv("LC_TIME", region, 1);
  setenv("LC_COLLATE", region, 1);
  setenv("LC_MONETARY", region, 1);
  setenv("LC_PAPER", region, 1);
  setenv("LC_NAME", region, 1);
  setenv("LC_ADDRESS", region, 1);
  setenv("LC_TELEPHONE", region, 1);
  setenv("LC_MEASUREMENT", region, 1);
  setenv("LC_IDENTIFICATION", region, 1);
}

void SetGadgetPkgIdsEnvironments(const tizen_base::Bundle& b) {
  auto gadget_pkgids = b.GetStringArray(kAulMountGadgetPkgIds);
  if (gadget_pkgids.empty()) return;

  std::string pkgids;
  for (auto& pkgid : gadget_pkgids) {
    if (!pkgids.empty()) pkgids += ":";

    pkgids += pkgid;
  }

  setenv("GADGET_PKGIDS", pkgids.c_str(), 1);
}

#ifdef TIZEN_FEATURE_SET_PERSONALITY_32
static void SetExecutionDomain() {
  int ret = personality(PER_LINUX32);
  if (ret < 0) {
    char err_buf[1024];
    _E("persionality() is failed. errno: %d(%s)",
        errno, strerror_r(errno, err_buf, sizeof(err_buf)));
  }
}
#endif  // TIZEN_FEATURE_SET_PERSONALITY_32

class DBus {
 public:
  DBus() {
    DBusError error;
    dbus_error_init(&error);
    conn_ = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error);
    if (conn_ == nullptr) {
      _E("Failed to connect to D-Bus Daemon");
      if (dbus_error_is_set(&error)) {
        _E("D-Bus error: %s", error.message);
        dbus_error_free(&error);
      }
      THROW(-ENOTCONN);
    }
  }

  virtual ~DBus() {
    if (conn_ != nullptr)
      dbus_connection_close(conn_);
  }

  void SendMessage(DBusMessage* message, int timeout, int* result) {
    if (message == nullptr) {
      _E("Invalid parameter");
      THROW(-EINVAL);
    }

    DBusPendingCall* pending = nullptr;
    dbus_bool_t ret = dbus_connection_send_with_reply(conn_, message, &pending,
        timeout);
    if (!ret || pending == nullptr) {
      _E("Failed to send message");
      THROW(-EIO);
    }

    dbus_connection_flush(conn_);
    dbus_pending_call_block(pending);
    auto* reply = dbus_pending_call_steal_reply(pending);
    dbus_pending_call_unref(pending);
    if (reply == nullptr) {
      _E("Failed to get reply message");
      THROW(-EIO);
    }

    auto reply_auto =
        std::unique_ptr<DBusMessage, decltype(dbus_message_unref)*>(
            reply, dbus_message_unref);
    DBusMessageIter iter;
    if (!dbus_message_iter_init(reply, &iter)) {
      _E("Message ha no argument");
      THROW(-EIO);
    }

    if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_INT32) {
      _E("Argument is not interger. type(%d)",
          dbus_message_iter_get_arg_type(&iter));
      THROW(-EIO);
    }

    dbus_int32_t res;
    dbus_message_iter_get_basic(&iter, &res);
    *result = static_cast<int>(res);
    _D("Result: %d", *result);
  }

 private:
  DBusConnection* conn_ = nullptr;
};

class TepMountChecker : public DBus {
 public:
  explicit TepMountChecker(std::vector<std::string> paths)
      : paths_(std::move(paths)) {}

  bool IsMounted() {
    for (auto& path : paths_) {
      if (CheckTepMount(path) != 0)
        return false;
    }

    return true;
  }

 private:
  DBusMessage* CreateTepMountMessage(const std::string& path) {
    DBusMessage* message = dbus_message_new_method_call(kTepBusName,
        kTepObjectPath, kTepInterfaceName, kTepIsMountedMethod);
    if (message == nullptr) {
      _E("dbus_message_new_method_call() is failed");
      return nullptr;
    }

    DBusMessageIter iter;
    dbus_message_iter_init_append(message, &iter);
    auto* tep_path = path.c_str();
    auto ret = dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING,
        &tep_path);
    if (!ret) {
      _E("dbus_message_iter_append_basic() is failed");
      dbus_message_unref(message);
      return nullptr;
    }

    return message;
  }

  int IsTepMountDone(const std::string& path) {
    int result = -1;
    auto message = std::unique_ptr<DBusMessage, decltype(dbus_message_unref)*>(
        CreateTepMountMessage(path), dbus_message_unref);
    SendMessage(message.get(), 500, &result);
    return result;
  }

  int CheckTepMount(const std::string& path) {
    if (path.empty())
      return 0;

    int count = 0;
    while (count < kMaxTepIsMountRetryCount) {
      if (IsTepMountDone(path) == 1)
        return 0;

      usleep(50 * 1000);
      count++;
    }

    _E("Not able to mount within 5 seconds. path(%s", path.c_str());
    return -1;
  }

 private:
  std::vector<std::string> paths_;
};

int MountDirectories(const std::vector<std::string>& srcs,
    const std::string& dest) {
  std::string opt = "lowerdir=" + dest;
  for (auto& src : srcs)
    opt += ":" + src;

  _D("mount opt: %s", opt.c_str());
  int ret = mount(nullptr, dest.c_str(), "overlay", MS_RDONLY, opt.c_str());
  if (ret != 0)
    _E("mount() is failed. dest(%s), errno(%d)", dest.c_str(), errno);

  return ret;
}

class ExternalPackage : public DBus {
 public:
  ExternalPackage(std::string package, uid_t uid)
      : package_(std::move(package)), uid_(uid) {
    _D("package(%s), uid(%u)", package_.c_str(), uid_);
  }

  void Enable() {
    int result = -1;
    int retry_count = 0;
    auto message = std::unique_ptr<DBusMessage, decltype(dbus_message_unref)*>(
        CreateApp2sdMessage(), dbus_message_unref);
    while (retry_count <= kApp2sdRetryMax) {
      try {
        SendMessage(message.get(), 500, &result);
      } catch (const Exception& e) {
        _E("Exception occurs. error(%s)", e.what());
        retry_count++;
        continue;
      }

      break;
    }

    _D("Result: %d", result);
    if (result < 0)
      THROW(-EIO);
  }

 private:
  DBusMessage* CreateApp2sdMessage() {
    DBusMessage* message = dbus_message_new_method_call(kApp2sdBusName,
        kApp2sdObjectPath, kApp2sdInterfaceName,
        kApp2sdOndemandSetupInitMethod);
    if (message == nullptr) {
      _E("dbus_message_new_method_call() is failed");
      return nullptr;
    }

    DBusMessageIter iter;
    dbus_message_iter_init_append(message, &iter);
    const char* package = package_.c_str();
    if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &package)) {
      _E("dbus_message_iter_append_basic() is failed");
      dbus_message_unref(message);
      return nullptr;
    }

    if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_INT32, &uid_)) {
      _E("dbus_message_iter_append_basic() is failed");
      dbus_message_unref(message);
      return nullptr;
    }

    return message;
  }

 private:
  std::string package_;
  uid_t uid_;
};

class AmdPacket : public tizen_base::Parcelable {
 public:
  explicit AmdPacket(int cmd, bundle* request, int opt)
      : cmd_(cmd), request_(request), opt_(opt) {}

  void WriteToParcel(tizen_base::Parcel* parcel) const {
    parcel->WriteInt32(cmd_);
    if (request_ == nullptr) {
      parcel->WriteInt32(0);
      parcel->WriteInt32(opt_);
    } else {
      bundle_raw* raw = nullptr;
      int len = 0;
      bundle_encode(request_, &raw, &len);
      parcel->WriteInt32(len);
      parcel->WriteInt32(opt_);
      parcel->Write(reinterpret_cast<unsigned char*>(raw), len);
      bundle_free_encoded_rawdata(&raw);
    }
  }

  void ReadFromParcel(tizen_base::Parcel* parcel) {
    parcel->ReadInt32(&cmd_);
  }

 private:
  int cmd_ = -1;
  bundle* request_ = nullptr;
  int opt_ = 0;
};

}  // namespace

void Util::SetEnvironments(const AppInfo* app_info) {
  auto& b = app_info->GetBundle();
  auto value = b.GetString(kAulStarttime);
  if (!value.empty())
    setenv("APP_START_TIME", value.c_str(), 1);

  if (!app_info->GetHwacc().empty())
    setenv("HWACC", app_info->GetHwacc().c_str(), 1);

  if (!app_info->GetTaskmanage().empty())
    setenv("TASKMANAGE", app_info->GetTaskmanage().c_str(), 1);

  if (!app_info->GetRootPath().empty())
    setenv("AUL_ROOT_PATH", app_info->GetRootPath().c_str(), 1);

  if (!app_info->GetAppId().empty()) {
    auto multiple_instance_app_id = b.GetString(kAulMultipleInstanceAppId);
    if (!multiple_instance_app_id.empty())
      setenv("AUL_APPID", multiple_instance_app_id.c_str(), 1);
    else
      setenv("AUL_APPID", app_info->GetAppId().c_str(), 1);
  }

  if (!app_info->GetPkgId().empty())
    setenv("AUL_PKGID", app_info->GetPkgId().c_str(), 1);

  if (!app_info->GetAppType().empty())
    setenv("RUNTIME_TYPE", app_info->GetAppType().c_str(), 1);

  value = b.GetString(kAulWaylandDisplay);
  if (!value.empty())
    setenv("WAYLAND_DISPLAY", value.c_str(), 1);

  value = b.GetString(kAulWaylandWorkingDir);
  if (!value.empty())
    setenv("XDG_RUNTIME_DIR", value.c_str(), 1);

  value = b.GetString(kAulApiVersion);
  if (!value.empty())
    setenv("TIZEN_API_VERSION", value.c_str(), 1);

  setenv("AUL_PID", std::to_string(getpid()).c_str(), 1);

  if (getenv("TIZEN_GLIB_CONTEXT") == nullptr)
    setenv("TIZEN_GLIB_CONTEXT", "0", 1);

  value = b.GetString(kAulFastLaunch);
  if (!value.empty())
    setenv("AUL_FAST_LAUNCH", value.c_str(), 1);

  SetLanguageEnvironments();
  SetRegionFormatEnvironments();

#ifdef TIZEN_FEATURE_SET_PERSONALITY_32
  SetExecutionDomain();
#endif  // TIZEN_FEATURE_SET_PERSONALITY_32

  setenv("GCOV_PREFIX", "/tmp", 1);
  setenv("DALI_DISABLE_PARTIAL_UPDATE", "0", 1);
  SetGadgetPkgIdsEnvironments(b);
}

void Util::DeleteSocketPath(pid_t pid, uid_t uid) {
  std::string path ="/run/aul/apps/" + std::to_string(uid) + "/" +
      std::to_string(pid);
  if (!fs::exists(path))
    return;

  try {
    fs::remove_all(path);
  } catch (const std::exception& e) {
    _E("Exception occurs. error: %s", e.what());
  }
}

int Util::EnableExternalPackage(const AppInfo* app_info) {
  auto installed_storage = app_info->GetBundle().GetString(
      kAulInstalledStorage);
  if (installed_storage != "external")
    return 0;

  try {
    ExternalPackage external_package(app_info->GetPkgId(),
        app_info->IsGlobal() ? GLOBAL_USER : getuid());
    external_package.Enable();
  } catch (const Exception& e) {
    _E("Exception occurs. error(%s)", e.what());
    return -1;
  }

  return 0;
}

int Util::MountResourceDirectories(const AppInfo* app_info) {
  auto& root_path = app_info->GetRootPath();
  auto& b = app_info->GetBundle();
  auto global_res_dir = b.GetStringArray(kAulMountGlobalResDir);
  if (!global_res_dir.empty())
    MountDirectories(global_res_dir, root_path + "/res/mount/global");

  auto allowed_res_dir = b.GetStringArray(kAulMountAllowedResDir);
  if (!allowed_res_dir.empty())
    MountDirectories(allowed_res_dir, root_path + "/res/mount/allowed");

  auto res_pkgids = b.GetStringArray(kAulMountResPkgIds);
  if (!res_pkgids.empty()) {
    std::string pkgids;
    for (auto& pkgid : res_pkgids) {
      if (!pkgids.empty())
        pkgids += ":";

      pkgids += pkgid;
    }

    setenv("RES_PKGIDS", pkgids.c_str(), 1);
  }

  return 0;
}

int Util::MountGadgetDirectories(const tizen_base::Bundle& b) {
  auto gadget_paths = b.GetStringArray(kAulMountGadgetPaths);
  if (!gadget_paths.empty()) {
    auto root_path = b.GetString(kAulRootPath);
    return MountDirectories(gadget_paths, root_path + "/bin");
  }

  return 0;
}

int Util::WaitTepMount(const AppInfo* app_info) {
  if (app_info->GetBundle().GetType(kAulTepPath) == BUNDLE_TYPE_NONE)
    return 0;

  try {
    auto paths = app_info->GetBundle().GetStringArray(kAulTepPath);
    TepMountChecker checker(std::move(paths));
    if (!checker.IsMounted())
      return -1;
  } catch (const Exception& e) {
    _E("Exception occurs. error(%s)", e.what());
    return e.GetErrorCode();
  }

  _I("TEP Mount has been done");
  return 0;
}

std::string Util::GetLibDirectory(const std::string& app_path) {
  std::filesystem::path path(app_path);
  auto lib_dir = path.parent_path().string() + "/../lib/";
  if (std::filesystem::exists(lib_dir))
    return lib_dir;

  return "";
}

void Util::CloseAllFds(const std::vector<int>& except_fds) {
  int aul_fd = -1;
  const char* aul_listen_fd = getenv("AUL_LISTEN_FD");
  if (aul_listen_fd != nullptr)
    aul_fd = atoi(aul_listen_fd);

  std::vector<int> fds;
  try {
    fs::path proc_path("/proc/self/fd");
    for (const auto& entry : fs::directory_iterator(proc_path)) {
      if (!isdigit(entry.path().filename().string()[0]))
        continue;

      int fd = std::stoi(entry.path().filename().string());
      if (fd < 3 || fd == aul_fd)
        continue;

      auto found = std::find_if(except_fds.begin(), except_fds.end(),
          [&](int except_fd) {
            return except_fd == fd;
          });
      if (found != except_fds.end())
        continue;

      fds.push_back(fd);
    }
  } catch (const fs::filesystem_error& e) {
    _E("Execption occurs. error(%s)", e.what());
  }

  _W("size: %zd", fds.size());
  for (auto fd : fds)
    close(fd);
}

int Util::PrepareAppSocket() {
  try {
    std::string path = "/run/aul/apps/" + std::to_string(getuid()) + "/" +
        std::to_string(getpid());
    if (access(path.c_str(), F_OK) != 0)
      fs::create_directory(path);

    path += "/.app-sock";
    ServerSocket socket;
    socket.Bind(path);
    socket.Listen(128);
    socket.SetReceiveBufferSize(Socket::kSocketMaxBufferSize);
    socket.SetSendBufferSize(Socket::kSocketMaxBufferSize);
    socket.SetCloseOnExec(false);
    int fd = socket.RemoveFd();
    setenv("AUL_LISTEN_FD", std::to_string(fd).c_str(), 1);
  } catch (const Exception& e) {
    _E("Exception occurs. error(%s)", e.what());
    return e.GetErrorCode();
  }

  return 0;
}

int Util::PrepareAppIdFile(const AppInfo* app_info) {
  std::string path = "/run/aul/apps/" + std::to_string(getuid()) + "/" +
      std::to_string(getpid()) + "/" + app_info->GetAppId();
  std::ofstream stream(path);
  stream.close();
  return 0;
}

int Util::SendCmdToAmd(enum AmdCmd cmd) {
  return SendCmdToAmd(cmd, nullptr, static_cast<int>(AmdSocketOption::None));
}

int Util::SendCmdToAmd(enum AmdCmd cmd, bundle* request, int opt) {
  try {
    std::string endpoint = "/run/aul/daemons/.amd-sock";
    ClientSocket socket;
    socket.Connect(endpoint);
    socket.SetReceiveBufferSize(Socket::kSocketMaxBufferSize);
    socket.SetReceiveTimeout(5000);

    AmdPacket packet(static_cast<int>(cmd), request, opt);
    tizen_base::Parcel parcel;
    parcel.WriteParcelable(packet);

    int ret = socket.Send(parcel.GetData(), parcel.GetDataSize());
    if (ret != 0) {
      _E("Failed to send cmd(%d), error(%d)", static_cast<int>(cmd), ret);
      return -ECOMM;
    }
  } catch (const Exception& e) {
    _E("Exception occrus. error(%s)", e.what());
    return e.GetErrorCode();
  }

  return 0;
}

}  // namespace launchpad