aboutsummaryrefslogtreecommitdiff
path: root/xbmc/osx/XBMCHelper.cpp
blob: 2b6fd352c95558ec3b02e4988159f57b07ba6694 (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
/*
 *      Copyright (C) 2005-2013 Team XBMC
 *      http://xbmc.org
 *
 *  This Program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2, or (at your option)
 *  any later version.
 *
 *  This Program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with XBMC; see the file COPYING.  If not, see
 *  <http://www.gnu.org/licenses/>.
 *
 */

#if defined(__APPLE__) && !defined(__arm__)
#include <fstream>
#include <signal.h>
#include <sstream>
#include <mach-o/dyld.h>

#include "XBMCHelper.h"
#include "PlatformDefs.h"
#include "Util.h"

#include "dialogs/GUIDialogOK.h"
#include "dialogs/GUIDialogYesNo.h"
#include "utils/log.h"
#include "system.h"
#include "settings/Setting.h"
#include "settings/Settings.h"
#include "utils/SystemInfo.h"

#include "threads/Atomics.h"

static long sg_singleton_lock_variable = 0;
XBMCHelper* XBMCHelper::smp_instance = 0;

#define XBMC_HELPER_PROGRAM "XBMCHelper"
#define SOFA_CONTROL_PROGRAM "Sofa Control"
#define XBMC_LAUNCH_PLIST "org.xbmc.helper.plist"

static int GetBSDProcessList(kinfo_proc **procList, size_t *procCount);

XBMCHelper&
XBMCHelper::GetInstance()
{
  CAtomicSpinLock lock(sg_singleton_lock_variable);
  if( ! smp_instance )
  {
    smp_instance = new XBMCHelper();
  }
  return *smp_instance;
}

/////////////////////////////////////////////////////////////////////////////
XBMCHelper::XBMCHelper()
  : m_alwaysOn(false)
  , m_mode(APPLE_REMOTE_DISABLED)
  , m_sequenceDelay(0)
  , m_port(0)
  , m_errorStarting(false)
{
  // Compute the XBMC_HOME path.
  CStdString homePath;
  CUtil::GetHomePath(homePath);
  m_homepath = homePath;

  // Compute the helper filename.
  m_helperFile = m_homepath + "/tools/darwin/runtime/";
  m_helperFile += XBMC_HELPER_PROGRAM;
  
  // Compute the local (pristine) launch agent filename.
  m_launchAgentLocalFile = m_homepath + "/tools/darwin/runtime/";
  m_launchAgentLocalFile += XBMC_LAUNCH_PLIST;

  // Compute the install path for the launch agent.
  // not to be confused with app home, this is user home
  m_launchAgentInstallFile = getenv("HOME");
  m_launchAgentInstallFile += "/Library/LaunchAgents/";
  m_launchAgentInstallFile += XBMC_LAUNCH_PLIST;

  // Compute the configuration file name.
  m_configFile = getenv("HOME");
  m_configFile += "/Library/Application Support/XBMC/XBMCHelper.conf";
}

/////////////////////////////////////////////////////////////////////////////
bool XBMCHelper::OnSettingChanging(const CSetting *setting)
{
  if (setting == NULL)
    return false;

  const std::string &settingId = setting->GetId();
  if (settingId == "input.appleremotemode")
  {
    int remoteMode = ((CSettingInt*)setting)->GetValue();

    // if it's not disabled, start the event server or else apple remote won't work
    if (remoteMode != APPLE_REMOTE_DISABLED)
    {
      // if starting the event server fails, we have to revert the change
      if (!CSettings::Get().SetBool("services.esenabled", true))
        return false;
    }

    // if XBMC helper is running, prompt user before effecting change
    if (IsRunning() && GetMode() != remoteMode)
    {
      bool cancelled;
      if (!CGUIDialogYesNo::ShowAndGetInput(13144, 13145, 13146, 13147, -1, -1, cancelled, 10000))
        return false;
      // reload configuration
      else
        Configure();
    }
    // set new configuration.
    else
      Configure();

    if (ErrorStarting() == true)
    {
      // inform user about error
      CGUIDialogOK::ShowAndGetInput(13620, 13621, 20022, 20022);
      return false;
    }
  }

  return true;
}

/////////////////////////////////////////////////////////////////////////////
void XBMCHelper::Start()
{
  int pid = GetProcessPid(XBMC_HELPER_PROGRAM);
  if (pid == -1)
  {
    //printf("Asking helper to start.\n");
    // use -x to have XBMCHelper read its configure file
    std::string cmd = "\"" + m_helperFile + "\" -x &";
    system(cmd.c_str());
  }
}

/////////////////////////////////////////////////////////////////////////////
void XBMCHelper::Stop()
{

  // Kill the process.
  int pid = GetProcessPid(XBMC_HELPER_PROGRAM);
  if (pid != -1)
  {
    printf("Asked to stop\n");
    kill(pid, SIGKILL);
  }
}

/////////////////////////////////////////////////////////////////////////////
void XBMCHelper::Configure()
{
  int oldMode = m_mode;
  int oldDelay = m_sequenceDelay;
  int oldAlwaysOn = m_alwaysOn;
  int oldPort = m_port;

  // Read the new configuration.
  m_errorStarting = false;
  m_mode = CSettings::Get().GetInt("input.appleremotemode");
  m_sequenceDelay = CSettings::Get().GetInt("input.appleremotesequencetime");
  m_alwaysOn = CSettings::Get().GetBool("input.appleremotealwayson");
  m_port = CSettings::Get().GetInt("services.esport");


  // Don't let it enable if sofa control or remote buddy is around.
  if (IsRemoteBuddyInstalled() || IsSofaControlRunning())
  {
    // If we were starting then remember error.
    if (oldMode == APPLE_REMOTE_DISABLED && m_mode != APPLE_REMOTE_DISABLED)
      m_errorStarting = true;

    m_mode = APPLE_REMOTE_DISABLED;
    CSettings::Get().SetInt("input.appleremotemode", APPLE_REMOTE_DISABLED);
  }

  // New configuration.
  if (oldMode != m_mode || oldDelay != m_sequenceDelay || oldPort != m_port)
  {
    // Build a new config string.
    std::string strConfig;
    switch (m_mode) {
      case APPLE_REMOTE_UNIVERSAL:
        strConfig = "--universal ";
        break;
      case APPLE_REMOTE_MULTIREMOTE:
        strConfig = "--multiremote ";
        break;
      default:
        break;
    }
    std::stringstream strPort;
    strPort << "--port " << m_port;
    strConfig += strPort.str();

#ifdef _DEBUG
    strConfig += "--verbose ";
#endif
    char strDelay[64];
    sprintf(strDelay, "--timeout %d ", m_sequenceDelay);
    strConfig += strDelay;

    // Find out where we're running from.
    char real_path[2*MAXPATHLEN];
    char given_path[2*MAXPATHLEN];
    uint32_t path_size = 2*MAXPATHLEN;

    if (_NSGetExecutablePath(given_path, &path_size) == 0)
    {
      if (realpath(given_path, real_path) != NULL)
      {
        strConfig += "--appPath \"";
        strConfig += real_path;
        strConfig += "\" ";

        strConfig += "--appHome \"";
        strConfig += m_homepath;
        strConfig += "\" ";
      }
    }

    // Write the new configuration.
    strConfig + "\n";
    WriteFile(m_configFile.c_str(), strConfig);

    // If process is running, kill -HUP to have it reload settings.
    int pid = GetProcessPid(XBMC_HELPER_PROGRAM);
    if (pid != -1)
      kill(pid, SIGHUP);
  }

  // Turning off?
  if (oldMode != APPLE_REMOTE_DISABLED && m_mode == APPLE_REMOTE_DISABLED)
  {
    Stop();
    Uninstall();
  }

  // Turning on.
  if (oldMode == APPLE_REMOTE_DISABLED && m_mode != APPLE_REMOTE_DISABLED)
    Start();

  // Installation/uninstallation.
  if (oldAlwaysOn == false && m_alwaysOn == true)
    Install();
  if (oldAlwaysOn == true && m_alwaysOn == false)
    Uninstall();
}

/////////////////////////////////////////////////////////////////////////////
void XBMCHelper::Install()
{
  // Make sure directory exists.
  std::string strDir = getenv("HOME");
  strDir += "/Library/LaunchAgents";
  CreateDirectory(strDir.c_str(), NULL);

  // Load template.
  std::string plistData = ReadFile(m_launchAgentLocalFile.c_str());

  if (plistData != "") 
  {
      std::string launchd_args;

      // Replace PATH with path to app.
      int start = plistData.find("${PATH}");
      plistData.replace(start, 7, m_helperFile.c_str(), m_helperFile.length());

      // Replace ARG1 with a single argument, additional args 
      // will need ARG2, ARG3 added to plist.
      launchd_args = "-x";
      start = plistData.find("${ARG1}");
      plistData.replace(start, 7, launchd_args.c_str(), launchd_args.length());

      // Install it.
      WriteFile(m_launchAgentInstallFile.c_str(), plistData);

      // Load it if not running already.
      int pid = GetProcessPid(XBMC_HELPER_PROGRAM);
      if (pid == -1)
      {
          std::string cmd = "/bin/launchctl load ";
          cmd += m_launchAgentInstallFile;
          system(cmd.c_str());
      }
  }
}

/////////////////////////////////////////////////////////////////////////////
void XBMCHelper::Uninstall()
{
  // Call the unloader.
  std::string cmd = "/bin/launchctl unload ";
  cmd += m_launchAgentInstallFile;
  system(cmd.c_str());
  
  //this also stops the helper, so restart it here again, if not disabled
  if(m_mode != APPLE_REMOTE_DISABLED)
    Start();

  // Remove the plist file.
  DeleteFile(m_launchAgentInstallFile.c_str());
}

/////////////////////////////////////////////////////////////////////////////
bool XBMCHelper::IsRunning()
{
  return (GetProcessPid(XBMC_HELPER_PROGRAM)!=-1);
}

/////////////////////////////////////////////////////////////////////////////
bool XBMCHelper::IsRemoteBuddyInstalled()
{
  return false;
  // Check for existence of kext file.
  return access("/System/Library/Extensions/RBIOKitHelper.kext", R_OK) != -1;
}

/////////////////////////////////////////////////////////////////////////////
bool XBMCHelper::IsSofaControlRunning()
{
  return false;
  // Check for a "Sofa Control" process running.
  return GetProcessPid(SOFA_CONTROL_PROGRAM) != -1;
}

/////////////////////////////////////////////////////////////////////////////
std::string XBMCHelper::ReadFile(const char* fileName)
{
  std::string ret = "";
  std::ifstream is;
  
  is.open(fileName);
  if( is.good() )
  {
    // Get length of file:
    is.seekg(0, std::ios::end);
    int length = is.tellg();
    is.seekg(0, std::ios::beg);

    // Allocate memory:
    char* buffer = new char [length+1];

    // Read data as a block:
    is.read(buffer,length);
    is.close();
    buffer[length] = '\0';

    ret = buffer;
    delete[] buffer;
  }
  return ret;
}

/////////////////////////////////////////////////////////////////////////////
void XBMCHelper::WriteFile(const char* fileName, const std::string& data)
{
  std::ofstream out(fileName);
  if (!out)
  {
    CLog::Log(LOGERROR, "XBMCHelper: Unable to open file '%s'", fileName);
  }
  else
  {
    // Write new configuration.
    out << data << std::endl;
    out.flush();
    out.close();
  }
}

/////////////////////////////////////////////////////////////////////////////
int XBMCHelper::GetProcessPid(const char* strProgram)
{
  kinfo_proc* mylist = 0;
  size_t mycount = 0;
  int ret = -1;

  GetBSDProcessList(&mylist, &mycount);
  for (size_t k = 0; k < mycount && ret == -1; k++)
  {
    kinfo_proc *proc = NULL;
    proc = &mylist[k];

    // Process names are at most sixteen characters long.
    if (strncmp(proc->kp_proc.p_comm, strProgram, 16) == 0)
    {
      ret = proc->kp_proc.p_pid;
    }
  }

  free (mylist);

  return ret;
}

typedef struct kinfo_proc kinfo_proc;

// Returns a list of all BSD processes on the system.  This routine
// allocates the list and puts it in *procList and a count of the
// number of entries in *procCount.  You are responsible for freeing
// this list (use "free" from System framework).
// On success, the function returns 0.
// On error, the function returns a BSD errno value.
//
static int GetBSDProcessList(kinfo_proc **procList, size_t *procCount)
{
  // example from http://developer.apple.com/qa/qa2001/qa1123.html
  int err;
  kinfo_proc * result;
  bool done;
  static const int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };

  // Declaring name as const requires us to cast it when passing it to
  // sysctl because the prototype doesn't include the const modifier.
  size_t length;

  assert(procList != NULL);
  assert(procCount != NULL);

  *procCount = 0;

  // We start by calling sysctl with result == NULL and length == 0.
  // That will succeed, and set length to the appropriate length.
  // We then allocate a buffer of that size and call sysctl again
  // with that buffer.  If that succeeds, we're done.  If that fails
  // with ENOMEM, we have to throw away our buffer and loop.  Note
  // that the loop causes use to call sysctl with NULL again; this
  // is necessary because the ENOMEM failure case sets length to
  // the amount of data returned, not the amount of data that
  // could have been returned.
  //
  result = NULL;
  done = false;
  do
  {
    assert(result == NULL);

    // Call sysctl with a NULL buffer.
    length = 0;
    err = sysctl((int *) name, (sizeof(name) / sizeof(*name)) - 1, NULL,
        &length, NULL, 0);
    if (err == -1)
      err = errno;

    // Allocate an appropriately sized buffer based on the results from the previous call.
    if (err == 0)
    {
      result = (kinfo_proc*) malloc(length);
      if (result == NULL)
        err = ENOMEM;
    }

    // Call sysctl again with the new buffer.  If we get an ENOMEM
    // error, toss away our buffer and start again.
    //
    if (err == 0)
    {
      err = sysctl((int *) name, (sizeof(name) / sizeof(*name)) - 1, result,
          &length, NULL, 0);

      if (err == -1)
        err = errno;
        
      if (err == 0)
      {
        done = true;
      }
      else if (err == ENOMEM)
      {
        assert(result != NULL);
        free(result);
        result = NULL;
        err = 0;
      }
    }
  } while (err == 0 && !done);

  // Clean up and establish post conditions.
  if (err != 0 && result != NULL)
  {
    free(result);
    result = NULL;
  }

  *procList = result;
  if (err == 0)
    *procCount = length / sizeof(kinfo_proc);

  assert( (err == 0) == (*procList != NULL) );
  return err;
}
#endif