summaryrefslogtreecommitdiffstats
path: root/probe-modem/probe-modem.c
blob: 8ffe964ef3a6c0c61ce6b5b98f479b9164c831d6 (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
/*
 * modem_caps - probe Hayes-compatible modem capabilities
 *
 * Copyright (C) 2008 Dan Williams <dcbw@redhat.com>
 *
 *	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 version 2 of the License.
 */

#ifndef _GNU_SOURCE
#define _GNU_SOURCE 1
#endif

#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <getopt.h>

#include <glib.h>

#include "../../udev.h"

#define MODEM_CAP_GSM         0x0001 /* GSM */
#define MODEM_CAP_IS707_A     0x0002 /* CDMA Circuit Switched Data */
#define MODEM_CAP_IS707_P     0x0004 /* CDMA Packet Switched Data */
#define MODEM_CAP_DS          0x0008 /* Data compression selection (v.42bis) */
#define MODEM_CAP_ES          0x0010 /* Error control selection (v.42) */
#define MODEM_CAP_FCLASS      0x0020 /* Group III Fax */
#define MODEM_CAP_MS          0x0040 /* Modulation selection */
#define MODEM_CAP_W           0x0080 /* Wireless commands */      
#define MODEM_CAP_IS856       0x0100 /* CDMA 3G EVDO rev 0 */
#define MODEM_CAP_IS856_A     0x0200 /* CDMA 3G EVDO rev A */

static gboolean verbose = FALSE;

struct modem_caps {
	char *name;
	guint32 bits;
};

static struct modem_caps modem_caps[] = {
	{"+CGSM",     MODEM_CAP_GSM},
	{"+CIS707-A", MODEM_CAP_IS707_A},
	{"+CIS707",   MODEM_CAP_IS707_A},
	{"+CIS707P",  MODEM_CAP_IS707_P},
	{"CIS-856",   MODEM_CAP_IS856},
	{"CIS-856-A", MODEM_CAP_IS856_A},
	{"+DS",       MODEM_CAP_DS},
	{"+ES",       MODEM_CAP_ES},
	{"+MS",       MODEM_CAP_MS},
	{"+FCLASS",   MODEM_CAP_FCLASS},
	{NULL}
};

#define debug(fmt, args...) \
if (verbose) { \
	g_printerr ("%s(): " fmt "\n", G_STRFUNC, ##args); \
}

static gboolean
modem_send_command (int fd, const char *cmd)
{
	int eagain_count = 1000;
	guint32 i;
	ssize_t written;

	debug ("Sending: '%s'", cmd);

	for (i = 0; i < strlen (cmd) && eagain_count > 0;) {
		written = write (fd, cmd + i, 1);

		if (written > 0)
			i += written;
		else {
			/* Treat written == 0 as EAGAIN to ensure we break out of the
			 * for() loop eventually.
			 */
			if ((written < 0) && (errno != EAGAIN)) {
				g_printerr ("error writing command: %d\n", errno);
				return FALSE;
			}
			eagain_count--;
			g_usleep (G_USEC_PER_SEC / 10000);
		}
	}

	return eagain_count <= 0 ? FALSE : TRUE;
}

static int
find_terminator (const char *line, const char **terminators)
{
	int i;

	for (i = 0; terminators[i]; i++) {
		if (!strncasecmp (line, terminators[i], strlen (terminators[i])))
			return i;
	}
	return -1;
}

static const char *
find_response (const char *line, const char **responses, int *idx)
{
	int i;

	/* Don't look for a result again if we got one previously */
	for (i = 0; responses[i]; i++) {
		if (strstr (line, responses[i])) {
			*idx = i;
			return line;
		}
	}
	return NULL;
}

#define RESPONSE_LINE_MAX 128
#define SERIAL_BUF_SIZE 2048

static int
modem_wait_reply (int fd,
                  guint32 timeout_secs,
                  const char **needles,
                  const char **terminators,
                  int *out_terminator,
                  char **out_response)
{
	char buf[SERIAL_BUF_SIZE + 1];
	int reply_index = -1, bytes_read;
	GString *result = g_string_sized_new (RESPONSE_LINE_MAX * 2);
	time_t end;
	const char *response = NULL;
	gboolean done = FALSE;

	*out_terminator = -1;
	end = time (NULL) + timeout_secs;
	do {
		bytes_read = read (fd, buf, SERIAL_BUF_SIZE);
		if (bytes_read < 0 && errno != EAGAIN) {
			g_string_free (result, TRUE);
			g_printerr ("read error: %d\n", errno);
			return -1;
		}

		if (bytes_read == 0)
			break; /* EOF */
		else if (bytes_read > 0) {
			char **lines, **iter, *tmp;

			buf[bytes_read] = 0;
			g_string_append (result, buf);

			debug ("Got: '%s'", result->str);

			lines = g_strsplit_set (result->str, "\n\r", 0);

			/* Find response terminators */
			for (iter = lines; *iter && !done; iter++) {
				tmp = g_strstrip (*iter);
				if (tmp && strlen (tmp)) {
					*out_terminator = find_terminator (tmp, terminators);
					if (*out_terminator >= 0)
						done = TRUE;
				}
			}

			/* If the terminator is found, look for expected responses */
			if (done) {
				for (iter = lines; *iter && (reply_index < 0); iter++) {
					tmp = g_strstrip (*iter);
					if (tmp && strlen (tmp)) {
						response = find_response (tmp, needles, &reply_index);
						if (response) {
							g_free (*out_response);
							*out_response = g_strdup (response);
						}
					}
				}
			}
			g_strfreev (lines);
		}

		if (!done)
			g_usleep (1000);
	} while (!done && (time (NULL) < end) && (result->len <= SERIAL_BUF_SIZE));

	g_string_free (result, TRUE);
	return reply_index;
}

#define GCAP_TAG "+GCAP:"
#define GMM_TAG "+GMM:"

static int
parse_gcap (const char *buf)
{
	const char *p = buf + strlen (GCAP_TAG);
	char **caps, **iter;
	int ret = 0;

	caps = g_strsplit_set (p, " ,\t", 0);
	if (!caps)
		return -1;

	for (iter = caps; *iter; iter++) {
		struct modem_caps *cap = modem_caps;

		while (cap->name) {
			if (!strcmp(cap->name, *iter)) {
				ret |= cap->bits;
				break;
			}
			cap++;
		}
	}

	g_strfreev (caps);
	return ret;
}

static int
parse_gmm (const char *buf)
{
	const char *p = buf + strlen (GMM_TAG);
	char **gmm, **iter;
	gboolean gsm = FALSE;

	gmm = g_strsplit_set (p, " ,\t", 0);
	if (!gmm)
		return -1;

	/* BUSlink SCWi275u USB GPRS modem */
	for (iter = gmm; *iter && !gsm; iter++) {
		if (strstr (*iter, "GSM900") || strstr (*iter, "GSM1800") ||
		    strstr (*iter, "GSM1900") || strstr (*iter, "GSM850"))
			gsm = TRUE;
	}

	g_strfreev (gmm);
	return gsm ? MODEM_CAP_GSM : 0;
}

static int modem_probe_caps(int fd)
{
	const char *gcap_responses[] = { GCAP_TAG, NULL };
	const char *terminators[] = { "OK", "ERROR", "ERR", NULL };
	char *reply = NULL;
	int idx, term_idx, ret = -1;

	if (!modem_send_command (fd, "AT+GCAP\r\n"))
		return -1;

	idx = modem_wait_reply (fd, 3, gcap_responses, terminators, &term_idx, &reply);
	if (0 == term_idx && 0 == idx) {
		/* Success */
		debug ("GCAP response: %s", reply);
		ret = parse_gcap (reply);
	} else if (1 == term_idx || 2 == term_idx) {
		const char *ati_responses[] = { GCAP_TAG, NULL };

		/* Many cards (ex Sierra 860 & 875) won't accept AT+GCAP but
		 * accept ATI when the SIM is missing.  Often the GCAP info is
		 * in the ATI response too.
		 */
		g_free (reply);
		reply = NULL;

		if (modem_send_command (fd, "ATI\r\n")) {
			idx = modem_wait_reply (fd, 3, ati_responses, terminators, &term_idx, &reply);
			if (0 == term_idx && 0 == idx) {
				debug ("ATI response: %s", reply);
				ret = parse_gcap (reply);
			}
		}
	}
	g_free (reply);
	reply = NULL;

	/* Try an alternate method on some hardware (ex BUSlink SCWi275u) */
	if (!(ret & MODEM_CAP_GSM) && !(ret & MODEM_CAP_IS707_A)) {
		const char *gmm_responses[] = { GMM_TAG, NULL };

		if (modem_send_command (fd, "AT+GMM\r\n")) {
			idx = modem_wait_reply (fd, 5, gmm_responses, terminators, &term_idx, &reply);
			if (0 == term_idx && 0 == idx) {
				debug ("GMM response: %s", reply);
				ret |= parse_gmm (reply);
			}
			g_free (reply);
		}
	}

	return ret;
}

void
print_usage (void)
{
	printf("Usage: modem_caps [options] <device>\n"
	    " --export        export key/value pairs\n"
	    " --verbose       print verbose debugging output\n"
	    " --help\n\n");
}

int
main(int argc, char *argv[])
{
	static const struct option options[] = {
		{ "export", 0, NULL, 'x' },
		{ "verbose", 0, NULL, 'v' },
		{ "help", 0, NULL, 'h' },
		{}
	};

	const char *device = NULL;
	int i;
	gboolean export = 0;
	struct termios orig, attrs;
	char *udi;
	int fd, caps;

	while (1) {
		int option;

		option = getopt_long(argc, argv, "xvh", options, NULL);
		if (option == -1)
			break;

		switch (option) {
		case 'x':
			export = TRUE;
			break;
		case 'v':
			verbose = TRUE;
			break;
		case 'h':
			print_usage ();
			return 1;
		default:
			return 1;
		}
	}

	device = argv[optind];
	if (device == NULL) {
		g_printerr ("no node specified\n");
		return 2;
	}

	fd = open (device, O_RDWR | O_EXCL | O_NONBLOCK);
	if (fd < 0) {
		g_printerr ("open(%s) failed: %d\n", device, errno);
		return 3;
	}

	if (tcgetattr (fd, &orig)) {
		g_printerr ("tcgetattr(%s): failed %d\n", device, errno);
		return 4;
	}
	
	memcpy (&attrs, &orig, sizeof (attrs));
	attrs.c_iflag &= ~(IGNCR | ICRNL | IUCLC | INPCK | IXON | IXANY | IGNPAR);
	attrs.c_oflag &= ~(OPOST | OLCUC | OCRNL | ONLCR | ONLRET);
	attrs.c_lflag &= ~(ICANON | XCASE | ECHO | ECHOE | ECHONL);
	attrs.c_lflag &= ~(ECHO | ECHOE);
	attrs.c_cc[VMIN] = 1;
	attrs.c_cc[VTIME] = 0;
	attrs.c_cc[VEOF] = 1;

	attrs.c_cflag &= ~(CBAUD | CSIZE | CSTOPB | CLOCAL | PARENB);
	attrs.c_cflag |= (B9600 | CS8 | CREAD | 0 | 0 | 0);
	
	tcsetattr (fd, TCSANOW, &attrs);
	caps = modem_probe_caps (fd);
	tcsetattr (fd, TCSANOW, &orig);

	if (caps < 0) {
		g_printerr ("%s: couldn't get modem capabilities\n", device);
		return 5;
	}

	if (export) {
		if (caps & MODEM_CAP_GSM)
			g_print ("ID_MODEM_GSM=1\n");
		if (caps & MODEM_CAP_IS707_A)
			g_print ("ID_MODEM_IS707_A=1\n");
		if (caps & MODEM_CAP_IS707P)
			g_print ("ID_MODEM_IS707P=1\n");
		if (caps & MODEM_CAP_IS856)
			g_print ("ID_MODEM_IS856=1\n");
		if (caps & MODEM_CAP_IS856_A)
			g_print ("ID_MODEM_IS856_A=1\n");
	} else {
		g_print ("%s: caps 0x%X%s%s%s%s\n", device, caps,
		         caps & MODEM_CAP_GSM     ? " GSM" : "",
		         caps & (MODEM_CAP_IS707_A | MODEM_CAP_IS707P) ? " CDMA-1x" : "",
		         caps & MODEM_CAP_IS856   ? " EVDOr0" : "",
		         caps & MODEM_CAP_IS856_A ? " EVDOrA" : "");
	}

	return 0;
}