]> CyberLeo.Net >> Repos - SourceForge/eyefi-config.git/blob - eyefi-config.c
better error message
[SourceForge/eyefi-config.git] / eyefi-config.c
1 /*
2  * eyefitest.c
3  *
4  * Copyright (C) 2008 Dave Hansen <dave@sr71.net>
5  *
6  * This software may be redistributed and/or modified under the terms of
7  * the GNU General Public License ("GPL") version 2 as published by the
8  * Free Software Foundation.
9  */
10
11 #include <assert.h>
12 #include <string.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <unistd.h>
16 #include <getopt.h>
17 #include <sys/types.h>
18 #include <sys/stat.h>
19 #include <fcntl.h>
20 #include <errno.h>
21
22 #include "eyefi-config.h"
23
24 int debug_level = 1;
25 #define debug_printf(level, args...) do {       \
26         if ((level) <= debug_level)             \
27                 fprintf(stderr, ## args);       \
28         } while(0)
29
30 #define O_DIRECT        00040000        /* direct disk access hint */
31
32 enum eyefi_file {
33         REQC,
34         REQM,
35         RSPC,
36         RSPM
37 };
38  
39 #define PATHNAME_MAX 4096
40 char eyefi_mount[PATHNAME_MAX]; // PATH_MAX anyone?
41 static char *eyefi_file_name(enum eyefi_file file)
42 {
43         switch (file) {
44         case REQC: return "reqc";
45         case REQM: return "reqm";
46         case RSPC: return "rspc";
47         case RSPM: return "rspm";
48         }
49
50         return NULL;
51 }
52
53 static char *eyefi_file_on(enum eyefi_file file, char *mnt)
54 {
55         char *filename = eyefi_file_name(file);
56         char *full = malloc(PATHNAME_MAX);
57
58         sprintf(&full[0], "%s/EyeFi/%s", mnt, filename);
59         debug_printf(4, "eyefile nr: %d on '%s' is: '%s'\n", file, mnt, &full[0]);
60         return full;
61 }
62
63
64 #define BUFSZ 16384
65 #define EYEFI_BUF_SIZE 16384
66 char unaligned_buf[BUFSZ*2];
67 void *buf;
68
69 /*
70  * Just a few functions so that I can't easily forget about
71  * endinness.
72  */
73 struct __be32 {
74         u32 val;
75 } __attribute__((packed));
76 typedef struct __be32 be32;
77
78 /*
79  * These two obviously need to get fixed for
80  * big endian machines.
81  */
82 u32 be32_to_u32(be32 src)
83 {
84         return swap_bytes(src.val);
85 }
86 be32 u32_to_be32(u32 src)
87 {
88         be32 ret;
89         ret.val = swap_bytes(src);
90         return ret;
91 }
92
93 void dumpbuf(const char *buffer, int bytesToWrite)
94 {
95     int i;
96     static char linebuf[500];
97
98     for (i=0; i < bytesToWrite; i += 16) {
99         char *tmpbuf = &linebuf[0];
100         unsigned long sum = 0;
101         int j;
102 #define lprintf(args...)        do {            \
103         tmpbuf += sprintf(tmpbuf, ## args);\
104 } while (0)
105
106         lprintf("[%03d]: ", i);
107         for (j=0; j < 16; j++) {
108                 u8 c = ((unsigned char *)buffer)[i+j];
109                 lprintf("%02x ", (unsigned int)c);
110                 sum += c;
111         }
112         lprintf(" |");
113         for (j=0; j < 16; j++) {
114                 u8 c = ((unsigned char *)buffer)[i+j];
115                 if (c >= 'a' && c <= 'z')
116                         lprintf("%c", c);
117                 else if (c >= 'A' && c <= 'Z')
118                         lprintf("%c", c);
119                 else if (c >= '0' && c <= '9')
120                         lprintf("%c", c);
121                 else if (c >= 0x20 && c <= 127)
122                         lprintf("%c", c);
123                 else
124                         lprintf(".");
125         }
126         lprintf("|\n");
127         if (sum == 0)
128                 continue;
129         printf("%s", linebuf);
130         //if (i > 200)
131         //      break;
132     }
133 }
134
135 struct card_seq_num {
136         u32 seq;
137 } __attribute__((packed));
138
139 void read_from(enum eyefi_file);
140 void write_to(enum eyefi_file, void *, int);
141 struct card_seq_num read_seq_from(enum eyefi_file file)
142 {
143         struct card_seq_num *ret;
144         read_from(file);
145         ret = buf;
146         return *ret;
147 }
148
149 /*
150  * For O_DIRECT writes to files, we need
151  * to be 512 byte aligned on Linux, I think.
152  * So, just align this to something big
153  * and be done with it.  FIXME :)
154  */
155 void align_buf(void)
156 {
157         unsigned long addr = (unsigned long)&unaligned_buf[BUFSZ];
158         addr &= ~(BUFSZ-1);
159         buf = (void *)addr;
160         debug_printf(4, "buf: %p\n", buf);
161         debug_printf(4, "unaligned: %p\n", &unaligned_buf[0]);
162 }
163
164 struct card_seq_num seq;
165
166 /*
167  * The real manager does this so we might
168  * as well, too.
169  */
170 void zero_card_files(void)
171 {
172         write_to(REQM, buf, BUFSZ);
173         write_to(REQC, buf, BUFSZ);
174         write_to(RSPM, buf, BUFSZ);
175         write_to(RSPC, buf, BUFSZ);
176
177         read_from(REQM);
178         read_from(REQC);
179         read_from(RSPM);
180         read_from(RSPC);
181 }
182
183 char lower(char c)
184 {
185         if ((c >= 'A') && (c <= 'Z'))
186                 c += ('a' - 'A');
187         return c;
188 }
189
190 int atoh(char c)
191 {
192         char lc = lower(c);
193         if ((c >= '0') && (c <= '9'))
194                 return c - '0';
195         else if ((c >= 'a') && (c <= 'z'))
196                 return (c - 'a') + 10;
197         debug_printf(5, "non-hex character: '%c'/'%c'\n", c, lc);
198         return -1;
199 }
200
201 int atoo(char o)
202 {
203         if ((o >= '0') && (o <= '7'))
204                 return atoh(o);
205         return -1;
206 }
207
208 int octal_esc_to_chr(char *input) {
209         int i=0;
210         int ret = 0;
211         int len = strlen(input);
212
213         //intf("%s('%s')\n", __func__, input);
214         if (input[0] != '\\')
215                 return -1;
216         if (len < 4)
217                 return -1;
218
219         for (i=1; i < len ; i++) {
220                 if (i > 3)
221                         break;
222                 int tmp = atoo(input[i]);
223                 //intf("tmp: %d\n", tmp);
224                 if (tmp < 0)
225                         return tmp;
226                 ret <<= 3;
227                 ret += tmp;
228         }
229         return ret;
230 }
231
232 char *replace_escapes(char *str)
233 {
234         int i;
235         int output = 0;
236         debug_printf(4, "%s(%s)\n", __func__, str);
237         for (i=0; i < strlen(str); i++) {
238                 int esc = octal_esc_to_chr(&str[i]);
239                 if (esc >= 0) {
240                         str[output++] = esc;
241                         i += 3;
242                         continue;
243                 }
244                 str[output++] = str[i];
245         }
246         str[output] = '\0';
247         debug_printf(4, "replaced escapes in: '%s' bytes of output: %d\n", str, output);
248         return str;
249 }
250
251 #define LINEBUFSZ 1024
252 char *locate_eyefi_mount(void)
253 {
254         char line[LINEBUFSZ];
255         FILE *mounts = fopen("/proc/mounts", "r");
256
257         char dev[LINEBUFSZ];
258         char mnt[LINEBUFSZ];
259         char fs[LINEBUFSZ];
260         char opt[LINEBUFSZ];
261         int foo;
262         int bar;
263         
264         if (strlen(eyefi_mount))
265                 return &eyefi_mount[0];
266
267         while (fgets(&line[0], 1023, mounts)) {
268                 int read;
269                 read = sscanf(&line[0], "%s %s %s %s %d %d",
270                                 &dev[0], &mnt[0], &fs[0], &opt[0],
271                                 &foo, &bar);
272                 // only look at fat filesystems:
273                 if (strcmp(fs, "msdos") && strcmp(fs, "vfat")) {
274                         debug_printf(2, "fs at '%s' is not fat, skipping...\n", mnt);
275                         continue;
276                 }
277                 // Linux's /proc/mounts has spaces like this \040
278                 replace_escapes(&mnt[0]);
279                 char *file = eyefi_file_on(REQM, &mnt[0]);
280                 debug_printf(2, "looking for EyeFi file here: '%s'\n", file);
281
282                 struct stat statbuf;
283                 int statret;
284                 statret = stat(file, &statbuf);
285                 free(file);
286                 if (statret) {
287                         debug_printf(2, "fs at: %s is not an Eye-Fi card, skipping...\n",
288                                         eyefi_mount);
289                         continue;
290                 }
291                 strcpy(&eyefi_mount[0], &mnt[0]);
292                 debug_printf(1, "located EyeFi card at: '%s'\n", eyefi_mount);
293                 break;
294         }
295         fclose(mounts);
296         if (strlen(eyefi_mount))
297                 return &eyefi_mount[0];
298         return NULL;
299 }
300
301 void init_card()
302 {
303         char *mnt;
304         if (buf != NULL)
305                 return;
306
307         debug_printf(2, "Initializing card...\n");
308         mnt = locate_eyefi_mount();
309         if (mnt == NULL) {
310                 debug_printf(1, "unable to locate Eye-Fi card\n");
311                 if (debug_level < 5)
312                         debug_printf(0, "please run with '-d5' option and report the output\n");
313                 else {
314                         debug_printf(0, "----------------------------------------------\n");
315                         debug_printf(0, "Debug information:\n");
316                         system("cat /proc/mounts >&2");
317                 }
318                 exit(1);
319         }
320
321         align_buf();
322         zero_card_files();
323         seq = read_seq_from(RSPC);
324         if (seq.seq == 0)
325                 seq.seq = 0x1234;
326         debug_printf(2, "Done initializing card...\n");
327 }
328
329 static char *eyefi_file(enum eyefi_file file)
330 {
331         init_card();
332         return eyefi_file_on(file, &eyefi_mount[0]);
333 }
334
335 void open_error(char *file)
336 {
337         fprintf(stderr, "unable to open '%s'\n", file);
338         fprintf(stderr, "Is the Eye-Fi card inserted and mounted at: %s ?\n", eyefi_mount);
339         fprintf(stderr, "Do you have write permissions to it?\n");
340         fprintf(stderr, "debug information:\n");
341         if (debug_level > 0)
342                 system("cat /proc/mounts >&2");
343         if (debug_level > 1)
344                 perror("bad open");
345         exit(1);
346 }
347
348 void read_from(enum eyefi_file __file)
349 {
350         u8 c;
351         int i;
352         int ret, retcntl;
353         int fd;
354         int zeros = 0;
355         char *file = eyefi_file(__file);
356         
357         init_card();
358
359         fd = open(file, O_RDONLY);
360         if (fd < 0) 
361                 open_error(file);
362         retcntl = fcntl(fd, F_SETFL, O_DIRECT);
363         if (retcntl < 0) {
364                 perror("bad fcntl");
365                 exit(1);
366         }
367         ret = read(fd, buf, BUFSZ);
368         if (debug_level > 3)
369                 dumpbuf(buf, 128);
370         if (ret < 0) {
371                 perror("bad read");
372                 exit(1);
373         }
374         debug_printf(3, "read '%s': bytes: %d fcntl: %d\n", file, ret, retcntl);
375         for (i=0; i < BUFSZ; i++) {
376                 c = ((char *)buf)[i];
377                 if (c == '\0') {
378                         zeros++;
379                         continue;
380                 }
381         }
382         //if (zeros)
383         //      printf(" zeros: %d", zeros);
384         //fsync(fd);
385         free(file);
386         close(fd);
387 }
388
389 void write_to(enum eyefi_file __file, void *stuff, int len)
390 {
391         int ret;
392         int fd;
393         char *file;
394
395         init_card();
396         file = eyefi_file(__file);
397         if (len == -1)
398                 len = strlen(stuff);
399
400         if (debug_level > 3) {
401                 debug_printf(3, "%s('%s', ..., %d)\n", __func__, file, len);
402                 dumpbuf(stuff, len);
403         }
404         memset(buf, 0, BUFSZ);
405         memcpy(buf, stuff, len);
406         fd = open(file, O_RDWR|O_DIRECT|O_CREAT, 0600);
407         //ret = lseek(fd, 0, SEEK_SET);
408         if (fd < 0)
409                 open_error(file);
410         if (debug_level > 3)
411                 dumpbuf(buf, 128);
412         ret = write(fd, buf, BUFSZ);
413         //fsync(fd);
414         close(fd);
415         debug_printf(3, "wrote %d bytes to '%s' (string was %d bytes)\n", ret, file, len);
416         if (ret < 0) {
417                 fprintf(stderr, "error writing to '%s': ", file);
418                 perror("");
419                 exit(ret);
420         }
421         free(file);
422 }       
423
424 /*
425  * Most of the eyefi strings are pascal-style with
426  * a length byte preceeding content.  (Did pascal
427  * have just a byte for length or more??)
428  */
429 struct pascal_string {
430         u8 length;
431         u8 value[32];
432 } __attribute__((packed));
433
434 void print_pascal_string(struct pascal_string *str)
435 {
436         int i;
437         for (i = 0; i < str->length; i++)
438                 printf("%c", str->value[i]);
439 }
440
441 /*
442  * The 'o' command has several sub-commands:
443  */
444 enum card_info_subcommand {
445         MAC_ADDRESS   = 1,
446         FIRMWARE_INFO = 2,
447         CARD_KEY      = 3,
448         API_URL       = 4,
449         UNKNOWN1      = 5, // Chris says these are 
450         UNKNOWN2      = 6, // checksums
451         LOG_LEN       = 7,
452 };
453
454 struct card_info_req {
455         u8 o;
456         u8 subcommand;
457 } __attribute__((packed));
458
459 struct card_info_rsp_key {
460         struct pascal_string key;
461 };
462
463 #define MAC_BYTES 6
464 struct mac_address {
465         u8 length;
466         u8 mac[MAC_BYTES];
467 } __attribute__((packed));
468
469 struct card_info_api_url {
470         struct pascal_string key;
471 };
472
473 struct card_info_log_len {
474         u8 len;
475         be32 val;
476 } __attribute__((packed));
477
478 #define write_struct(file, s) write_to((file), s, sizeof(*(s)))
479
480 void print_mac(struct mac_address *mac)
481 {
482         int i;
483         for (i=0; i < MAC_BYTES-1; i++) {
484                 printf("%02x:", mac->mac[i]);
485         }
486         printf("%02x\n", mac->mac[i]);
487 }
488
489 void inc_seq(void)
490 {
491         //u32 tmpseq = be32_to_u32(seq.seq);
492         //seq.seq = u32_to_be32(tmpseq+1);
493         seq.seq++;
494         write_struct(REQC, &seq);
495 }
496
497 u32 current_seq(void)
498 {
499         return seq.seq;
500 }
501
502 void wait_for_response(void)
503 {
504         int i;
505         debug_printf(3, "waiting for response...\n");
506         inc_seq();
507         for (i = 0; i < 50; i++) {
508                 struct card_seq_num cardseq = read_seq_from(RSPC);
509                 u32 rsp = cardseq.seq;
510                 debug_printf(3, "read rsp code: %lx, looking for: %lx raw: %lx\n", rsp, current_seq(),
511                                 cardseq.seq);
512                 if (rsp == current_seq())
513                         break;
514                 usleep(300000);
515         }
516         debug_printf(3, "got good seq, reading RSPM...\n");
517         read_from(RSPM);
518         debug_printf(3, "done reading RSPM\n");
519 }
520 struct byte_response {
521         u8 response;
522 };
523
524 enum net_type {
525         UNSECURED,
526         WEP,
527         WPA,
528         WPA2
529 };
530
531 #define ESSID_LEN 32
532 struct scanned_net {
533         char essid[ESSID_LEN];
534         signed char strength;
535         u8 type;
536 } __attribute__((packed));
537
538 struct scanned_net_list {
539         u8 nr;
540         struct scanned_net nets[100];
541 } __attribute__((packed));
542
543 struct configured_net {
544         char essid[ESSID_LEN];
545 } __attribute__((packed));
546
547 struct configured_net_list {
548         u8 nr;
549         struct configured_net nets[100];
550 } __attribute__((packed));
551
552 char *net_test_states[] = {
553         "not scanning",
554         "locating network",
555         "verifying network key",
556         "waiting for DHCP",
557         "testing connection to Eye-Fi server",
558         "success",
559 };
560
561 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
562
563 char *net_test_state_name(u8 state)
564 {
565         int size = ARRAY_SIZE(net_test_states);
566         if (state >= size)
567                 return "unknown";
568         return net_test_states[state];
569 }
570
571 char *net_types[] = {
572         "No security",
573         "WEP",
574         "WPA",
575         "unknown1",
576         "WPA2",
577 };
578
579 char *net_type_name(u8 type)
580 {
581         int size = ARRAY_SIZE(net_types);
582         if (type >= size)
583                 return "unknown";
584         return net_types[type];
585 }
586
587 #define WPA_KEY_BYTES 32
588 struct wpa_key {
589         u8 key[WPA_KEY_BYTES];
590 } __attribute((packed));
591
592 #define WEP_KEY_BYTES 32
593 struct wep_key {
594         u8 key[WEP_KEY_BYTES];
595 } __attribute((packed));
596
597 struct network_key {
598         u8 len;
599         union {
600                 struct wpa_key wpa;
601                 struct wep_key wep;
602         };
603 } __attribute((packed));
604
605 #define KEY_LEN 32
606 struct net_request {
607         char req;
608         u8 essid_len;
609         char essid[ESSID_LEN];
610         struct network_key key;
611 } __attribute((packed));
612
613 /*
614  * Take a string like "0ab1" and make it
615  * a series of bytes: { 0x0a, 0xb1 }
616  *
617  * @len is the strlen() of the ascii
618  *
619  * Destroys the original string.
620  */
621 char *convert_ascii_to_hex(char *ascii, int len)
622 {
623         int i;
624         if (len%2) {
625                 fprintf(stderr, "%s() must be even number of bytes: %d\n",
626                 __func__, len);
627                 exit(2);
628         }
629         for (i=0; i < len; i+=2) {
630                 int high = atoh(ascii[i]);
631                 int low  = atoh(ascii[i+1]);
632                 u8 byte = (high<<4 | low);
633                 if (high < 0 || low < 0)
634                         return NULL;
635                 debug_printf(6, "high: %02x low: %02x, both: %02x\n", high, low, byte);
636                 ascii[i/2] = byte;
637         }
638         for (i=len/2; i < len; i++)
639                 ascii[i] = '\0';
640         return &ascii[0];
641 }
642
643 #define PASSPHRASE_PROG "wpa_passphrase"
644
645 struct wpa_key *make_wpa_key(char *essid, char *pass)
646 {
647         struct wpa_key *key = malloc(sizeof(*key));
648
649         if (strlen(pass) == WPA_KEY_BYTES*2) {
650                 char *hex_pass;
651                 debug_printf(2, "Interpreting password as hex WPA key\n");
652                 hex_pass = convert_ascii_to_hex(pass, WPA_KEY_BYTES*2);
653                 if (!hex_pass)
654                         return NULL;
655                 memcpy(&key->key[0], pass, WPA_KEY_BYTES);
656         } else {
657                 debug_printf(2, "Interpreting password as ASCII WPA key\n");
658                 pbkdf2_sha1(pass, essid, strlen(essid), 4096,
659                             &key->key[0], WPA_KEY_BYTES);
660         }
661         return key;
662 }
663
664 void card_info_cmd(enum card_info_subcommand cmd)
665 {
666         struct card_info_req cir;
667         cir.o = 'o';
668         cir.subcommand = cmd;
669
670         write_struct(REQM, &cir);
671         wait_for_response();
672 }
673
674 u32 fetch_log_length(void)
675 {
676         card_info_cmd(LOG_LEN);
677         struct card_info_log_len *loglen = buf;
678         return be32_to_u32(loglen->val);
679 }
680
681 void print_log_len(void)
682 {
683         u32 len = fetch_log_length();
684         printf("log len: %08lx\n", len);
685 }
686
687 void print_card_mac(void)
688 {
689         debug_printf(2, "%s()\n", __func__);
690         card_info_cmd(MAC_ADDRESS);
691         struct mac_address *mac = buf;
692         assert(mac->length == MAC_BYTES);
693         printf("card mac address: ");
694         print_mac(mac);
695 }
696
697 void print_card_key(void)
698 {
699         debug_printf(2, "%s()\n", __func__);
700         card_info_cmd(CARD_KEY);
701         struct card_info_rsp_key *foo = buf;
702         printf("card key (len: %d): '", foo->key.length);
703         print_pascal_string(&foo->key);
704         printf("'\n");
705 }
706
707 struct noarg_request {
708         u8 req;
709 };
710
711 void issue_noarg_command(u8 cmd)
712 {
713         struct noarg_request req;
714         req.req = cmd;
715         write_struct(REQM, &req);
716         wait_for_response();
717 }
718
719 void scan_print_nets(void)
720 {
721         int i;
722
723         debug_printf(2, "%s()\n", __func__);
724         issue_noarg_command('g');
725         struct scanned_net_list *scanned = buf;
726         if (scanned->nr == 0) {
727                 printf("unable to detect any wireless networks\n");
728                 return;
729         }
730         printf("Scanned wireless networks:\n");
731         for (i=0; i < scanned->nr; i++) {
732                 struct scanned_net *net = &scanned->nets[i];
733                 printf("'%s' type(%d): %s, strength: %d\n", net->essid,
734                                 net->type,
735                                 net_type_name(net->type),
736                                 net->strength);
737         }
738 }
739
740 void print_configured_nets(void)
741 {
742         int i;
743         struct configured_net_list *configured;
744
745         debug_printf(2, "%s()\n", __func__);
746         issue_noarg_command('l');
747         configured = buf;
748         if (configured->nr == 0) {
749                 printf("No wireless networks configured on card\n");
750                 return;
751         }
752         printf("configured wireless networks:\n");
753         for (i=0; i < configured->nr; i++) {
754                 struct configured_net *net = &configured->nets[i];
755                 printf("'%s'\n", net->essid);
756         }
757 }
758
759 void reboot_card(void)
760 {
761         debug_printf(2, "%s()\n", __func__);
762         issue_noarg_command('b');
763 }
764
765 void copy_wep_key(struct wep_key *dst, struct wep_key *src)
766 {
767         memcpy(&dst->key, &src->key, sizeof(*dst));
768 }
769
770 void copy_wpa_key(struct wpa_key *dst, struct wpa_key *src)
771 {
772         memcpy(&dst->key, &src->key, sizeof(*dst));
773 }
774
775 void network_action(char cmd, char *essid, char *wpa_ascii)
776 {
777         struct net_request nr;
778         memset(&nr, 0, sizeof(nr));
779
780         nr.req = cmd;
781         strcpy(&nr.essid[0], essid);
782         nr.essid_len = strlen(essid);
783         struct wpa_key *wpakey;
784         if (wpa_ascii) {
785                 wpakey = make_wpa_key(essid, wpa_ascii);
786                 nr.key.len = sizeof(*wpakey);
787                 copy_wpa_key(&nr.key.wpa, wpakey);
788         }
789         write_struct(REQM, &nr);
790         wait_for_response();
791 }
792
793 void add_network(char *essid, char *wpa_ascii)
794 {
795         debug_printf(2, "%s()\n", __func__);
796         network_action('a', essid, wpa_ascii);
797 }
798
799 void remove_network(char *essid)
800 {
801         debug_printf(2, "%s()\n", __func__);
802         network_action('d', essid, NULL);
803 }
804
805 int try_connection_to(char *essid, char *wpa_ascii)
806 {
807         int i;
808         int ret = -1;
809
810         char *type = net_type_name(WPA);
811         if (!wpa_ascii)
812                 type = net_type_name(UNSECURED);
813         printf("trying to connect to %s network: '%s'", type, essid);
814         if (wpa_ascii)
815                 printf(" with passphrase: '%s'", wpa_ascii);
816         fflush(NULL);
817
818         // test network
819         network_action('t', essid, wpa_ascii);
820         u8 last_rsp = -1;
821
822         char rsp = '\0';
823         for (i=0; i < 200; i++) {
824                 struct byte_response *r;
825                 issue_noarg_command('s');
826                 r = buf;
827                 rsp = r->response;
828                 char *state = net_test_state_name(rsp);
829                 if (rsp == last_rsp) {
830                         printf(".");
831                         fflush(NULL);;
832                 } else {
833                         if (rsp)
834                                 printf("\nTesting connecion to '%s' (%d): %s", essid, rsp, state);
835                         last_rsp = rsp;
836                 }
837                 
838                 if (!strcmp("success", state)) {
839                         ret = 0;
840                         break;
841                 }
842                 if (!strcmp("not scanning", state))
843                         break;
844                 if (!strcmp("unknown", state))
845                         break;
846         }
847         printf("\n");
848         if (!ret) {
849                 printf("Succeeded connecting to: '%s'\n", essid);
850         } else {
851                 printf("Unable to connect to: '%s' (final state: %d/'%s')\n", essid,
852                                 rsp, net_test_state_name(rsp));
853         }
854         return ret;
855 }
856
857 struct fetch_log_cmd {
858         char m;
859         be32 offset;
860 } __attribute__((packed));
861
862 /*
863  * When you ask for the log at offset 0x0, you
864  * get back 8 bytes of offsets into the rest of
865  * the data
866  */
867 struct first_log_response {
868         be32 log_end;
869         be32 log_start;
870         u8 data[EYEFI_BUF_SIZE-8];
871 } __attribute__((packed));
872
873 struct rest_log_response {
874         u8 data[EYEFI_BUF_SIZE];
875 } __attribute__((packed));
876
877 unsigned char *get_log_at_offset(u32 offset)
878 {
879         struct fetch_log_cmd cmd;
880         cmd.m = 'm';
881         cmd.offset = u32_to_be32(offset);
882
883         debug_printf(2, "getting log at offset: %08lx\n", offset);
884         write_struct(REQM, &cmd);
885         wait_for_response();
886         return buf;
887 }
888
889 int get_log(void)
890 {
891         int total_bytes = 0;
892         int i;
893         u32 log_start;
894         u32 log_end;
895         u32 log_size = fetch_log_length();
896         char *resbuf = malloc(log_size);
897
898         int nr_bufs_per_log = log_size/EYEFI_BUF_SIZE;
899         for (i = 0; i < log_size/EYEFI_BUF_SIZE; i++) {
900                 debug_printf(1, "fetching EyeFi card log part %d/%d...",
901                                 i+1, nr_bufs_per_log);
902                 fflush(NULL);
903                 get_log_at_offset(EYEFI_BUF_SIZE*i);
904                 debug_printf(1, "done\n");
905                 u32 log_size;
906                 u8 *log_data;
907                 if (i == 0) {
908                         struct first_log_response *log = buf;
909                         log_end = be32_to_u32(log->log_end);
910                         log_start = be32_to_u32(log->log_start);
911                         debug_printf(2, "log end:   0x%04lx\n", log_end);
912                         debug_printf(2, "log start: 0x%04lx\n", log_start);
913                         log_data = &log->data[0];
914                         log_size = ARRAY_SIZE(log->data);
915                 } else {
916                         struct rest_log_response *log = buf;
917                         log_data = &log->data[0];
918                         log_size = ARRAY_SIZE(log->data);
919                 }
920                 debug_printf(3, "writing %ld bytes to resbuf[%d]\n",
921                                 log_size, total_bytes);
922                 memcpy(&resbuf[total_bytes], log_data, log_size);
923                 total_bytes += log_size;
924         }
925         // The last byte *should* be a null, and the 
926         // official software does not print it.
927         for (i = 0; i < total_bytes-1; i++) {
928                 int offset = (log_start+i)%total_bytes;
929                 char c = resbuf[offset];
930                 // the official software converts UNIX to DOS-style
931                 // line breaks, so we'll do the same
932                 if (c == '\n')
933                         printf("%c", '\r');
934                 printf("%c", c);
935         }
936         printf("\n");
937         // just some simple sanity checking to make sure what
938         // we are fetching looks valid
939         int null_bytes_left = 20;
940         if (resbuf[log_end] != 0) {
941                 debug_printf(2, "error: unexpected last byte (%ld/0x%lx) of log: %02x\n",
942                                 log_end, log_end, resbuf[log_end]);
943                 for (i=0; i<log_size; i++) {
944                         if (resbuf[i])
945                                 continue;
946                         if (null_bytes_left <= 0)
947                                 continue;
948                         null_bytes_left--;
949                         debug_printf(2, "null byte %d\n", i);
950                 }
951         }
952         free(resbuf);
953         return 0;
954 }
955
956 void usage(void)
957 {
958         printf("Usage:\n");
959         printf("  eyefitest [OPTIONS]\n");
960         printf("  -a ESSID      add network (implies test unless --force)\n");
961         printf("  -t ESSID      test network\n");
962         printf("  -p KEY        set WPA key for add/test\n");
963         printf("  -r ESSID      remove network\n");
964         printf("  -s            scan for networks\n");
965         printf("  -c            list configured networks\n");
966         printf("  -b            reboot card\n");
967         printf("  -d level      set debugging level (default: 1)\n");
968         printf("  -k            print card unique key\n");
969         printf("  -l            dump card log\n");
970         printf("  -m            print card mac\n");
971         exit(4);
972 }
973
974 int main(int argc, char **argv)
975 {
976         if (argc == 1)
977                 usage();
978
979         debug_printf(3, "%s starting...\n", argv[0]);
980         
981         //static int passed_wep = 0;
982         //static int passed_wpa = 0;
983         static int force = 0;
984         static struct option long_options[] = {
985                 //{"wep", 'x', &passed_wep, 1},
986                 //{"wpa", 'y', &passed_wpa, 1},
987                 {"force", 0, &force, 1},
988                 {"help", 'h', NULL, 1},
989         };
990
991         int option_index;
992         char c;
993         char *essid = NULL;
994         char *passwd = NULL;
995         char network_action = 0;
996         debug_printf(3, "about to parse arguments\n");
997         while ((c = getopt_long_only(argc, argv, "a:bcd:klmp:r:st:",
998                         &long_options[0], &option_index)) != -1) {
999                 debug_printf(3, "argument: '%c' %d optarg: '%s'\n", c, c, optarg);
1000                 switch (c) {
1001                 case 0:
1002                         // was a long argument
1003                         break;
1004                 case 'a':
1005                 case 't':
1006                 case 'r':
1007                         essid = optarg;
1008                         network_action = c;
1009                         break;
1010                 case 'b':
1011                         reboot_card();
1012                         break;
1013                 case 'c':
1014                         print_configured_nets();
1015                         break;
1016                 case 'd':
1017                         debug_level = atoi(optarg);
1018                         fprintf(stderr, "set debug level to: %d\n", debug_level);
1019                         break;
1020                 case 'k':
1021                         print_card_key();
1022                         break;
1023                 case 'l':
1024                         get_log();
1025                         break;
1026                 case 'm':
1027                         print_card_mac();
1028                         break;
1029                 case 'p':
1030                         passwd = optarg;
1031                         break;
1032                 case 's':
1033                         scan_print_nets();
1034                         break;
1035                 case 'h':
1036                 default:
1037                         usage();
1038                         break;
1039                 }
1040         }
1041         debug_printf(3, "after arguments essid: '%s' passwd: '%s'\n", essid, passwd);
1042         if (network_action && essid) {
1043                 int ret = 0;
1044                 init_card();
1045                 switch (network_action) {
1046                 case 't':
1047                         ret = try_connection_to(essid, passwd);
1048                         break;
1049                 case 'a':
1050                         if (!force) {
1051                                 ret = try_connection_to(essid, passwd);
1052                         } else {
1053                                 debug_printf(1, "forced: skipping network test\n");
1054                         }
1055                         if (ret) {
1056                                 printf("Error connecting to network '%s', not adding.\n", essid);
1057                                 printf("use --force to override\n");
1058                                 break;
1059                         }
1060                         add_network(essid, passwd);
1061                         break;
1062                 case 'r':
1063                         remove_network(essid);
1064                         break;
1065                 }
1066         }
1067         return 0;
1068 }
1069
1070