nm-modem-broadband.c 44.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* NetworkManager -- Network link manager
 *
 * 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 of the License, 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 this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Copyright (C) 2012 Aleksander Morgado <aleksander@gnu.org>
 */

21
#include "nm-default.h"
22

23
#include <string.h>
24
#include <arpa/inet.h>
25
#include <libmm-glib.h>
26

27
#include "nm-modem-broadband.h"
28
#include "nm-core-internal.h"
29 30
#include "NetworkManagerUtils.h"
#include "nm-device-private.h"
31
#include "nm-platform.h"
32 33 34

G_DEFINE_TYPE (NMModemBroadband, nm_modem_broadband, NM_TYPE_MODEM)

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
typedef enum {
    CONNECT_STEP_FIRST,
    CONNECT_STEP_WAIT_FOR_SIM,
    CONNECT_STEP_UNLOCK,
    CONNECT_STEP_WAIT_FOR_READY,
    CONNECT_STEP_CONNECT,
    CONNECT_STEP_LAST
} ConnectStep;

typedef struct {
	NMModemBroadband *self;
	ConnectStep step;

	MMModemCapability caps;
	NMConnection *connection;
	GCancellable *cancellable;
	MMSimpleConnectProperties *connect_properties;
	GArray *ip_types;
	guint ip_types_i;
54
	guint ip_type_tries;
55 56 57
	GError *first_error;
} ConnectContext;

58 59 60 61 62 63
struct _NMModemBroadbandPrivate {
	/* The modem object from dbus */
	MMObject *modem_object;
	/* Per-interface objects */
	MMModem *modem_iface;
	MMModemSimple *simple_iface;
64
	MMSim *sim_iface;
65 66

	/* Connection setup */
67
	ConnectContext *ctx;
68

69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
	MMBearer *bearer;
	MMBearerIpConfig *ipv4_config;
	MMBearerIpConfig *ipv6_config;

	guint32 pin_tries;
};

enum {
	PROP_0,
	PROP_MODEM,
};

#define MODEM_CAPS_3GPP(caps) (caps & (MM_MODEM_CAPABILITY_GSM_UMTS |    \
                                       MM_MODEM_CAPABILITY_LTE |         \
                                       MM_MODEM_CAPABILITY_LTE_ADVANCED))

#define MODEM_CAPS_3GPP2(caps) (caps & (MM_MODEM_CAPABILITY_CDMA_EVDO))

87 88 89
/* Maximum time to keep the DBus call waiting for a connection result */
#define MODEM_CONNECT_TIMEOUT_SECS 120

90 91 92 93 94 95 96
/*****************************************************************************/

static NMDeviceStateReason
translate_mm_error (GError *error)
{
	NMDeviceStateReason reason;

97 98
	g_return_val_if_fail (error != NULL, NM_DEVICE_STATE_REASON_UNKNOWN);

99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
	if (g_error_matches (error, MM_CONNECTION_ERROR, MM_CONNECTION_ERROR_NO_CARRIER))
		reason = NM_DEVICE_STATE_REASON_MODEM_NO_CARRIER;
	else if (g_error_matches (error, MM_CONNECTION_ERROR, MM_CONNECTION_ERROR_NO_DIALTONE))
		reason = NM_DEVICE_STATE_REASON_MODEM_NO_DIAL_TONE;
	else if (g_error_matches (error, MM_CONNECTION_ERROR, MM_CONNECTION_ERROR_BUSY))
		reason = NM_DEVICE_STATE_REASON_MODEM_BUSY;
	else if (g_error_matches (error, MM_CONNECTION_ERROR, MM_CONNECTION_ERROR_NO_ANSWER))
		reason = NM_DEVICE_STATE_REASON_MODEM_DIAL_TIMEOUT;
	else if (g_error_matches (error, MM_MOBILE_EQUIPMENT_ERROR, MM_MOBILE_EQUIPMENT_ERROR_NETWORK_NOT_ALLOWED))
		reason = NM_DEVICE_STATE_REASON_GSM_REGISTRATION_DENIED;
	else if (g_error_matches (error, MM_MOBILE_EQUIPMENT_ERROR, MM_MOBILE_EQUIPMENT_ERROR_NETWORK_TIMEOUT))
		reason = NM_DEVICE_STATE_REASON_GSM_REGISTRATION_TIMEOUT;
	else if (g_error_matches (error, MM_MOBILE_EQUIPMENT_ERROR, MM_MOBILE_EQUIPMENT_ERROR_NO_NETWORK))
		reason = NM_DEVICE_STATE_REASON_GSM_REGISTRATION_NOT_SEARCHING;
	else if (g_error_matches (error, MM_MOBILE_EQUIPMENT_ERROR, MM_MOBILE_EQUIPMENT_ERROR_SIM_NOT_INSERTED))
		reason = NM_DEVICE_STATE_REASON_GSM_SIM_NOT_INSERTED;
	else if (g_error_matches (error, MM_MOBILE_EQUIPMENT_ERROR, MM_MOBILE_EQUIPMENT_ERROR_SIM_PIN))
		reason = NM_DEVICE_STATE_REASON_GSM_SIM_PIN_REQUIRED;
	else if (g_error_matches (error, MM_MOBILE_EQUIPMENT_ERROR, MM_MOBILE_EQUIPMENT_ERROR_SIM_PUK))
		reason = NM_DEVICE_STATE_REASON_GSM_SIM_PUK_REQUIRED;
	else if (g_error_matches (error, MM_MOBILE_EQUIPMENT_ERROR, MM_MOBILE_EQUIPMENT_ERROR_SIM_WRONG))
		reason = NM_DEVICE_STATE_REASON_GSM_SIM_WRONG;
121 122
	else if (g_error_matches (error, MM_MOBILE_EQUIPMENT_ERROR, MM_MOBILE_EQUIPMENT_ERROR_INCORRECT_PASSWORD))
		reason = NM_DEVICE_STATE_REASON_SIM_PIN_INCORRECT;
123 124 125 126 127 128 129 130 131 132 133
	else {
		/* unable to map the ModemManager error to a NM_DEVICE_STATE_REASON */
		nm_log_dbg (LOGD_MB, "unmapped error detected: '%s'", error->message);
		reason = NM_DEVICE_STATE_REASON_UNKNOWN;
	}

	return reason;
}

/*****************************************************************************/

134 135 136 137
static void
get_capabilities (NMModem *_self,
                  NMDeviceModemCapabilities *modem_caps,
                  NMDeviceModemCapabilities *current_caps)
138
{
139
	NMModemBroadband *self = NM_MODEM_BROADBAND (_self);
140 141 142
	MMModemCapability all_supported = MM_MODEM_CAPABILITY_NONE;
	MMModemCapability *supported;
	guint n_supported;
143

144 145 146 147 148 149 150 151 152 153 154 155 156
	/* For now, we don't care about the capability combinations, just merge all
	 * combinations in a single mask */
	if (mm_modem_get_supported_capabilities (self->priv->modem_iface, &supported, &n_supported)) {
		guint i;

		for (i = 0; i < n_supported; i++)
			all_supported |= supported[i];

		g_free (supported);
	}

	*modem_caps = (NMDeviceModemCapabilities) all_supported;
	*current_caps = (NMDeviceModemCapabilities) mm_modem_get_current_capabilities (self->priv->modem_iface);
157 158
}

159 160 161 162 163 164 165 166 167 168 169 170 171 172
static gboolean
owns_port (NMModem *_self, const char *iface)
{
	NMModemBroadband *self = NM_MODEM_BROADBAND (_self);
	const MMModemPortInfo *ports = NULL;
	guint n_ports = 0, i;
	gboolean owns = FALSE;

	mm_modem_peek_ports (self->priv->modem_iface, &ports, &n_ports);
	for (i = 0; i < n_ports && !owns; i++)
		owns = (g_strcmp0 (iface, ports[i].name) == 0);
	return owns;
}

173 174 175 176 177 178 179 180 181 182 183 184 185 186
/*****************************************************************************/

static void
ask_for_pin (NMModemBroadband *self)
{
	guint32 tries;

	tries = self->priv->pin_tries++;
	nm_modem_get_secrets (NM_MODEM (self),
	                      NM_SETTING_GSM_SETTING_NAME,
	                      tries ? TRUE : FALSE,
	                      NM_SETTING_GSM_PIN);
}

187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
static NMModemIPMethod
get_bearer_ip_method (MMBearerIpConfig *config)
{
	MMBearerIpMethod mm_method;

	mm_method = mm_bearer_ip_config_get_method (config);
	if (mm_method == MM_BEARER_IP_METHOD_PPP)
		return NM_MODEM_IP_METHOD_PPP;
	else if (mm_method == MM_BEARER_IP_METHOD_STATIC)
		return NM_MODEM_IP_METHOD_STATIC;
	else if (mm_method == MM_BEARER_IP_METHOD_DHCP)
		return NM_MODEM_IP_METHOD_AUTO;
	return NM_MODEM_IP_METHOD_UNKNOWN;
}

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
static MMSimpleConnectProperties *
create_cdma_connect_properties (NMConnection *connection)
{
	NMSettingCdma *setting;
	MMSimpleConnectProperties *properties;
	const gchar *str;

	setting = nm_connection_get_setting_cdma (connection);
	properties = mm_simple_connect_properties_new ();

	str = nm_setting_cdma_get_number (setting);
	if (str)
		mm_simple_connect_properties_set_number (properties, str);

	return properties;
}

static MMSimpleConnectProperties *
220
create_gsm_connect_properties (NMConnection *connection)
221 222
{
	NMSettingGsm *setting;
223
	NMSettingPpp *s_ppp;
224 225 226 227 228 229 230 231 232 233 234
	MMSimpleConnectProperties *properties;
	const gchar *str;

	setting = nm_connection_get_setting_gsm (connection);
	properties = mm_simple_connect_properties_new ();

	/* TODO: not needed */
	str = nm_setting_gsm_get_number (setting);
	if (str)
		mm_simple_connect_properties_set_number (properties, str);

235
	/* Blank APN ("") means the default subscription APN */
236
	str = nm_setting_gsm_get_apn (setting);
237
	mm_simple_connect_properties_set_apn (properties, str ? str : "");
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

	str = nm_setting_gsm_get_network_id (setting);
	if (str)
		mm_simple_connect_properties_set_operator_id (properties, str);

	str = nm_setting_gsm_get_pin (setting);
	if (str)
		mm_simple_connect_properties_set_pin (properties, str);

	str = nm_setting_gsm_get_username (setting);
	if (str)
		mm_simple_connect_properties_set_user (properties, str);

	str = nm_setting_gsm_get_password (setting);
	if (str)
		mm_simple_connect_properties_set_password (properties, str);

	/* Roaming */
	if (nm_setting_gsm_get_home_only (setting))
		mm_simple_connect_properties_set_allow_roaming (properties, FALSE);

	/* For IpMethod == STATIC or DHCP */
	s_ppp = nm_connection_get_setting_ppp (connection);
	if (s_ppp) {
		MMBearerAllowedAuth allowed_auth = MM_BEARER_ALLOWED_AUTH_UNKNOWN;

		if (nm_setting_ppp_get_noauth (s_ppp))
			allowed_auth = MM_BEARER_ALLOWED_AUTH_NONE;
		if (!nm_setting_ppp_get_refuse_pap (s_ppp))
			allowed_auth |= MM_BEARER_ALLOWED_AUTH_PAP;
		if (!nm_setting_ppp_get_refuse_chap (s_ppp))
			allowed_auth |= MM_BEARER_ALLOWED_AUTH_CHAP;
		if (!nm_setting_ppp_get_refuse_mschap (s_ppp))
			allowed_auth |= MM_BEARER_ALLOWED_AUTH_MSCHAP;
		if (!nm_setting_ppp_get_refuse_mschapv2 (s_ppp))
			allowed_auth |= MM_BEARER_ALLOWED_AUTH_MSCHAPV2;
		if (!nm_setting_ppp_get_refuse_eap (s_ppp))
			allowed_auth |= MM_BEARER_ALLOWED_AUTH_EAP;

		mm_simple_connect_properties_set_allowed_auth (properties, allowed_auth);
	}

280 281 282 283
	return properties;
}

static void
284
connect_context_clear (NMModemBroadband *self)
285
{
286 287 288 289 290 291 292 293 294 295 296 297
	if (self->priv->ctx) {
		ConnectContext *ctx = self->priv->ctx;

		g_clear_error (&ctx->first_error);
		g_clear_pointer (&ctx->ip_types, (GDestroyNotify) g_array_unref);
		g_clear_object (&ctx->cancellable);
		g_clear_object (&ctx->connection);
		g_clear_object (&ctx->connect_properties);
		g_clear_object (&ctx->self);
		g_slice_free (ConnectContext, ctx);
		self->priv->ctx = NULL;
	}
298 299
}

300
static void connect_context_step (NMModemBroadband *self);
301 302 303 304

static void
connect_ready (MMModemSimple *simple_iface,
               GAsyncResult *res,
305
               NMModemBroadband *self)
306
{
307
	ConnectContext *ctx = self->priv->ctx;
308 309 310 311
	GError *error = NULL;
	NMModemIPMethod ip4_method = NM_MODEM_IP_METHOD_UNKNOWN;
	NMModemIPMethod ip6_method = NM_MODEM_IP_METHOD_UNKNOWN;

312 313
	self->priv->bearer = mm_modem_simple_connect_finish (simple_iface, res, &error);
	if (!self->priv->bearer) {
314 315
		if (g_error_matches (error, MM_MOBILE_EQUIPMENT_ERROR, MM_MOBILE_EQUIPMENT_ERROR_SIM_PIN) ||
		    (g_error_matches (error, MM_CORE_ERROR, MM_CORE_ERROR_UNAUTHORIZED) &&
316
		     mm_modem_get_unlock_required (self->priv->modem_iface) == MM_MODEM_LOCK_SIM_PIN)) {
317
			g_error_free (error);
318 319 320 321

			/* Request PIN */
			ask_for_pin (self);
			connect_context_clear (self);
322 323 324 325 326 327 328 329 330 331 332 333
			return;
		}

		/* Save the error, if it's the first one */
		if (!ctx->first_error) {
			/* Strip remote error info before saving it */
			if (g_dbus_error_is_remote_error (error))
				g_dbus_error_strip_remote_error (error);
			ctx->first_error = error;
		} else
			g_error_free (error);

334 335 336 337 338 339 340 341 342 343 344
		if (ctx->ip_type_tries == 0 && g_error_matches (error, MM_CORE_ERROR, MM_CORE_ERROR_RETRY)) {
			/* Try one more time */
			ctx->ip_type_tries++;
		} else {
			/* If the modem/provider lies and the IP type we tried isn't supported,
			 * retry with the next one, if any.
			 */
			ctx->ip_types_i++;
			ctx->ip_type_tries = 0;
		}
		connect_context_step (self);
345 346 347 348
		return;
	}

	/* Grab IP configurations */
349 350 351
	self->priv->ipv4_config = mm_bearer_get_ipv4_config (self->priv->bearer);
	if (self->priv->ipv4_config)
		ip4_method = get_bearer_ip_method (self->priv->ipv4_config);
352

353 354 355
	self->priv->ipv6_config = mm_bearer_get_ipv6_config (self->priv->bearer);
	if (self->priv->ipv6_config)
		ip6_method = get_bearer_ip_method (self->priv->ipv6_config);
356 357 358 359

	if (ip4_method == NM_MODEM_IP_METHOD_UNKNOWN &&
	    ip6_method == NM_MODEM_IP_METHOD_UNKNOWN) {
		nm_log_warn (LOGD_MB, "(%s): failed to connect modem: invalid bearer IP configuration",
360 361 362
		             nm_modem_get_uid (NM_MODEM (self)));
		g_signal_emit_by_name (self, NM_MODEM_PREPARE_RESULT, FALSE, NM_DEVICE_STATE_REASON_CONFIG_FAILED);
		connect_context_clear (self);
363
		return;
364 365
	}

366 367
	g_object_set (self,
	              NM_MODEM_DATA_PORT,  mm_bearer_get_interface (self->priv->bearer),
368 369
	              NM_MODEM_IP4_METHOD, ip4_method,
	              NM_MODEM_IP6_METHOD, ip6_method,
370
	              NM_MODEM_IP_TIMEOUT, mm_bearer_get_ip_timeout (self->priv->bearer),
371
	              NULL);
372

373 374
	ctx->step++;
	connect_context_step (self);
375 376 377
}

static void
378
send_pin_ready (MMSim *sim, GAsyncResult *result, NMModemBroadband *self)
379
{
380 381 382 383 384 385 386 387 388 389 390
    GError *error = NULL;

    if (!mm_sim_send_pin_finish (sim, result, &error)) {
		if (g_error_matches (error, MM_MOBILE_EQUIPMENT_ERROR, MM_MOBILE_EQUIPMENT_ERROR_SIM_PIN) ||
		    (g_error_matches (error, MM_CORE_ERROR, MM_CORE_ERROR_UNAUTHORIZED) &&
		     mm_modem_get_unlock_required (self->priv->modem_iface) == MM_MODEM_LOCK_SIM_PIN)) {
			ask_for_pin (self);
		} else {
			g_signal_emit_by_name (self, NM_MODEM_PREPARE_RESULT, FALSE, translate_mm_error (error));
		}
		g_error_free (error);
391
		return;
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
    }

	self->priv->ctx->step++;
	connect_context_step (self);
}

static void
connect_context_step (NMModemBroadband *self)
{
	ConnectContext *ctx = self->priv->ctx;

	switch (ctx->step) {
	case CONNECT_STEP_FIRST:
		ctx->step++;
		/* fall through */

	case CONNECT_STEP_WAIT_FOR_SIM:
		if (MODEM_CAPS_3GPP (ctx->caps) && !self->priv->sim_iface) {
			/* Have to wait for the SIM to show up */
			break;
		}
		ctx->step++;
		/* fall through */

	case CONNECT_STEP_UNLOCK:
		if (   MODEM_CAPS_3GPP (ctx->caps)
		    && mm_modem_get_unlock_required (self->priv->modem_iface) == MM_MODEM_LOCK_SIM_PIN) {
			NMSettingGsm *s_gsm = nm_connection_get_setting_gsm (ctx->connection);
			const char *pin = nm_setting_gsm_get_pin (s_gsm);

			/* If we have a PIN already, send it.  If we don't, get it. */
			if (pin) {
				mm_sim_send_pin (self->priv->sim_iface,
				                 pin,
				                 ctx->cancellable,
				                 (GAsyncReadyCallback) send_pin_ready,
				                 self);
			} else {
				ask_for_pin (self);
			}
			break;
		}
		ctx->step++;
		/* fall through */

	case CONNECT_STEP_WAIT_FOR_READY: {
		GError *error = NULL;

		if (mm_modem_get_state (self->priv->modem_iface) <= MM_MODEM_STATE_LOCKED)
			break;

		/* Create core connect properties based on the modem capabilities */
		g_assert (!ctx->connect_properties);

		if (MODEM_CAPS_3GPP (ctx->caps))
			ctx->connect_properties = create_gsm_connect_properties (ctx->connection);
		else if (MODEM_CAPS_3GPP2 (ctx->caps))
			ctx->connect_properties = create_cdma_connect_properties (ctx->connection);
		else {
			nm_log_warn (LOGD_MB, "(%s): Failed to connect '%s': not a mobile broadband modem",
			             nm_modem_get_uid (NM_MODEM (self)),
			             nm_connection_get_id (ctx->connection));

			g_signal_emit_by_name (self, NM_MODEM_PREPARE_RESULT, FALSE, NM_DEVICE_STATE_REASON_MODEM_INIT_FAILED);
			connect_context_clear (self);
			break;
		}
		g_assert (ctx->connect_properties);

		/* Build up list of IP types that we need to use in the retries */
		ctx->ip_types = nm_modem_get_connection_ip_type (NM_MODEM (self), ctx->connection, &error);
		if (!ctx->ip_types) {
			nm_log_warn (LOGD_MB, "(%s): Failed to connect '%s': %s",
			             nm_modem_get_uid (NM_MODEM (self)),
			             nm_connection_get_id (ctx->connection),
467
			             error->message);
468 469 470 471 472 473 474 475 476
			g_clear_error (&error);

			g_signal_emit_by_name (self, NM_MODEM_PREPARE_RESULT, FALSE, NM_DEVICE_STATE_REASON_MODEM_INIT_FAILED);
			connect_context_clear (self);
			break;
		}

		ctx->step++;
		/* fall through */
477 478
	}

479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
	case CONNECT_STEP_CONNECT:
		if (ctx->ip_types_i < ctx->ip_types->len) {
			NMModemIPType current;

			current = g_array_index (ctx->ip_types, NMModemIPType, ctx->ip_types_i);

			if (current == NM_MODEM_IP_TYPE_IPV4)
				mm_simple_connect_properties_set_ip_type (ctx->connect_properties, MM_BEARER_IP_FAMILY_IPV4);
			else if (current == NM_MODEM_IP_TYPE_IPV6)
				mm_simple_connect_properties_set_ip_type (ctx->connect_properties, MM_BEARER_IP_FAMILY_IPV6);
			else if (current == NM_MODEM_IP_TYPE_IPV4V6)
				mm_simple_connect_properties_set_ip_type (ctx->connect_properties, MM_BEARER_IP_FAMILY_IPV4V6);
			else
				g_assert_not_reached ();

494
			nm_log_dbg (LOGD_MB, "(%s): launching connection with ip type '%s' (try %d)",
495
			            nm_modem_get_uid (NM_MODEM (self)),
496 497
			            nm_modem_ip_type_to_string (current),
			            ctx->ip_type_tries + 1);
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

			mm_modem_simple_connect (self->priv->simple_iface,
			                         ctx->connect_properties,
			                         NULL,
			                         (GAsyncReadyCallback) connect_ready,
			                         self);
			break;
		}

		ctx->step++;
		/* fall through */

	case CONNECT_STEP_LAST:
		if (self->priv->ipv4_config || self->priv->ipv6_config) {
			g_signal_emit_by_name (self, NM_MODEM_PREPARE_RESULT, TRUE, NM_DEVICE_STATE_REASON_NONE);
		} else {
			/* If we have a saved error from a previous attempt, use it */
			if (!ctx->first_error)
				ctx->first_error = g_error_new_literal (NM_DEVICE_ERROR,
				                                        NM_DEVICE_ERROR_INVALID_CONNECTION,
				                                        "invalid bearer IP configuration");

			nm_log_warn (LOGD_MB, "(%s): failed to connect modem: %s",
					     nm_modem_get_uid (NM_MODEM (self)),
					     ctx->first_error->message);
			g_signal_emit_by_name (self, NM_MODEM_PREPARE_RESULT, FALSE, translate_mm_error (ctx->first_error));
		}

		connect_context_clear (self);
		break;
	}
529 530 531 532
}

static NMActStageReturn
act_stage1_prepare (NMModem *_self,
533
                    NMConnection *connection,
534 535 536 537
                    NMDeviceStateReason *reason)
{
	NMModemBroadband *self = NM_MODEM_BROADBAND (_self);

538 539 540 541 542 543 544 545 546 547 548
	/* Make sure we can get the Simple interface from the modem */
	if (!self->priv->simple_iface) {
		self->priv->simple_iface = mm_object_get_modem_simple (self->priv->modem_object);
		if (!self->priv->simple_iface) {
			nm_log_warn (LOGD_MB, "(%s) cannot access the Simple mobile broadband modem interface",
			             nm_modem_get_uid (NM_MODEM (self)));
			*reason = NM_DEVICE_STATE_REASON_MODEM_INIT_FAILED;
			return NM_ACT_STAGE_RETURN_FAILURE;
		}
	}

549
	connect_context_clear (self);
550

551 552 553 554 555
	/* Allocate new context for this connect stage attempt */
	self->priv->ctx = g_slice_new0 (ConnectContext);
	self->priv->ctx->caps = mm_modem_get_current_capabilities (self->priv->modem_iface);
	self->priv->ctx->cancellable = g_cancellable_new ();
	self->priv->ctx->connection = g_object_ref (connection);
556

557
	g_dbus_proxy_set_default_timeout (G_DBUS_PROXY (self->priv->simple_iface), MODEM_CONNECT_TIMEOUT_SECS * 1000);
558
	connect_context_step (self);
559 560 561 562 563 564 565

	return NM_ACT_STAGE_RETURN_POSTPONE;
}

/*****************************************************************************/

static gboolean
566
check_connection_compatible (NMModem *_self, NMConnection *connection)
567 568 569 570 571 572 573 574 575 576 577 578 579
{
	NMModemBroadband *self = NM_MODEM_BROADBAND (_self);
	MMModemCapability modem_caps;
	NMSettingConnection *s_con;

	modem_caps = mm_modem_get_current_capabilities (self->priv->modem_iface);
	s_con = nm_connection_get_setting_connection (connection);
	g_assert (s_con);

	if (MODEM_CAPS_3GPP (modem_caps)) {
		NMSettingGsm *s_gsm;

		if (!g_str_equal (nm_setting_connection_get_connection_type (s_con),
580
		                  NM_SETTING_GSM_SETTING_NAME))
581 582 583
			return FALSE;

		s_gsm = nm_connection_get_setting_gsm (connection);
584
		if (!s_gsm)
585 586 587 588 589 590 591 592 593
			return FALSE;

		return TRUE;
	}

	if (MODEM_CAPS_3GPP2 (modem_caps)) {
		NMSettingCdma *s_cdma;

		if (!g_str_equal (nm_setting_connection_get_connection_type (s_con),
594
		                  NM_SETTING_CDMA_SETTING_NAME))
595 596 597
			return FALSE;

		s_cdma = nm_connection_get_setting_cdma (connection);
598
		if (!s_cdma)
599 600 601 602 603
			return FALSE;

		return TRUE;
	}

604
	return FALSE;
605 606 607 608 609 610 611 612 613 614 615 616
}

/*****************************************************************************/

static gboolean
complete_connection (NMModem *_self,
                     NMConnection *connection,
                     const GSList *existing_connections,
                     GError **error)
{
	NMModemBroadband *self = NM_MODEM_BROADBAND (_self);
	MMModemCapability modem_caps;
617
	NMSettingPpp *s_ppp;
618 619 620 621 622 623

	modem_caps = mm_modem_get_current_capabilities (self->priv->modem_iface);

	/* PPP settings common to 3GPP and 3GPP2 */
	s_ppp = nm_connection_get_setting_ppp (connection);
	if (!s_ppp) {
624
		s_ppp = (NMSettingPpp *) nm_setting_ppp_new ();
625 626 627 628 629 630 631 632 633 634 635
		g_object_set (G_OBJECT (s_ppp),
		              NM_SETTING_PPP_LCP_ECHO_FAILURE, 5,
		              NM_SETTING_PPP_LCP_ECHO_INTERVAL, 30,
		              NULL);
		nm_connection_add_setting (connection, NM_SETTING (s_ppp));
	}

	if (MODEM_CAPS_3GPP (modem_caps)) {
		NMSettingGsm *s_gsm;

		s_gsm = nm_connection_get_setting_gsm (connection);
636 637
		if (!s_gsm) {
			/* Need a GSM setting at least */
638
			g_set_error_literal (error,
639 640 641 642
			                     NM_CONNECTION_ERROR,
			                     NM_CONNECTION_ERROR_MISSING_SETTING,
			                     _("GSM mobile broadband connection requires a 'gsm' setting"));
			g_prefix_error (error, "%s: ", NM_SETTING_GSM_SETTING_NAME);
643 644 645 646 647 648 649
			return FALSE;
		}

		/* TODO: This is not needed */
		if (!nm_setting_gsm_get_number (s_gsm))
			g_object_set (G_OBJECT (s_gsm), NM_SETTING_GSM_NUMBER, "*99#", NULL);

650 651
		nm_utils_complete_generic (NM_PLATFORM_GET,
		                           connection,
652 653 654
		                           NM_SETTING_GSM_SETTING_NAME,
		                           existing_connections,
		                           NULL,
655
		                           _("GSM connection"),
656
		                           NULL,
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
		                           FALSE); /* No IPv6 yet by default */

		return TRUE;
	}

	if (MODEM_CAPS_3GPP2 (modem_caps)) {
		NMSettingCdma *s_cdma;

		s_cdma = nm_connection_get_setting_cdma (connection);
		if (!s_cdma) {
			s_cdma = (NMSettingCdma *) nm_setting_cdma_new ();
			nm_connection_add_setting (connection, NM_SETTING (s_cdma));
		}

		if (!nm_setting_cdma_get_number (s_cdma))
			g_object_set (G_OBJECT (s_cdma), NM_SETTING_CDMA_NUMBER, "#777", NULL);

674 675
		nm_utils_complete_generic (NM_PLATFORM_GET,
		                           connection,
676 677 678
		                           NM_SETTING_CDMA_SETTING_NAME,
		                           existing_connections,
		                           NULL,
679
		                           _("CDMA connection"),
680
		                           NULL,
681 682 683 684 685
		                           FALSE); /* No IPv6 yet by default */

		return TRUE;
	}

686
	g_set_error (error,
687 688
	             NM_DEVICE_ERROR,
	             NM_DEVICE_ERROR_INCOMPATIBLE_CONNECTION,
689 690
	             "Device is not a mobile broadband modem");
	return FALSE;
691 692 693 694 695 696 697 698 699 700 701
}

/*****************************************************************************/

static gboolean
get_user_pass (NMModem *modem,
               NMConnection *connection,
               const char **user,
               const char **pass)
{
	NMSettingGsm *s_gsm;
702
	NMSettingCdma *s_cdma;
703 704

	s_gsm = nm_connection_get_setting_gsm (connection);
705 706
	s_cdma = nm_connection_get_setting_cdma (connection);
	if (!s_gsm && !s_cdma)
707 708
		return FALSE;

709 710 711 712 713 714 715 716 717 718 719 720
	if (user) {
		if (s_gsm)
			*user = nm_setting_gsm_get_username (s_gsm);
		else if (s_cdma)
			*user = nm_setting_cdma_get_username (s_cdma);
	}
	if (pass) {
		if (s_gsm)
			*pass = nm_setting_gsm_get_password (s_gsm);
		else if (s_cdma)
			*pass = nm_setting_cdma_get_password (s_cdma);
	}
721 722 723 724 725 726 727

	return TRUE;
}

/*****************************************************************************/
/* Query/Update enabled state */

728 729 730 731 732 733 734 735 736
static void
set_power_state_low_ready (MMModem *modem,
                           GAsyncResult *result,
                           NMModemBroadband *self)
{
	GError *error = NULL;

	if (!mm_modem_set_power_state_finish (modem, result, &error)) {
		/* Log but ignore errors; not all modems support low power state */
737
		nm_log_dbg (LOGD_MB, "(%s): failed to set modem low power state: %s",
738
		            nm_modem_get_uid (NM_MODEM (self)),
739
		            NM_G_ERROR_MSG (error));
740 741 742 743 744 745 746
		g_clear_error (&error);
	}

	/* Balance refcount */
	g_object_unref (self);
}

747 748 749 750 751 752 753
static void
modem_disable_ready (MMModem *modem_iface,
                     GAsyncResult *res,
                     NMModemBroadband *self)
{
	GError *error = NULL;

754 755 756 757 758 759 760 761
	if (mm_modem_disable_finish (modem_iface, res, &error)) {
		/* Once disabled, move to low-power mode */
		mm_modem_set_power_state (modem_iface,
		                          MM_MODEM_POWER_STATE_LOW,
		                          NULL,
		                          (GAsyncReadyCallback) set_power_state_low_ready,
		                          g_object_ref (self));
	} else {
762
		nm_log_warn (LOGD_MB, "(%s): failed to disable modem: %s",
763
		             nm_modem_get_uid (NM_MODEM (self)),
764
		             NM_G_ERROR_MSG (error));
765
		nm_modem_set_prev_state (NM_MODEM (self), "disable failed");
766
		g_clear_error (&error);
767
	}
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782

	/* Balance refcount */
	g_object_unref (self);
}

static void
modem_enable_ready (MMModem *modem_iface,
                    GAsyncResult *res,
                    NMModemBroadband *self)
{
	GError *error = NULL;

	if (!mm_modem_enable_finish (modem_iface, res, &error)) {
		nm_log_warn (LOGD_MB, "(%s) failed to enable modem: %s",
		             nm_modem_get_uid (NM_MODEM (self)),
783
		             NM_G_ERROR_MSG (error));
784
		nm_modem_set_prev_state (NM_MODEM (self), "enable failed");
785
		g_clear_error (&error);
786
	}
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811

	/* Balance refcount */
	g_object_unref (self);
}

static void
set_mm_enabled (NMModem *_self,
                gboolean enabled)
{
	NMModemBroadband *self = NM_MODEM_BROADBAND (_self);

	if (enabled) {
		mm_modem_enable (self->priv->modem_iface,
		                 NULL, /* cancellable */
		                 (GAsyncReadyCallback)modem_enable_ready,
		                 g_object_ref (self));
	} else {
		mm_modem_disable (self->priv->modem_iface,
		                  NULL, /* cancellable */
		                  (GAsyncReadyCallback)modem_disable_ready,
		                  g_object_ref (self));
	}
}

/*****************************************************************************/
812
/* IPv4 method static */
813 814

static gboolean
815
ip4_string_to_num (const gchar *str, guint32 *out)
816
{
817 818
	guint32 addr = 0;
	gboolean success = FALSE;
819

820 821 822 823
	if (!str || inet_pton (AF_INET, str, &addr) != 1)
		addr = 0;
	else
		success = TRUE;
824

825
	*out = (guint32)addr;
826
	return success;
827 828 829
}

static gboolean
830
static_stage3_ip4_done (NMModemBroadband *self)
831 832 833
{
	GError *error = NULL;
	NMIP4Config *config = NULL;
834
	const char *data_port;
835
	const gchar *address_string;
836
	const gchar *gw_string;
837
	guint32 address_network;
838
	guint32 gw;
839
	NMPlatformIP4Address address;
840 841 842 843
	const gchar **dns;
	guint i;

	g_assert (self->priv->ipv4_config);
844
	g_assert (self->priv->bearer);
845 846 847 848 849 850

	nm_log_info (LOGD_MB, "(%s): IPv4 static configuration:",
	             nm_modem_get_uid (NM_MODEM (self)));

	/* Fully fail if invalid IP address retrieved */
	address_string = mm_bearer_ip_config_get_address (self->priv->ipv4_config);
851
	if (!ip4_string_to_num (address_string, &address_network)) {
852 853
		error = g_error_new (NM_DEVICE_ERROR,
		                     NM_DEVICE_ERROR_INVALID_CONNECTION,
854 855 856 857 858 859
		                     "(%s) retrieving IP4 configuration failed: invalid address given '%s'",
		                     nm_modem_get_uid (NM_MODEM (self)),
		                     address_string);
		goto out;
	}

860 861
	/* Missing gateway not a hard failure */
	gw_string = mm_bearer_ip_config_get_gateway (self->priv->ipv4_config);
862
	ip4_string_to_num (gw_string, &gw);
863

864 865
	data_port = mm_bearer_get_interface (self->priv->bearer);
	g_assert (data_port);
866
	config = nm_ip4_config_new (nm_platform_link_get_ifindex (NM_PLATFORM_GET, data_port));
867 868 869

	memset (&address, 0, sizeof (address));
	address.address = address_network;
870
	address.peer_address = address_network;
871
	address.plen = mm_bearer_ip_config_get_prefix (self->priv->ipv4_config);
872
	address.source = NM_IP_CONFIG_SOURCE_WWAN;
873 874
	if (address.plen <= 32)
		nm_ip4_config_add_address (config, &address);
875

876 877 878 879 880 881
	nm_log_info (LOGD_MB, "  address %s/%d", address_string, address.plen);

	if (gw) {
		nm_ip4_config_set_gateway (config, gw);
		nm_log_info (LOGD_MB, "  gateway %s", gw_string);
	}
882 883 884

	/* DNS servers */
	dns = mm_bearer_ip_config_get_dns (self->priv->ipv4_config);
885
	for (i = 0; dns && dns[i]; i++) {
886
		if (   ip4_string_to_num (dns[i], &address_network)
887 888 889 890 891 892 893
		    && address_network > 0) {
			nm_ip4_config_add_nameserver (config, address_network);
			nm_log_info (LOGD_MB, "  DNS %s", dns[i]);
		}
	}

out:
894
	g_signal_emit_by_name (self, NM_MODEM_IP4_CONFIG_RESULT, config, error);
895 896 897 898 899 900 901 902 903 904 905 906 907
	g_clear_error (&error);
	return FALSE;
}

static NMActStageReturn
static_stage3_ip4_config_start (NMModem *_self,
                                NMActRequest *req,
                                NMDeviceStateReason *reason)
{
	NMModemBroadband *self = NM_MODEM_BROADBAND (_self);

	/* We schedule it in an idle just to follow the same logic as in the
	 * generic modem implementation. */
908 909 910 911 912 913 914 915 916 917 918 919 920
	g_idle_add ((GSourceFunc) static_stage3_ip4_done, self);

	return NM_ACT_STAGE_RETURN_POSTPONE;
}

/*****************************************************************************/
/* IPv6 method static */

static gboolean
stage3_ip6_done (NMModemBroadband *self)
{
	GError *error = NULL;
	NMIP6Config *config = NULL;
921
	const char *data_port;
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
	const gchar *address_string;
	NMPlatformIP6Address address;
	NMModemIPMethod ip_method;
	const gchar **dns;
	guint i;

	g_assert (self->priv->ipv6_config);

	memset (&address, 0, sizeof (address));

	ip_method = get_bearer_ip_method (self->priv->ipv6_config);

	address_string = mm_bearer_ip_config_get_address (self->priv->ipv6_config);
	if (!address_string) {
		/* DHCP/SLAAC is allowed to skip addresses; other methods require it */
		if (ip_method != NM_MODEM_IP_METHOD_AUTO) {
938
			error = g_error_new (NM_DEVICE_ERROR,
939 940 941
			                     NM_DEVICE_ERROR_INVALID_CONNECTION,
			                     "(%s) retrieving IPv6 configuration failed: no address given",
			                     nm_modem_get_uid (NM_MODEM (self)));
942 943 944 945 946 947
		}
		goto out;
	}

	/* Fail if invalid IP address retrieved */
	if (!inet_pton (AF_INET6, address_string, (void *) &(address.address))) {
948 949
		error = g_error_new (NM_DEVICE_ERROR,
		                     NM_DEVICE_ERROR_INVALID_CONNECTION,
950 951 952 953 954 955 956 957 958
		                     "(%s) retrieving IPv6 configuration failed: invalid address given '%s'",
		                     nm_modem_get_uid (NM_MODEM (self)),
		                     address_string);
		goto out;
	}

	nm_log_info (LOGD_MB, "(%s): IPv6 base configuration:",
	             nm_modem_get_uid (NM_MODEM (self)));

959 960
	data_port = mm_bearer_get_interface (self->priv->bearer);
	g_assert (data_port);
961
	config = nm_ip6_config_new (nm_platform_link_get_ifindex (NM_PLATFORM_GET, data_port));
962 963

	address.plen = mm_bearer_ip_config_get_prefix (self->priv->ipv6_config);
964 965
	if (address.plen <= 128)
		nm_ip6_config_add_address (config, &address);
966 967 968 969 970 971

	nm_log_info (LOGD_MB, "  address %s/%d", address_string, address.plen);

	address_string = mm_bearer_ip_config_get_gateway (self->priv->ipv6_config);
	if (address_string) {
		if (!inet_pton (AF_INET6, address_string, (void *) &(address.address))) {
972
			error = g_error_new (NM_DEVICE_ERROR,
973 974 975 976
			                     NM_DEVICE_ERROR_INVALID_CONNECTION,
			                     "(%s) retrieving IPv6 configuration failed: invalid gateway given '%s'",
			                     nm_modem_get_uid (NM_MODEM (self)),
			                     address_string);
977 978 979 980 981 982
			goto out;
		}
		nm_log_info (LOGD_MB, "  gateway %s", address_string);
		nm_ip6_config_set_gateway (config, &address.address);
	} else if (ip_method == NM_MODEM_IP_METHOD_STATIC) {
		/* Gateway required for the 'static' method */
983 984
		error = g_error_new (NM_DEVICE_ERROR,
		                     NM_DEVICE_ERROR_INVALID_CONNECTION,
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
		                     "(%s) retrieving IPv6 configuration failed: missing gateway",
		                     nm_modem_get_uid (NM_MODEM (self)));
		goto out;
	}

	/* DNS servers */
	dns = mm_bearer_ip_config_get_dns (self->priv->ipv6_config);
	for (i = 0; dns[i]; i++) {
		struct in6_addr addr;

		if (inet_pton (AF_INET6, dns[i], &addr)) {
			nm_ip6_config_add_nameserver (config, &addr);
			nm_log_info (LOGD_MB, "  DNS %s", dns[i]);
		}
	}

out:
	nm_modem_emit_ip6_config_result (NM_MODEM (self), config, error);
	g_clear_object (&config);
	g_clear_error (&error);
	return FALSE;
}

static NMActStageReturn
stage3_ip6_config_request (NMModem *_self, NMDeviceStateReason *reason)
{
	NMModemBroadband *self = NM_MODEM_BROADBAND (_self);

	/* We schedule it in an idle just to follow the same logic as in the
	 * generic modem implementation. */
	g_idle_add ((GSourceFunc) stage3_ip6_done, self);
1016 1017 1018 1019 1020 1021 1022 1023 1024

	return NM_ACT_STAGE_RETURN_POSTPONE;
}

/*****************************************************************************/
/* Disconnect */

typedef struct {
	NMModemBroadband *self;
1025 1026
	GSimpleAsyncResult *result;
	GCancellable *cancellable;
1027
	gboolean warn;
1028
} DisconnectContext;
1029 1030

static void
1031
disconnect_context_complete (DisconnectContext *ctx)
1032
{
1033 1034 1035 1036
	g_simple_async_result_complete_in_idle (ctx->result);
	if (ctx->cancellable)
		g_object_unref (ctx->cancellable);
	g_object_unref (ctx->result);
1037
	g_object_unref (ctx->self);
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
	g_slice_free (DisconnectContext, ctx);
}

static gboolean
disconnect_context_complete_if_cancelled (DisconnectContext *ctx)
{
	GError *error = NULL;

	if (g_cancellable_set_error_if_cancelled (ctx->cancellable, &error)) {
		g_simple_async_result_take_error (ctx->result, error);
		disconnect_context_complete (ctx);
		return TRUE;
	}
	return FALSE;
}

static gboolean
disconnect_finish (NMModem *self,
                   GAsyncResult *res,
                   GError **error)
{
	return !g_simple_async_result_propagate_error (G_SIMPLE_ASYNC_RESULT (res), error);
1060 1061 1062 1063 1064
}

static void
simple_disconnect_ready (MMModemSimple *modem_iface,
                         GAsyncResult *res,
1065
                         DisconnectContext *ctx)
1066 1067 1068 1069
{
	GError *error = NULL;

	if (!mm_modem_simple_disconnect_finish (modem_iface, res, &error)) {
1070
		if (ctx->warn && !g_error_matches (error, G_DBUS_ERROR, G_DBUS_ERROR_SERVICE_UNKNOWN)) {
1071 1072
			nm_log_warn (LOGD_MB, "(%s) failed to disconnect modem: %s",
			             nm_modem_get_uid (NM_MODEM (ctx->self)),
1073
			             error->message);
1074
		}
1075
		g_simple_async_result_take_error (ctx->result, error);
1076 1077
	}

1078
	disconnect_context_complete (ctx);
1079 1080 1081
}

static void
1082 1083 1084 1085 1086
disconnect (NMModem *self,
            gboolean warn,
            GCancellable *cancellable,
            GAsyncReadyCallback callback,
            gpointer user_data)
1087
{
1088
	DisconnectContext *ctx;
1089

1090
	ctx = g_slice_new (DisconnectContext);
1091
	ctx->self = g_object_ref (self);
1092 1093 1094 1095
	ctx->result = g_simple_async_result_new (G_OBJECT (self),
	                                         callback,
	                                         user_data,
	                                         disconnect);
1096 1097 1098
	/* Don't bother warning on FAILED since the modem is already gone */
	ctx->warn = warn;

1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
	/* Setup cancellable */
	ctx->cancellable = cancellable ? g_object_ref (cancellable) : NULL;
	if (disconnect_context_complete_if_cancelled (ctx))
		return;

	/* If no simple iface, we're done */
	if (!ctx->self->priv->simple_iface) {
		disconnect_context_complete (ctx);
		return;
	}

1110 1111
	nm_log_dbg (LOGD_MB, "(%s): notifying ModemManager about the modem disconnection",
	            nm_modem_get_uid (NM_MODEM (ctx->self)));
1112 1113 1114
	mm_modem_simple_disconnect (
		ctx->self->priv->simple_iface,
		NULL, /* bearer path; if NULL given ALL get disconnected */
1115
		cancellable,
1116 1117 1118 1119 1120 1121 1122
		(GAsyncReadyCallback)simple_disconnect_ready,
		ctx);
}

/*****************************************************************************/

static void
1123
deactivate_cleanup (NMModem *_self, NMDevice *device)
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
{
	NMModemBroadband *self = NM_MODEM_BROADBAND (_self);

	/* TODO: cancel SimpleConnect() if any */

	/* Cleanup IPv4 addresses and routes */
	g_clear_object (&self->priv->ipv4_config);
	g_clear_object (&self->priv->ipv6_config);
	g_clear_object (&self->priv->bearer);

	self->priv->pin_tries = 0;

	/* Chain up parent's */
1137
	NM_MODEM_CLASS (nm_modem_broadband_parent_class)->deactivate_cleanup (_self, device);
1138 1139 1140 1141
}

/*****************************************************************************/

1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
#define MAP_STATE(name) case MM_MODEM_STATE_##name: return NM_MODEM_STATE_##name;

static NMModemState
mm_state_to_nm (MMModemState mm_state)
{
	switch (mm_state) {
	MAP_STATE(UNKNOWN)
	MAP_STATE(FAILED)
	MAP_STATE(INITIALIZING)
	MAP_STATE(LOCKED)
	MAP_STATE(DISABLED)
	MAP_STATE(DISABLING)
	MAP_STATE(ENABLING)
	MAP_STATE(ENABLED)
	MAP_STATE(SEARCHING)
	MAP_STATE(REGISTERED)
	MAP_STATE(DISCONNECTING)
	MAP_STATE(CONNECTING)
	MAP_STATE(CONNECTED)
	}
	return NM_MODEM_STATE_UNKNOWN;
}

1165 1166 1167 1168 1169 1170 1171
static void
modem_state_changed (MMModem *modem,
                     MMModemState old_state,
                     MMModemState new_state,
                     MMModemStateChangeReason reason,
                     NMModemBroadband *self)
{
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
	/* After the SIM is unlocked MM1 will move the device to INITIALIZING which
	 * is an unavailable state.  That makes state handling confusing here, so
	 * suppress this state change and let the modem move from LOCKED to DISABLED.
	 */
	if (new_state == MM_MODEM_STATE_INITIALIZING && old_state == MM_MODEM_STATE_LOCKED)
		return;

	nm_modem_set_state (NM_MODEM (self),
	                    mm_state_to_nm (new_state),
	                    mm_modem_state_change_reason_get_string (reason));
1182 1183 1184

	if (self->priv->ctx && self->priv->ctx->step == CONNECT_STEP_WAIT_FOR_READY)
		connect_context_step (self);
1185 1186 1187 1188
}

/*****************************************************************************/

1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
static NMModemIPType
mm_ip_family_to_nm (MMBearerIpFamily family)
{
	NMModemIPType nm_type = NM_MODEM_IP_TYPE_UNKNOWN;

	if (family & MM_BEARER_IP_FAMILY_IPV4)
		nm_type |= NM_MODEM_IP_TYPE_IPV4;
	if (family & MM_BEARER_IP_FAMILY_IPV6)
		nm_type |= NM_MODEM_IP_TYPE_IPV6;
	if (family & MM_BEARER_IP_FAMILY_IPV4V6)
		nm_type |= MM_BEARER_IP_FAMILY_IPV4V6;

	return nm_type;
}

1204
NMModem *
1205
nm_modem_broadband_new (GObject *object, GError **error)
1206
{
1207
	NMModem *modem;
1208 1209
	MMObject *modem_object;
	MMModem *modem_iface;
1210
	gchar *drivers;
1211 1212 1213 1214

	g_return_val_if_fail (MM_IS_OBJECT (object), NULL);
	modem_object = MM_OBJECT (object);

1215
	/* Ensure we have the 'Modem' interface and the primary port at least */
1216 1217
	modem_iface = mm_object_peek_modem (modem_object);
	g_return_val_if_fail (!!modem_iface, NULL);
1218
	g_return_val_if_fail (!!mm_modem_get_primary_port (modem_iface), NULL);
1219

1220 1221 1222 1223 1224 1225 1226 1227
	/* Build a single string with all drivers listed */
	drivers = g_strjoinv (", ", (gchar **)mm_modem_get_drivers (modem_iface));

	modem = g_object_new (NM_TYPE_MODEM_BROADBAND,
	                      NM_MODEM_PATH, mm_object_get_path (modem_object),
	                      NM_MODEM_UID, mm_modem_get_primary_port (modem_iface),
	                      NM_MODEM_CONTROL_PORT, mm_modem_get_primary_port (modem_iface),
	                      NM_MODEM_DATA_PORT, NULL, /* We don't know it until bearer created */
1228
	                      NM_MODEM_IP_TYPES, mm_ip_family_to_nm (mm_modem_get_supported_ip_families (modem_iface)),
1229
	                      NM_MODEM_STATE, mm_state_to_nm (mm_modem_get_state (modem_iface)),
1230
	                      NM_MODEM_DEVICE_ID, mm_modem_get_device_identifier (modem_iface),
1231 1232 1233 1234 1235
	                      NM_MODEM_BROADBAND_MODEM, modem_object,
	                      NM_MODEM_DRIVER, drivers,
	                      NULL);
	g_free (drivers);
	return modem;
1236 1237
}

1238 1239 1240 1241 1242 1243 1244 1245
static void
get_sim_ready (MMModem *modem,
               GAsyncResult *res,
               NMModemBroadband *self)
{
	GError *error = NULL;
	MMSim *new_sim;

1246

1247
	new_sim = mm_modem_get_sim_finish (modem, res, &error);
1248 1249 1250 1251 1252 1253 1254
	if (new_sim != self->priv->sim_iface) {
		g_clear_object (&self->priv->sim_iface);
		self->priv->sim_iface = new_sim;
	} else
		g_clear_object (&new_sim);

	if (self->priv->sim_iface) {
1255
		g_object_set (G_OBJECT (self),
1256 1257
		              NM_MODEM_SIM_ID, mm_sim_get_identifier (self->priv->sim_iface),
		              NM_MODEM_SIM_OPERATOR_ID, mm_sim_get_operator_identifier (self->priv->sim_iface),
1258
		              NULL);
1259 1260 1261 1262

		/* If we're waiting for the SIM during a connect, proceed with the connect */
		if (self->priv->ctx && self->priv->ctx->step == CONNECT_STEP_WAIT_FOR_SIM)
			connect_context_step (self);
1263
	} else {
1264
		nm_log_warn (LOGD_MB, "(%s): failed to retrieve SIM object: %s",
1265
		             nm_modem_get_uid (NM_MODEM (self)),
1266
		             NM_G_ERROR_MSG (error));
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
	}
	g_clear_error (&error);
	g_object_unref (self);
}

static void
sim_changed (MMModem *modem, GParamSpec *pspec, gpointer user_data)
{
	NMModemBroadband *self = NM_MODEM_BROADBAND (user_data);

	g_return_if_fail (modem == self->priv->modem_iface);

	if (mm_modem_get_sim_path (self->priv->modem_iface)) {
		mm_modem_get_sim (self->priv->modem_iface,
		                  NULL,  /* cancellable */
		                  (GAsyncReadyCallback) get_sim_ready,
		                  g_object_ref (self));
	} else
1285 1286 1287 1288
		g_object_set (G_OBJECT (self),
		              NM_MODEM_SIM_ID, NULL,
		              NM_MODEM_SIM_OPERATOR_ID, NULL,
		              NULL);
1289 1290
}

1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
static void
supported_ip_families_changed (MMModem *modem, GParamSpec *pspec, gpointer user_data)
{
	NMModemBroadband *self = NM_MODEM_BROADBAND (user_data);

	g_return_if_fail (modem == self->priv->modem_iface);

	g_object_set (G_OBJECT (self),
	              NM_MODEM_IP_TYPES,
	              mm_ip_family_to_nm (mm_modem_get_supported_ip_families (modem)),
	              NULL);
}

1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
static void
nm_modem_broadband_init (NMModemBroadband *self)
{
	self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self,
	                                          NM_TYPE_MODEM_BROADBAND,
	                                          NMModemBroadbandPrivate);
}

static void
set_property (GObject *object,
              guint prop_id,
1315
              const GValue *value,
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
              GParamSpec *pspec)
{
	NMModemBroadband *self = NM_MODEM_BROADBAND (object);

	switch (prop_id) {
	case PROP_MODEM:
		/* construct-only */
		self->priv->modem_object = g_value_dup_object (value);
		self->priv->modem_iface = mm_object_get_modem (self->priv->modem_object);
		g_assert (self->priv->modem_iface != NULL);
		g_signal_connect (self->priv->modem_iface,
1327 1328 1329 1330 1331 1332 1333 1334
		                  "state-changed",
		                  G_CALLBACK (modem_state_changed),
		                  self);
		g_signal_connect (self->priv->modem_iface,
		                  "notify::sim",
		                  G_CALLBACK (sim_changed),
		                  self);
		sim_changed (self->priv->modem_iface, NULL, self);
1335 1336 1337 1338
		g_signal_connect (self->priv->modem_iface,
		                  "notify::supported-ip-families",
		                  G_CALLBACK (supported_ip_families_changed),
		                  self);
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351

		/* Note: don't grab the Simple iface here; the Modem interface is the
		 * only one assumed to be always valid and available */
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
		break;
	}
}

static void
get_property (GObject *object,
              guint prop_id,
1352
              GValue *value,
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
              GParamSpec *pspec)
{
	NMModemBroadband *self = NM_MODEM_BROADBAND (object);

	switch (prop_id) {
	case PROP_MODEM:
		g_value_set_object (value, self->priv->modem_object);
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
		break;
	}
}

static void
dispose (GObject *object)
{
	NMModemBroadband *self = NM_MODEM_BROADBAND (object);

1372
	connect_context_clear (self);
1373 1374 1375 1376 1377
	g_clear_object (&self->priv->ipv4_config);
	g_clear_object (&self->priv->ipv6_config);
	g_clear_object (&self->priv->bearer);
	g_clear_object (&self->priv->modem_iface);
	g_clear_object (&self->priv->simple_iface);
1378
	g_clear_object (&self->priv->sim_iface);
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
	g_clear_object (&self->priv->modem_object);

	G_OBJECT_CLASS (nm_modem_broadband_parent_class)->dispose (object);
}

static void
nm_modem_broadband_class_init (NMModemBroadbandClass *klass)
{
	GObjectClass *object_class = G_OBJECT_CLASS (klass);
	NMModemClass *modem_class = NM_MODEM_CLASS (klass);

	g_type_class_add_private (object_class, sizeof (NMModemBroadbandPrivate));

	/* Virtual methods */
	object_class->dispose = dispose;
	object_class->get_property = get_property;
	object_class->set_property = set_property;

1397
	modem_class->get_capabilities = get_capabilities;
1398
	modem_class->static_stage3_ip4_config_start = static_stage3_ip4_config_start;
1399
	modem_class->stage3_ip6_config_request = stage3_ip6_config_request;
1400
	modem_class->disconnect = disconnect;
1401
	modem_class->disconnect_finish = disconnect_finish;
1402
	modem_class->deactivate_cleanup = deactivate_cleanup;
1403 1404 1405 1406 1407
	modem_class->set_mm_enabled = set_mm_enabled;
	modem_class->get_user_pass = get_user_pass;
	modem_class->check_connection_compatible = check_connection_compatible;
	modem_class->complete_connection = complete_connection;
	modem_class->act_stage1_prepare = act_stage1_prepare;
1408
	modem_class->owns_port = owns_port;
1409 1410 1411 1412

	/* Properties */
	g_object_class_install_property
		(object_class, PROP_MODEM,
1413
		 g_param_spec_object (NM_MODEM_BROADBAND_MODEM, "", "",
1414
		                      MM_GDBUS_TYPE_OBJECT,
1415 1416
		                      G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
		                      G_PARAM_STATIC_STRINGS));
1417
}