session.cpp 10.7 KB
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
/*
 * Copyright © 2005 Novell, Inc.
 *
 * Permission to use, copy, modify, distribute, and sell this software
 * and its documentation for any purpose is hereby granted without
 * fee, provided that the above copyright notice appear in all copies
 * and that both that copyright notice and this permission notice
 * appear in supporting documentation, and that the name of
 * Novell, Inc. not be used in advertising or publicity pertaining to
 * distribution of the software without specific, written prior permission.
 * Novell, Inc. makes no representations about the suitability of this
 * software for any purpose. It is provided "as is" without express or
 * implied warranty.
 *
 * NOVELL, INC. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
 * NO EVENT SHALL NOVELL, INC. BE LIABLE FOR ANY SPECIAL, INDIRECT OR
 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
 * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
 * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
 * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 * Author: Radek Doulik <rodo@novell.com>
 */


#include "core/session.h"
#include "core/screen.h"

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include <stdlib.h>
#include <stdio.h>
#include <poll.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <pwd.h>
#include <X11/SM/SMlib.h>
#include <X11/ICE/ICElib.h>

#include <boost/bind.hpp>

#define SM_DEBUG(x)

static SmcConn           smcConnection;
static CompWatchFdHandle iceWatchFdHandle;
static bool              connected    = false;
static bool              iceConnected = false;
static char              *smClientId, *smPrevClientId;

static void iceInit (void);

static void
setStringListProperty (SmcConn    connection,
		       const char *name,
		       const char **values,
		       int        nValues)
{
    SmProp prop, *pProp;

    prop.name = (char *) name;
    prop.type = const_cast<char *> (SmLISTofARRAY8);

    prop.vals = (SmPropValue *) malloc (nValues * sizeof (SmPropValue));

    if (!prop.vals)
	return;

    for (int i = 0; i < nValues; ++i)
    {
	prop.vals[i].value = (char *) values[i];
	prop.vals[i].length = strlen (values[i]);
    }

    prop.num_vals = nValues;

    pProp = &prop;

    SmcSetProperties (connection, 1, &pProp);

    free (prop.vals);
}

static void
setCloneRestartCommands (SmcConn connection)
{
    /* at maximum, we pass our old arguments + our new client id
       to the SM, so allocate for that case */
    const char **args = (const char **) malloc ((programArgc + 2) * sizeof (char *));

    if (!args)
	return;

    int i, count = 0;

    for (i = 0; i < programArgc; ++i)
    {
	if (strcmp (programArgv[i], "--sm-client-id") == 0)
	    ++i; /* skip old client id, we'll add the new one later */
	else if (strcmp (programArgv[i], "--replace") == 0)
	    continue; /* there's nothing to replace when starting session */
	else
	    args[count++] = programArgv[i];
    }

    setStringListProperty (connection, SmCloneCommand, args, count);

    /* insert new client id at position 1 and 2;
       position 0 is the executable name */
    for (i = count - 1; i >= 1; i--)
	args[i + 2] = args[i];

    args[1] = "--sm-client-id";
    args[2] = smClientId;
    count  += 2;

    setStringListProperty (connection, SmRestartCommand, args, count);

    free (args);
}

static void
setRestartStyle (SmcConn connection,
		 char    hint)
{
    SmProp      prop, *pProp;
    SmPropValue propVal;

    prop.name      = const_cast<char *> (SmRestartStyleHint);
    prop.type      = const_cast<char *> (SmCARD8);
    prop.num_vals  = 1;
    prop.vals      = &propVal;
    propVal.value  = &hint;
    propVal.length = 1;

    pProp = &prop;

    SmcSetProperties (connection, 1, &pProp);
}

static void
setProgramInfo (SmcConn connection,
		pid_t   pid,
		uid_t   uid)
{
    SmProp        progProp, pidProp, userProp;
    SmPropValue   progVal, pidVal, userVal;
    SmProp        *props[3];
    char          pidBuffer[32];
    unsigned int  count = 0;
    struct passwd *pw;

    progProp.name     = const_cast<char *> (SmProgram);
    progProp.type     = const_cast<char *> (SmARRAY8);
    progProp.num_vals = 1;
    progProp.vals     = &progVal;
    progVal.value     = (SmPointer) "compiz";
    progVal.length    = strlen ((char *) progVal.value);

    props[count++] = &progProp;

    snprintf (pidBuffer, sizeof (pidBuffer), "%d", pid);

    pidProp.name     = const_cast<char *> (SmProcessID);
    pidProp.type     = const_cast<char *> (SmARRAY8);
    pidProp.num_vals = 1;
    pidProp.vals     = &pidVal;
    pidVal.value     = (SmPointer) pidBuffer;
    pidVal.length    = strlen (pidBuffer);

    props[count++] = &pidProp;

    pw = getpwuid (uid);

    if (pw)
    {
	userProp.name     = const_cast<char *> (SmUserID);
	userProp.type     = const_cast<char *> (SmARRAY8);
	userProp.num_vals = 1;
	userProp.vals     = &userVal;
	userVal.value     = (SmPointer) pw->pw_name;
	userVal.length    = strlen (pw->pw_name);

	props[count++] = &userProp;
    }

    SmcSetProperties (connection, count, props);
}

static void
saveYourselfCallback (SmcConn   connection,
		      SmPointer client_data,
		      int       saveType,
		      Bool      shutdown,
		      int       interact_Style,
		      Bool      fast)
{
    CompOption::Vector args;

    args.push_back (CompOption ("save_type",      CompOption::TypeInt));
    args.push_back (CompOption ("shutdown",       CompOption::TypeBool));
    args.push_back (CompOption ("interact_style", CompOption::TypeInt));
    args.push_back (CompOption ("fast",           CompOption::TypeBool));

    args[0].value ().set (saveType);
    args[1].value ().set ((bool) shutdown);
    args[2].value ().set (interact_Style);
    args[3].value ().set ((bool) fast);

    screen->sessionEvent (CompSession::EventSaveYourself, args);

    setCloneRestartCommands (connection);
    setRestartStyle (connection, SmRestartImmediately);
    setProgramInfo (connection, getpid (), getuid ());
    SmcSaveYourselfDone (connection, 1);
}

static void
dieCallback (SmcConn   connection,
	     SmPointer clientData)
{
    screen->sessionEvent (CompSession::EventDie, noOptions ());

    CompSession::close ();
    exit (0);
}

static void
saveCompleteCallback (SmcConn	connection,
		      SmPointer clientData)
{
    screen->sessionEvent (CompSession::EventSaveComplete, noOptions ());
}

static void
shutdownCancelledCallback (SmcConn   connection,
			   SmPointer clientData)
{
    screen->sessionEvent (CompSession::EventShutdownCancelled, noOptions ());
}

void
CompSession::init (char *prevClientId)
{
    static SmcCallbacks callbacks;

    if (getenv ("SESSION_MANAGER"))
    {
	char errorBuffer[1024];

	iceInit ();

	callbacks.save_yourself.callback    = saveYourselfCallback;
	callbacks.save_yourself.client_data = NULL;

	callbacks.die.callback    = dieCallback;
	callbacks.die.client_data = NULL;

	callbacks.save_complete.callback    = saveCompleteCallback;
	callbacks.save_complete.client_data = NULL;

	callbacks.shutdown_cancelled.callback    = shutdownCancelledCallback;
	callbacks.shutdown_cancelled.client_data = NULL;

	smcConnection = SmcOpenConnection (NULL,
					   NULL,
					   SmProtoMajor,
					   SmProtoMinor,
					   SmcSaveYourselfProcMask |
					   SmcDieProcMask          |
					   SmcSaveCompleteProcMask |
					   SmcShutdownCancelledProcMask,
					   &callbacks,
					   prevClientId,
					   &smClientId,
					   sizeof (errorBuffer),
					   errorBuffer);
	if (!smcConnection)
	    compLogMessage ("core", CompLogLevelWarn,
			    "SmcOpenConnection failed: %s",
			    errorBuffer);
	else
	{
	    connected = true;

	    if (prevClientId)
		smPrevClientId = strdup (prevClientId);

	    setRestartStyle (smcConnection, SmRestartImmediately);
	}
    }
}

void
CompSession::close ()
{
    if (connected)
    {
	setRestartStyle (smcConnection, SmRestartIfRunning);

	if (SmcCloseConnection (smcConnection, 0, NULL) != SmcConnectionInUse)
	    connected = false;

	if (smClientId)
	{
	    free (smClientId);
	    smClientId = NULL;
	}

	if (smPrevClientId)
	{
	    free (smPrevClientId);
	    smPrevClientId = NULL;
	}
    }
}

CompString
CompSession::getClientId (CompSession::ClientIdType type)
{
    if (!connected)
	return "";

    switch (type)
    {
	case CompSession::ClientId:
	    if (smClientId)
		return smClientId;

	    break;

	case CompSession::PrevClientId:
	    if (smPrevClientId)
		return smPrevClientId;

	    break;

	default:
	    break;
    }

    return "";
}
/* ice connection handling taken and updated from gnome-ice.c
 * original gnome-ice.c code written by Tom Tromey <tromey@cygnus.com>
 */

/* This is called when data is available on an ICE connection. */
static bool
iceProcessMessages (IceConn connection)
{
    SM_DEBUG (printf ("ICE connection process messages\n"));

    IceProcessMessagesStatus status = IceProcessMessages (connection, NULL, NULL);

    if (status == IceProcessMessagesIOError)
    {
	SM_DEBUG (printf ("ICE connection process messages"
			  " - error => shutting down the connection\n"));

	IceSetShutdownNegotiation (connection, False);
	IceCloseConnection (connection);
    }

    return 1;
}

/* This is called when a new ICE connection is made.  It arranges for
   the ICE connection to be handled via the event loop.  */
static void
iceNewConnection (IceConn    connection,
		  IcePointer clientData,
		  Bool	     opening,
		  IcePointer *watchData)
{
    if (opening)
    {
	SM_DEBUG (printf ("ICE connection opening\n"));

	/* Make sure we don't pass on these file descriptors to any
	   exec'ed children */
	fcntl (IceConnectionNumber (connection), F_SETFD,
	       fcntl (IceConnectionNumber (connection),
		      F_GETFD,0) | FD_CLOEXEC);

	iceWatchFdHandle = screen->addWatchFd (IceConnectionNumber (connection),
	    POLLIN | POLLPRI | POLLHUP | POLLERR,
	    boost::bind (iceProcessMessages, connection));

	iceConnected = true;
    }
    else
    {
	SM_DEBUG (printf ("ICE connection closing\n"));

	if (iceConnected)
	{
	    screen->removeWatchFd (iceWatchFdHandle);

	    iceWatchFdHandle = 0;
	    iceConnected = false;
	}
    }
}

static IceIOErrorHandler oldIceHandler;

static void
iceErrorHandler (IceConn connection)
{
    if (oldIceHandler)
	(*oldIceHandler) (connection);
}

/* We call any handler installed before (or after) iceInit but
   avoid calling the default libICE handler which does an exit() */
static void
iceInit (void)
{
    static bool iceInitialized = false;

    if (!iceInitialized)
    {
	IceIOErrorHandler defaultIceHandler;

	oldIceHandler	  = IceSetIOErrorHandler (NULL);
	defaultIceHandler = IceSetIOErrorHandler (iceErrorHandler);

	if (oldIceHandler == defaultIceHandler)
	    oldIceHandler = NULL;

	IceAddConnectionWatch (iceNewConnection, NULL);

	iceInitialized = true;
    }
}