GCC 'uninitialized variable' broken warnings workarounded.
[mdsms.git] / mdsms.c
1 #include "config.h"
2 #ifndef lint
3 static char rcsid[] ATTR_UNUSED = "$Id$";
4 #endif
5
6 #include "setup.h"
7
8 #ifdef HAVE_STDIO_H
9 #include <stdio.h>
10 #endif
11 #ifdef HAVE_STDLIB_H
12 #include <stdlib.h>
13 #endif
14 #ifdef HAVE_STRING_H
15 #include <string.h>
16 #endif
17 #ifdef HAVE_SIGNAL_H
18 #include <signal.h>
19 #endif
20 #ifdef HAVE_STDARG_H
21 #include <stdarg.h>
22 #endif
23 #ifdef HAVE_LIMITS_H
24 #include <limits.h>
25 #endif
26 #ifdef HAVE_CTYPE_H
27 #include <ctype.h>
28 #endif
29 #ifdef HAVE_TERMIOS_H
30 #include <termios.h>
31 #endif
32 #ifdef HAVE_UNISTD_H
33 #include <unistd.h>
34 #endif
35 #ifdef HAVE_ASSERT_H
36 #include <assert.h>
37 #endif
38 #ifdef HAVE_SYS_TYPES_H
39 #include <sys/types.h>
40 #endif
41 #ifdef HAVE_SYS_STAT_H
42 #include <sys/stat.h>
43 #endif
44 #ifdef HAVE_FCNTL_H
45 #include <fcntl.h>
46 #endif
47 #ifdef HAVE_ERRNO_H
48 #include <errno.h>
49 #endif
50 #ifdef HAVE_TIME_H
51 #include <time.h>
52 #endif
53 #ifdef HAVE_SYS_TIME_H
54 #include <sys/time.h>
55 #endif
56 #ifdef HAVE_SYS_POLL_H
57 #include <sys/poll.h>
58 #endif
59
60 #ifdef HAVE_GETOPT_LONG
61 #include <getopt.h>
62 #else
63 #include "getopt.h"
64 #endif
65
66 #define NELEM(x) (sizeof((x))/sizeof(*(x)))
67
68 #ifndef DEBUG
69 #define dbg(cmd)
70 #else
71 #define dbg(cmd) cmd
72 #endif
73 /* ANSI C does not allow macro with variable arguments */
74 #define dO stderr
75 #define dB(a) dbg(fprintf a)
76
77 #define d1(n1)                      dB((dO,n1                     ))
78 #define d2(n1,n2)                   dB((dO,n1,n2                  ))
79 #define d3(n1,n2,n3)                dB((dO,n1,n2,n3               ))
80 #define d4(n1,n2,n3,n4)             dB((dO,n1,n2,n3,n4            ))
81 #define d5(n1,n2,n3,n4,n5)          dB((dO,n1,n2,n3,n4,n5         ))
82 #define d6(n1,n2,n3,n4,n5,n6)       dB((dO,n1,n2,n3,n4,n5,n6      ))
83 #define d7(n1,n2,n3,n4,n5,n6,n7)    dB((dO,n1,n2,n3,n4,n5,n6,n7   ))
84 #define d8(n1,n2,n3,n4,n5,n6,n7,n8) dB((dO,n1,n2,n3,n4,n5,n6,n7,n8))
85
86 static const char version[]="This is Mobile Device SMS tool (" PACKAGE " " VERSION ")\n";
87
88 static int verbose
89 #ifdef DEBUG
90         =0xFFFF
91 #endif
92         ;
93 static char *pname;
94 static int dis_cleanup=0,devfd=-1;
95
96 static char *phone,*device,*logname,*lockfile,*smsc,*maxretry,*readtime,*chartime,*cmdtime,*baud,*restore;
97 static int readbody;
98 static long maxretryn=DEF_MAXRETRY,readtimen=-1,chartimen=DEF_CHARTIME,cmdtimen=DEF_CMDTIME,baudn=DEF_BAUD;
99 static size_t bodylen;
100 /* --send / --send-mobildock / --receive specific */
101 static char *body;
102 /* --logo-send specific */
103 static char *logoname,*gsmnet;
104 /* --ring-send specific */
105 static char *ringname;
106
107 static enum modenum {
108   MODE_UNKNOWN=0,
109 /* must differ from regular char-s */
110   MODE_FIRST         =0x3400,
111         MODE_SEND          =MODE_FIRST+0, /* --send / --send-mobildock */
112         MODE_SEND_MOBILDOCK=MODE_FIRST+1, /* --send-mobildock in before readtimen is set */
113         MODE_RECEIVE       =MODE_FIRST+2, /* --receive */
114         MODE_LOGO_SEND     =MODE_FIRST+3, /* --logo-send */
115         MODE_RING_SEND     =MODE_FIRST+4  /* --ring-send */
116         } mode=MODE_UNKNOWN;
117 #define MODE_ORDER(x) ((x)-MODE_FIRST)
118 #define MODE_NAME(x) (longopts[MODE_ORDER((x))].name)
119 #define MODE_BIT(x) (1<<MODE_ORDER((x)))
120
121 static unsigned mode_stamp;
122
123 /* pdusmsc variable has to be filled in */
124 #define NEED_PDUSMSC() (mode==MODE_SEND)
125
126 static char *devicename; /* path stripped */
127 static char lockreal[512],locked;
128
129 static struct termios restios,tios;
130 static char restios_yes;
131 static FILE *logf;
132
133 static void vlogmsg(char pm,char fatal,const char *fmt,va_list ap) ATTR_PRINTFORMAT(3,0);
134 static void vlogmsg(char pm,char fatal,const char *fmt,va_list ap)
135 {
136 time_t stamp;
137 char *ctm,*s;
138 pid_t mypid=-1;
139 char host[LINE_MAX];
140
141         if (!logf) return;
142         if (mypid==-1) {
143                 mypid=getpid();
144                 if (gethostname(host,sizeof(host))) strcpy(host,"<ERROR>");
145                 }
146         time(&stamp);
147         ctm=ctime(&stamp);
148         if ((s=strchr(ctm,'\n'))) *s='\0';
149         fprintf(logf,"%s %s %s[%d]: ",ctm,host,pname,mypid);
150         vfprintf(logf,fmt,ap);
151         if (pm) { fputs(": ",logf); fputs(strerror(errno),logf); }
152         if (fatal!='\n') fputc((fatal=='.'?'.':'!'),logf);
153         fputc('\n',logf);
154         fflush(logf);
155 }
156
157 static void logmsg(const char *fmt,...) ATTR_PRINTFORMAT(1,2);
158 static void logmsg(const char *fmt,...)
159 {
160 va_list ap;
161         va_start(ap,fmt);
162         vlogmsg(0,'\n',fmt,ap);
163         va_end(ap);
164 }
165
166 static void error(const char *fmt,...) ATTR_PRINTFORMAT(1,2);
167 static void error(const char *fmt,...)
168 {
169 va_list ap;
170 char fatal,pm;
171
172         if ((pm=(*fmt=='^'))) fmt++;
173         fatal=*fmt;
174         if (fatal=='!' || fatal=='.' || fatal=='\n') fmt++;
175         else fatal=0;
176
177         fprintf(stderr,"%s: ",pname);
178         va_start(ap,fmt);
179         vfprintf(stderr,fmt,ap);
180         if (fatal=='!') vlogmsg(pm,fatal,fmt,ap);
181         va_end(ap);
182         if (pm) { fputs(": ",stderr); fputs(strerror(errno),stderr); }
183         if (fatal!='\n') fputc((fatal=='.'?'.':'!'),stderr);
184         fputc('\n',stderr);
185         if (fatal=='!') exit(EXIT_FAILURE);
186 }
187
188 static void chk(const void *p)
189 {
190         if (p) return;
191         error("!Virtual memory exhausted");
192 }
193
194 static char *devcmd(const char *term,const char *catch,const char *send,...) ATTR_PRINTFORMAT(3,4);
195
196 static void unlockdevice(int hard)
197 {
198         d2("unlockdevice(), locked=%d\n",locked);
199         if (!locked || !*lockreal) return;
200         if (!hard && locked>1) { locked--; return; }
201         d2("Removing lockfile \"%s\"\n",lockreal);
202         if (unlink(lockreal))
203                 error("^Error removing my device lockfile \"%s\"",lockreal);
204         locked=0;
205 }
206
207 static void cleanup(void)
208 {
209         d1("cleanup()\n");
210         if (dis_cleanup) return;
211         if (restore) {
212 char *cmd=restore;
213                 restore=NULL;
214                 devcmd(NULL,NULL,"\r\nAT");
215                 devcmd(NULL,NULL,cmd);
216                 devcmd(NULL,NULL,"\r\nAT");
217                 }
218         if (restios_yes) {
219                 if (tcsetattr(devfd,TCSANOW,&restios))
220                         error("^Error restoring termios for device");
221                 restios_yes=0;
222                 }
223         unlockdevice(1);
224         dis_cleanup=1;
225         exit(EXIT_FAILURE);
226 }
227
228 static void usage(void)
229 {
230         fprintf(stderr,"\
231 \n\
232 %s\
233 \n\
234 Usage: " PACKAGE " [-c|--config <cfgfile>] [-d|--device <device>]\n\
235              {--send | --send-mobildock | --receive | --logo-send}\n\
236              [-L|--log <file>] [-b|--baud <rate>]\n\
237              [-l|--lockfile <lock>] [-s|--smsc <smsc #>] [-m|--maxretry <#>]\n\
238              [-r|--readtime <sec>] [-t|--chartime <msec>] [-T|--cmdtime <msec>]\n\
239              [-v|--verbose] [-h|--help] [-V|--version]\n\
240   --send / --send-mobildock:\n\
241              [-f|--file] <dest. phone> <msg text|msg filename>\n\
242   --receive:\n\
243              <command name>\n\
244   --logo-send:\n\
245              <dest. phone> <logo filename> [<GSMnet id>]\n\
246   --ring-send:\n\
247              <dest. phone> <ring filename>\n\
248 \n\
249  -c, --config\tRead this additional config file\n\
250 \t\t(def. \"" CONFIG_MAIN "\" and \"$HOME" CONFIG_HOME "\")\n\
251  -d, --device\tMobile on this serial device (def. \"" DEF_DEVICE "\")\n\
252  -L, --log\tLog all important messages to this file (def. \"" DEF_LOGNAME "\")\n\
253  -b, --baud\tSet baudrate, 2400-57600 supported (def. %d)\n\
254  -l, --lockfile\tLock serial port by this file, \"%%s\" is basename of device\n\
255 \t\t(def. \"%s\")\n\
256  -s, --smsc\tUse this SMS Center number (def. query from mobile)\n\
257  -m, --maxretry\tMaximum retries of any command before giving up (def. %d)\n\
258  -r, --readtime\tSeconds for maximum wait time for response\n\
259 \t\t(def. %ds standard, %ds for MobilDock modes, multiplied %dx for long cmds)\n\
260  -t, --chartime\tMilliseconds between each char (def. %dms)\n\
261  -T, --cmdtime\tMilliseconds before each whole AT command (def. %dms)\n\
262  -v, --verbose\tIncrease verbosity level, more \"-v\"s give more messages\n\
263  -h, --help\tPrint a summary of the options\n\
264  -V, --version\tPrint the version number\n\
265 \n\
266 --send / --send-mobildock:\n\
267  -f, --file\tRead contents of message from file instead\n\
268 --receive:\n\
269  <command name>\tProgram to run on receive, message will be on stdin\n\
270 \t\tFollowing substitutes are recognized:\n\
271 \t\t%%p - source phone number\n\
272 \t\t%%T - timestamp from SMSC as number of seconds from 1970\n\
273 \t\t%%t - ctime(3) style timestamp (e.g. \"Wed Jun 30 21:49:08 1993\")\n\
274 --logo-send:\n\
275  <GSMnet id>\t* Oper. logo: Enter custom network code MccMnc, e.g. 23002\n\
276 \t\t* Oper. logo: Specify \"" WORD_NET "\" to read network code from NOL file\n\
277 \t\t* Group gfx : Specify \"" WORD_GROUP "\" to send logo as group graphics\n\
278 \n\
279 You may need to use the following line to catch all of this help text:\n\
280 ./mdsms 2>&1|more\n\
281 \n",version,DEF_BAUD,DEF_LOCKFILE,DEF_MAXRETRY,
282 DEF_READTIME,DEF_READTIME_MOBILDOCK,EXT_READTIME,DEF_CHARTIME,DEF_CMDTIME);
283         exit(EXIT_FAILURE);
284 }
285
286 static const struct option longopts[]={
287 /* Modes has to be in-order on exact positions */
288 {"send"          ,0,0,MODE_SEND},
289 {"send-mobildock",0,0,MODE_SEND_MOBILDOCK},
290 {"receive"       ,0,0,MODE_RECEIVE},
291 {"logo-send"     ,0,0,MODE_LOGO_SEND},
292 {"ring-send"     ,0,0,MODE_RING_SEND},
293 /* Mode aliases may follow in no particular order *
294  * as long as no non-mode options is between them */
295 {"send-md"       ,0,0,MODE_SEND_MOBILDOCK},
296 {"recv"          ,0,0,MODE_RECEIVE},
297 {"logo"          ,0,0,MODE_LOGO_SEND},
298 {"ring"          ,0,0,MODE_RING_SEND},
299 {"config"  ,1,0,'c'},
300 {"device"  ,1,0,'d'},
301 {"log"     ,1,0,'L'},
302 {"baud"    ,1,0,'b'},
303 {"lockfile",1,0,'l'},
304 {"smsc"    ,1,0,'s'},
305 {"maxretry",1,0,'m'},
306 {"readtime",1,0,'r'},
307 {"chartime",1,0,'t'},
308 {"cmdtime" ,1,0,'T'},
309 {"file"    ,0,0,'f'},
310 {"verbose" ,0,0,'v'},
311 {"help"    ,0,0,'h'},
312 {"version" ,0,0,'V'}};
313
314 static void processargs(int argp,char **args,const char *from);
315
316 static char *cfgstack[MAXCFGLOOP];
317 static unsigned cfgstacki=0;
318
319 static void chkfclose(FILE *f,const char *fname)
320 {
321         if (fclose(f))
322                 error("^Error closing \"%s\"",fname);
323 }
324
325 static long getfilesize(FILE *f,const char *fname)
326 {
327 long size;
328
329         if (fseek(f,0,SEEK_END))
330                 error("^Error seeking to end of \"%s\"",fname);
331         if ((size=ftell(f))<0)
332                 size=-1,error("^Error measuring \"%s\"",fname);
333         rewind(f);
334         return(size);
335 }
336
337 static void readfile(const char *fname,char quiet)
338 {
339 FILE *f;
340 size_t got;
341 char *args[MAXCFGARGS],*d,*s,blank,quote;
342 unsigned argp;
343 char *buf;
344 long size;
345 static unsigned tot=0;
346
347         if (tot++>=MAXCFGNUM) {
348                 if (tot==MAXCFGNUM+1) error("Too many config files to read, max is %d, break-out",MAXCFGNUM);
349                 return;
350                 }
351         if (!(f=fopen(fname,"rt"))) {
352                 if (!quiet) error("^Can't open config file \"%s\" for r/o",fname);
353                 return;
354                 }
355                 
356         if (verbose>=2) error(".Reading config file \"%s\"",fname);
357         if ((size=getfilesize(f,fname))==-1) size=0;
358         if (size>MAXCONFIG) 
359                 error("File \"%s\" is too long, read only %d bytes",fname,MAXCONFIG);
360         chk(buf=malloc((size?size:MAXCONFIG)+1));
361         got=fread(buf,1,(size?size:MAXCONFIG),f);
362         if (size && got!=size)
363                 error("File \"%s\" read error, got only %u bytes of %ld",fname,got,size);
364         chkfclose(f,fname);
365         buf[got]='\0';
366         args[0]=pname;
367         for (argp=1,d=s=buf,blank=1,quote=0;s<buf+got;s++) {
368 char c=*s;
369
370                 if (!quote && isspace(c)) {
371                         if (!blank) {
372                                 *d='\0';
373                                 blank=1;
374                                 if (verbose>=2) error("\nConfig \"%s\": arg#%d: %s",fname,argp-1,args[argp-1]);
375                                 }
376                         continue;
377                         }
378                 if (blank) {
379                         if (argp>=NELEM(args)-1) {
380                                 error("Too many arguments in \"%s\", from offset %d ignored",fname,s-buf);
381                                 break;
382                                 }
383                         args[argp++]=s;
384                         d=s;
385                         blank=0;
386                         }
387                 if (c=='\\') { *d++=*++s; continue; }
388                 if (c=='"' || c=='\'') {
389                         if (!quote   ) { quote=c; continue; }
390                         if ( quote==c) { quote=0; continue; }
391                         /* FALLTHRU */
392                         }
393                 *d++=c;
394                 }
395         args[argp]=NULL;
396         processargs(argp,args,fname);
397         free(buf);
398 }
399
400 static struct argstack {
401         struct argstack *next;
402         int num,offset;
403         const char *from;
404         char *arg[1];
405         } *argstack;
406
407 static struct argstack **argstack_tail=&argstack;
408 static size_t lastargstack_len;
409 static const char *lastargstack_from;
410 static int lastargstack_index;
411
412 static size_t argstack_size;
413 static int argstack_num;
414
415 static void pushargstack(char **args,int num,int offset,const char *from,char stack)
416 {
417 struct argstack *as;
418 int i;
419
420         if (!num) return;
421         assert(num>=1);
422         chk(as=malloc(sizeof(*as)+sizeof(as->arg)*(num-1)));
423         as->num=num;
424         as->offset=offset;
425         if (!from) as->from=NULL;
426         else chk(as->from=strdup(from));
427         for (i=0;i<num;i++) {
428                 chk(as->arg[i]=strdup(args[i]));
429                 argstack_size+=strlen(args[i]);
430                 }
431         argstack_num+=num;
432         if (stack) {
433                 as->next=argstack;
434                 argstack=as;
435                 }
436         else {
437                 as->next=NULL;
438                 *argstack_tail=as;
439                 argstack_tail=&as->next;
440                 }
441 }
442
443 static void pushargstack_one(char *s,char stack)
444 { pushargstack(&s,1,0,NULL,stack); }
445
446 static char *nextargstack(void)
447 {
448 static int order=0;
449 char *r;
450
451         if (argstack && order==argstack->num) {
452 struct argstack *as=argstack;
453                 if (!(argstack=as->next))
454                         argstack_tail=&argstack;
455                 order=0;
456                 free((char *)as->from);
457                 lastargstack_from=NULL;
458                 free(as);
459                 }
460         if (!argstack) {
461                 assert(!argstack_num); assert(!argstack_size);
462                 return(NULL);
463                 }
464         assert(order<argstack->num);
465         lastargstack_index=argstack->offset+order;
466         r=argstack->arg[order++];
467         assert(argstack_num>0); argstack_num--;
468         lastargstack_len=strlen(r);
469         assert(argstack_size>=lastargstack_len); argstack_size-=lastargstack_len;
470         lastargstack_from=argstack->from;
471         return(r);
472 }
473
474 static char *glueargstack(size_t *destlenp,const char *glue)
475 {
476 size_t gluel=(glue?strlen(glue):0),destlen;
477 char *dest,*d,*s;
478
479         if (!argstack_num) {
480                 chk(dest=strdup(""));
481                 if (destlenp) *destlenp=0;
482                 return(dest);
483                 }
484         destlen=argstack_size+(argstack_num-1)*gluel;
485         if (destlenp) *destlenp=destlen;
486         chk(dest=malloc(destlen+1));
487         for (d=dest;(s=nextargstack());) {
488                 memcpy(d,s,lastargstack_len);
489                 free(s);
490                 d+=lastargstack_len;
491                 if (!argstack_num) break;
492                 if (!glue) continue;
493                 memcpy(d,glue,gluel);
494                 d+=gluel;
495                 assert(d<=dest+destlen);
496                 }
497         assert(!argstack_num);
498         assert(d==dest+destlen);
499         *d='\0';
500         return(dest);
501 }
502
503 static struct {
504         const char c;
505         char **const var;
506         unsigned stamp;
507         } optset[]={
508                 { 'd',&device   },
509                 { 'L',&logname  },
510                 { 'b',&baud     },
511                 { 'l',&lockfile },
512                 { 's',&smsc     },
513                 { 'm',&maxretry },
514                 { 'r',&readtime },
515                 { 't',&chartime },
516                 { 'T',&cmdtime  },
517         };
518
519 static void processargs(int argp,char **args,const char *from)
520 {
521 int optc;
522 static unsigned seq=0;
523 int i;
524
525         seq++;
526         optarg=NULL; optind=0; /* FIXME: Possible portability problem. */
527         while ((optc=getopt_long(argp,args,"c:d:L:b:l:s:m:r:t:T:fvhV",longopts,NULL))!=EOF) switch (optc) {
528                 case 'c':
529                         if (cfgstacki>=NELEM(cfgstack)) {
530                                 error("Looping (%d) during attempt to read config file \"%s\", break-out",NELEM(cfgstack),from);
531                                 break;
532                                 }
533                         chk(cfgstack[cfgstacki++]=strdup(optarg));
534                         break;
535                 case 'd': case 'L': case 'b': case 'l': case 's': case 'm': case 'r': case 't': case 'T':
536                         for (i=0;i<NELEM(optset);i++)
537                                 if (optset[i].c==optc) {
538                                         if (optset[i].stamp && optset[i].stamp!=seq) {
539                                                 assert(!!*optset[i].var);
540                                                 break;
541                                                 }
542                                         free(*optset[i].var);
543                                         chk(*optset[i].var=strdup(optarg));
544                                         optset[i].stamp=seq;
545                                         break;
546                                         }
547                         assert(i<NELEM(optset));
548                         break;
549                 case MODE_SEND:
550                 case MODE_SEND_MOBILDOCK:
551                 case MODE_RECEIVE:
552                 case MODE_LOGO_SEND:
553                 case MODE_RING_SEND:
554                         if (mode_stamp && mode_stamp!=seq) break;
555                         mode=optc;
556                         mode_stamp=seq;
557                         break;
558                 case 'f':
559                         readbody++;
560                         break;
561                 case 'v':
562                         verbose++;
563                         break;
564                 case 'V':
565                         fprintf(stderr,version);
566                         exit(EXIT_FAILURE);
567                 default:
568                         if (optc!='h')
569                                 error("\nLast getopt(3) error occured during parsing option %d from \"%s\"! Follows help:",optind-1,from);
570                         usage();
571                         break;
572                 }
573         pushargstack(args+optind,argp-optind,optind,from,1);
574         while (cfgstacki) {
575 char *s=cfgstack[--cfgstacki];
576
577                 assert(cfgstacki>=0);
578                 readfile(s,0);
579                 free(s);
580                 assert(cfgstacki>=0 && cfgstacki<NELEM(cfgstack));
581                 }
582 }
583
584 static const struct nullcheck {
585         char **var;
586         enum modenum reqd;
587         const char *name;
588         } nullcheck[]={
589                 {&phone,MODE_BIT(MODE_SEND)|MODE_BIT(MODE_SEND_MOBILDOCK)|MODE_BIT(MODE_LOGO_SEND),
590                         "destination phone number"},
591                 {&logoname,MODE_BIT(MODE_LOGO_SEND),"logo filename"},
592                 {&ringname,MODE_BIT(MODE_RING_SEND),"ring filename"},
593                 {&body,MODE_BIT(MODE_RECEIVE),"body text"}, /* we allow empty bodies for SENDs */
594 #if 0
595                 {&gsmnet,"GSM operator network code",MODE_LOGO_SEND},
596                 {&device,"device for communication",0},
597 #endif
598         };
599 static char **emptycheck[]={&logname,&smsc,&logoname,&gsmnet};
600
601 static inline void emptyclean(void)
602 {
603 int i;
604
605         for (i=0;i<NELEM(emptycheck);i++)
606                 if (*emptycheck[i] && !**emptycheck[i]) {
607                         free(*emptycheck[i]);
608                              *emptycheck[i]=NULL;
609                         }
610 }
611
612 static inline void cmdline_done(void)
613 {
614 char *s;
615         while ((s=nextargstack())) {
616                 error("\nExcessive option %d from \"%s\" ignored: %s",
617                         lastargstack_index,lastargstack_from,s);
618                 free(s);
619                 }
620         emptyclean();
621 }
622
623 static char *check_phone(const char *phone)
624 {
625 const char *s,*s1;
626 static char err[LINE_MAX];
627
628         for (s=s1=(phone+(*phone=='+'));*s && s-s1<MAXNUMLEN;s++)
629                 if (!isdigit(*s)) {
630                         VARPRINTF2(err,"Invalid digit '%c' in phone number - at offset %d",
631                                 *s,s-phone);
632                         return(err);
633                         }
634         if (!*s) return(NULL);
635         VARPRINTF2(err,"Phone number too long (%d), max. %d digits allowed",
636                 strlen(s1),MAXNUMLEN);
637         return(err);
638 }
639
640 static void cmdline_phone(void)
641 {
642         if (!phone && (phone=nextargstack())) {
643 char *s;
644
645                 if ((s=check_phone(phone)))
646                         error("!%s in option %d from \"%s\": %s",
647                                         s,lastargstack_index,lastargstack_from,phone);
648                 }
649 }
650
651 static inline void cmdline_receive(void)
652 {
653 char *s;
654
655         if (!body && argstack_num) {
656                 body=glueargstack(&bodylen," ");
657                 for (s=body;(s=strchr(s,'%'));s++)
658                         switch (*++s) {
659                                 case 'p': case 'T': case 't': break;
660                                 default:
661                                         error("Unknown formatsymbol '%c', use (\"%%%%%c\" to fix it) at pos %d in: %s",
662                                                 *s,*s,s-body,body);
663                                 }
664                 }
665 }
666
667 static inline void cmdline_send(void)
668 {
669         cmdline_phone();
670         if (!body && argstack_num)
671                 body=glueargstack(&bodylen," ");
672 }
673
674 static inline void cmdline_logo_send(void)
675 {
676 char *ogsmnet;
677
678         cmdline_phone();
679         if (!logoname) logoname=nextargstack();
680         if (!gsmnet && (ogsmnet=nextargstack())) {
681 char *s,*d,e=0;
682
683                 chk(gsmnet=strdup(ogsmnet));
684                 if (strtrycasecmp(gsmnet,WORD_NET) && strtrycasecmp(gsmnet,WORD_GROUP)) {
685                         for (d=s=gsmnet;*s;s++) {
686                                 if (isdigit(*s)) { *d++=*s; continue; }
687                                 if (isspace(*s)) continue;
688                                 error("\nInvalid characted '%c' in GSMnet at offs %d: %s",
689                                         *s,s-gsmnet,ogsmnet);
690                                 e=1;
691                                 break;
692                                 }
693                         if ((d-gsmnet)!=5) {
694                                 error("\nGSMnet is required to have exactly 5 digits or to be\n\
695 either \"" WORD_NET "\" or \"" WORD_GROUP "\", but found length %d: %s",
696                                         d-gsmnet,ogsmnet);
697                                 e=1;
698                                 }
699                         if (!e) *d='\0';
700                         else {
701                                 error("\nGSMnet option %d from \"%s\" rejected due to previous errors: %s",
702                                         lastargstack_index,lastargstack_from,ogsmnet);
703                                 free(gsmnet);
704                                 gsmnet=NULL;
705                                 }
706                         }
707                 }
708 }
709
710 static inline void cmdline_ring_send(void)
711 {
712         cmdline_phone();
713         if (!ringname) ringname=nextargstack();
714 }
715
716 static void lockclose(int fd)
717 {
718         if (close(fd))
719                 error("Error closing lockfile \"%s\"",lockreal);
720 }
721
722 static inline int lockdevice(int attempt)
723 {
724 int fd=-1;
725 char buf[64];
726 ssize_t got;
727 int delay=0;
728 char empty=0;
729 pid_t pid;
730
731         d2("lockdevice(), locked=%d\n",locked);
732         if (locked) return (++locked);
733         for (;;) {
734                 if (fd!=-1) lockclose(fd);
735 recheck:
736                 if (delay) sleep(delay);
737                 delay=DEVLOCK_PERIOD;
738                 if (verbose>=3) error(".Checking the lockfile \"%s\"..",lockreal);
739                 if ((fd=open(lockreal,O_RDONLY))==-1) break;
740                 if ((got=read(fd,buf,sizeof(buf)-1))<=0) {
741 isempty:
742                         if (empty>=DEVLOCK_MAXEMPTY) {
743                                 error(".Lockfile \"%s\" is still not valid, removing it",lockreal);
744                                 goto remove;
745                                 }
746                         empty++;
747                         continue;
748                         }
749                 assert(got<sizeof(buf));
750                 buf[got]='\0';
751                 if (sscanf(buf,"%d",&pid)!=1) goto isempty;
752                 empty=0;
753                 errno=0;
754                 if (kill(pid,0) && errno!=ESRCH && errno!=EPERM)
755                         error("^Error during checking consciousness of PID %d",pid);
756                 if (errno!=ESRCH) {
757                         if (attempt) return(0);
758                         continue;
759                         }
760                 error(".Lockfile \"%s\" is stale (PID %d), removing it",lockreal,pid);
761 remove:
762                 lockclose(fd);
763                 if (unlink(lockreal))
764                         error("^Error removing foreign lockfile \"%s\"",lockreal);
765                 break;
766                 }
767         errno=0;
768         if ((fd=open(lockreal,O_WRONLY|O_CREAT|O_EXCL,0644))==-1) {
769                 if (errno==EEXIST) goto recheck;
770                 error("^!Error creating lockfile \"%s\"",lockreal);
771                 }
772         locked=1;
773         got=VARPRINTF(buf,"%010d\n",getpid()); assert(got==11);
774         if (write(fd,buf,got)!=got)
775                 error("^!Error writing data to lockfile \"%s\"",lockreal);
776         lockclose(fd);
777         return((locked=1));
778 }
779
780 static char wasalarm=0;
781 static void sigalarm(int signo);
782
783 static void setalarm(void)
784 {
785         signal(SIGALRM,(RETSIGTYPE (*)(int))sigalarm);
786 #ifdef HAVE_SIGINTERRUPT
787         siginterrupt(SIGALRM,1);
788 #endif
789 }
790
791 static void sigalarm(int signo)
792 {
793         setalarm();
794         wasalarm=1;
795         if (verbose>=1) error("Timed out");
796 }
797
798 static void blocking(char yes)
799 {
800 static char state=-1;
801         if (state==yes) return;
802         if (fcntl(devfd,F_SETFL,(yes?0:O_NONBLOCK)))
803                 error("^!fcntl() on device for %sblocking mode",(yes?"":"non-"));
804         state=yes;
805 }
806
807 static const char *record;
808 static char *catchdata;
809 static size_t catchdatal,catchdatasiz;
810
811 static void catched(const char *end,char edata)
812 {
813 size_t len;
814 const char *p;
815
816         if (!record) return;
817         assert(end>=record);
818         p=memchr(record,edata,end-record);
819         if ((len=(p?p:end)-record)) {
820                 if (!catchdata)
821                         chk(catchdata=malloc((catchdatasiz=LINE_MAX)));
822                 if (catchdatal+len>catchdatasiz)
823                         chk(catchdata=realloc(catchdata,
824                                 (catchdatasiz=(catchdatal+len)*2)));
825                 memcpy(catchdata+catchdatal,record,len);
826                 catchdatal+=len;
827                 }
828         record=(p?NULL:end);
829         assert(catchdatal<=catchdatasiz);
830 }
831
832 static int retrycnt=0;
833 static void retrying(void)
834 {
835         if (maxretryn>=0 && ++retrycnt>maxretryn) error("!Maximum command retry count (%ld) exceeded",maxretryn);
836         if (verbose>=2) error(".Retrying phase, %d out of %ld..",retrycnt,maxretryn);
837 }
838
839 static char *reform(const char *s,int slot)
840 {
841 static struct formslot {
842         char *s;
843         size_t l;
844         } arr[3];
845 char c,*d;
846 struct formslot *fs;
847
848         assert(slot>=0 && slot<NELEM(arr));
849         if (!s) return("<unset>");
850         if (!(fs=&arr[slot])->s)
851                 chk(fs->s=malloc(fs->l=LINE_MAX));
852         d=fs->s;
853         for (*d++='"';(c=*s);s++) {
854                 if (d>=fs->s+fs->l-10) {
855 off_t o=d-fs->s;
856                         chk(fs->s=realloc(fs->s,(fs->l=(fs->l?fs->l*2:LINE_MAX))));
857                         d=fs->s+o;
858                         }
859                 if (c!='\\' && c!='"' && isprint(c)) { *d++=c; continue; }
860                 *d++='\\';
861                 switch (c) {
862                         case '\\': case '"': *d++=c; break;
863                         case '\n': *d++='n'; break;
864                         case '\r': *d++='r'; break;
865                         case '\032': *d++='Z'; break;
866                         case '\033': *d++='e'; break;
867                         default:
868                                 d+=sprintf(d,"x%02X",(unsigned char)c);
869                                 break;
870                         }
871                 }
872         *d++='"'; *d='\0';
873         return(fs->s);
874 }
875
876 static char *devcmd(const char *term,const char *catch,const char *send,...) ATTR_PRINTFORMAT(3,4);
877 static char *devcmd(const char *term,const char *catch,const char *send,...)
878 {
879 size_t l,bufl2,terml,catchl=0 /* GCC happiness */,fragl,offs;
880 static char buf[LINE_MAX];
881 static size_t bufl;
882 ssize_t got;
883 char *hit,*s;
884 va_list ap;
885 char errout,extend,noconvcr,edata;
886 long alarmtime;
887 const char *osend;
888 static const char emptystring[]="";
889
890         if (!term) term="\nOK\n";
891         if (!strcmp(send," ")) send=NULL; /* GCC formatstring-check workaround */
892         if (!(osend=send)) send="";
893         if ((noconvcr=(catch && *catch=='@'))) catch++;
894         if ((errout=(*send=='!'))) send++;
895         errout|=(maxretryn==-1);
896         if ((extend=(*send=='~'))) send++;
897         alarmtime=readtimen*(extend?EXT_READTIME:1);
898         d8("devcmd(), alarmtime=%ld, errout=%d, extend=%d, noconvcr=%d, osend=%p, bufl=%d, buf: %s\n",
899                 alarmtime,errout,extend,noconvcr,osend,bufl,reform(buf,0));
900         if (0) {
901 err:
902                 alarm(0);
903                 if (errout) return(NULL);
904                 retrying();
905                 }
906         catchdatal=0;
907         if (osend) {
908                 bufl=0;
909                 d1("Resetting bufl.\n");
910                 va_start(ap,send);
911                 l=VARVPRINTF(buf,send,ap); bufl=l+(!!osend);
912                 va_end(ap);
913                 if (bufl>=sizeof(buf)-1) error("!Command too big (%d>%d)",bufl,sizeof(buf)-1);
914                 if (verbose>=2) error(".devcmd(send=%s,term=%s,catch=%s,timeout=%ld)",
915                         reform(buf,0),reform(term,1),reform(catch,2),alarmtime);
916                 if (osend) buf[l]='\r';
917                 for (offs=0,got=0;offs<bufl;offs++) {
918                         alarm(MAXSENDTIME);
919                         usleep((offs?chartimen:cmdtimen)*1000);
920                         if (!offs && tcflush(devfd,TCIOFLUSH))
921                                 error("^Error flushing I/O queue of device");
922                         if (write(devfd,buf+offs,1)!=1) break;
923                         got++;
924                         if (tcdrain(devfd))
925                                 error("^Error forcing output of char at pos %d of cmd %s",offs,reform(buf,0));
926                         }
927                 alarm(0);
928                 if (got!=bufl) {
929                         error("^Wrote only %d of %d bytes of command",got,bufl);
930                         goto err;
931                         }
932                 }
933
934         if (!(terml=strlen(term))) {
935                 assert(!catch);
936                 return(NULL);
937                 }
938         if (catch) {
939                 catchl=strlen(catch);
940                 fragl=MAX(terml,catchl);
941                 }
942         else fragl=terml;
943         fragl=MAX(fragl,MAX(strlen(ERROR_SUBSTR1),strlen(ERROR_SUBSTR2)));
944         record=NULL;
945         wasalarm=0;
946         alarm(alarmtime);
947         edata=(noconvcr?'\r':'\n');
948         if (!osend) {
949                 got=bufl;
950                 bufl=0;
951                 goto skipread;
952                 }
953         for (;;) {
954                 blocking(0);
955                 errno=0;
956                 got=read(devfd,buf+bufl,sizeof(buf)-1-bufl);
957                 if (got==-1 && errno==EAGAIN) {
958                         blocking(1);
959                         errno=0;
960                         got=read(devfd,buf+bufl,1);
961                         }
962                 if (got<=0) {
963                         if (wasalarm) error("Maximum response timeout (%lds) exceeded",alarmtime);
964                         else error("^Couldn't read device data (ret=%d)",got);
965                         goto err;
966                         }
967 skipread:
968                 bufl2=bufl+got;
969                 buf[bufl2]='\0';
970                 s=buf+bufl;
971                 while (buf+bufl2>s && (s=memchr(s,'\0',buf+bufl2-s))) *s++=REPL_NULLCHAR;
972                 if (verbose>=3)
973                         error("\nGot chunk of data from device: %s",reform(buf+bufl,0));
974                 if (!noconvcr) {
975                         s=buf+bufl;
976                         while (buf+bufl2>s && (s=memchr(s,'\r',buf+bufl2-s))) *s++='\n';
977                         }
978                 bufl=bufl2;
979                 catched(buf+bufl,edata); assert(!record || record==buf+bufl);
980                 assert(bufl<sizeof(buf)-1);
981                 buf[bufl]='\0';
982                 assert(strlen(buf)==bufl);
983                 /* d3(">%s|%s<\n",buf,term); */
984                 if (strstr(buf,ERROR_SUBSTR1) || strstr(buf,ERROR_SUBSTR2)) {
985                         error("Found ERROR response on command %s",reform(send,0));
986                         goto err;
987                         }
988                 if (catch && !record && bufl>=catchl && (hit=strstr(buf,catch))) {
989                         record=hit+catchl;
990                         catched(buf+bufl,edata); assert(!record || record==buf+bufl);
991                         }
992                 if (         bufl>= terml && (hit=strstr(buf,term))) {
993                         memmove(buf,hit+terml,(bufl2=(buf+bufl)-(hit+terml))); bufl=bufl2;
994                         break;
995                         }
996                 if (bufl<fragl) continue;
997                 memmove(buf,buf+bufl-(fragl-1),(bufl2=fragl-1)); bufl=bufl2;
998                 if (record) record=buf+fragl-1;
999                 }
1000         alarm(0);
1001         if (!catchdatal) {
1002                 if (!catch) return("");
1003                 error("Data requested on command %s but no found after term %s",reform(send,0),reform(term,1));
1004                 goto err;
1005                 }
1006         assert(!!catch);
1007         record=emptystring;
1008         catched(record+1,edata);
1009         if (verbose>=2) error(".Returning data %s for cmd %s",reform(catchdata,0),reform(send,1));
1010         return(catchdata);
1011 }
1012
1013 static int prepaddr(unsigned char *d,const char *addr)
1014 {
1015 int tot=0;
1016 char flip=0,plus;
1017 unsigned char n;
1018
1019         if ((plus=(*addr=='+'))) addr++;
1020         *++d=(plus?ADDR_INT:ADDR_NAT);
1021         while (*addr) {
1022                 if (*addr<'0' || *addr>'9')
1023                         error("!Error during conversion of number at: %s",addr);
1024                 tot++;
1025                 n=(*addr++)-'0';
1026                 if ((flip=!flip)) *++d=0xF0|n;
1027                 else *d=(*d&0x0F)|(n<<4U);
1028                 }
1029         return(tot);
1030 }
1031
1032 static char *finalsmsc;
1033 #define SMSCBINSIZE (1+1+(MAXNUMLEN+1)/2)
1034 static char pdusmsc[SMSCBINSIZE*2+1];
1035
1036 static inline char tohex(unsigned char x)
1037 {
1038         x&=0x0F;
1039         if (x<10) return(x   +'0');
1040                   return(x-10+'A');
1041 }
1042
1043 static inline void textconv(char *d,unsigned char *s,size_t len)
1044 {
1045         while (len--) {
1046                 *d++=tohex(*s>>4U);
1047                 *d++=tohex(*s    );
1048                 s++;
1049                 }
1050         *d='\0';
1051 }
1052
1053 static inline void smscset(void)
1054 {
1055 char *s,*t,*e,*serr;
1056 long l;
1057 unsigned char bin[2+(MAXNUMLEN+1)/2];
1058
1059         if (smsc) devcmd(NULL,NULL,"\r\nAT+CSCA=\"%s\"",smsc);
1060         s=devcmd(NULL,"\n+CSCA:","\r\nAT+CSCA?");
1061         while (isspace(*s)) s++;
1062         if (!*s || !strcmp(s,"EMPTY"))
1063                 error("!No SMS set in mobile station found, please use option \"-s\"");
1064         if (verbose>=1) error("\nFound default SMSC in mobile: %s",s);
1065         if (*s!='"') error("!No left-quote found in: %s",s);
1066         if (!(t=strrchr(s+1,'"'))) error("!No right-quote found in: %s",s);
1067         if (s+1==t)
1068                 error("!No SMS set in mobile station found, please use option \"-s\"");
1069         e=t++;
1070         while (isspace(*t)) t++;
1071         if (*t++!=',') error("!No comma found after quotes in: %s",s);
1072         while (isspace(*t)) t++;
1073         l=strtol(t,&serr,10);
1074         if ((l!=ADDR_NAT && l!=ADDR_INT) || (serr && *serr))
1075                 error("!Type parse error in: %s",s);
1076         if (l==ADDR_NAT || s[1]=='+') s++;
1077         else *s='+';
1078         *e='\0';
1079         if (verbose>=2) error("\nDecoded SMSC address: %s",s);
1080         if (!NEED_PDUSMSC()) return;
1081         chk(finalsmsc=strdup(s));
1082         bin[0]=1+(prepaddr(bin,finalsmsc)+1)/2;
1083         textconv(pdusmsc,bin,bin[0]+1);
1084 }
1085
1086 static inline unsigned char charconv(char c,size_t offs)
1087 {
1088         switch (c) {
1089                 case '@': return(0);
1090                 case '$': return(2);
1091                 case 0: assert(0);
1092                 default:
1093                         return(c&0x7F);
1094                 }
1095 #if 0
1096         if ((c>='A' && c<='Z') || (c>='a' && c<='z') || (c>='0' && c<='9')) return(c);
1097         error("Can't convert character '%c' (0x%02X) at offs %d (0-based), substituted '?'",
1098                 c,(unsigned char)c,offs);
1099         return('?');
1100 #endif
1101 }
1102
1103 /* Logo format shamelessly stolen from GNokii-0.3.0: http://www.gnokii.org/
1104  * Beware - Nokia Smart Messaging specification 1.0.0 and 2.0.0 is incompatible
1105  * with Nokia current product line implementation
1106  * http://www.forum.nokia.com/developers/smartmsg/download/ssm2_0_0.pdf
1107  */
1108
1109 static char *pdudata;
1110 static struct hexdata {
1111         struct hexdata *next;
1112         char data[140*2+1];
1113         } *hexdata,**hexdatatail=&hexdata;
1114
1115 static void nokiaprep(unsigned char *bin,size_t w)
1116 {
1117 struct hexdata *hd;
1118         assert(w<=140);
1119         chk(hd=malloc(sizeof(*hd)));
1120         *hexdatatail=hd;
1121         hd->next=NULL;
1122         hexdatatail=&hd->next;
1123         textconv(hd->data,bin,w);
1124         if (verbose>=2) error("\nWill send hexdata: %s",hd->data);
1125 }
1126
1127 static inline void logoread(void)
1128 {
1129 FILE *f;
1130 char buf[32+140*8+1];
1131 unsigned char bin[140]={
1132         0x06, /* UDH length */
1133         0x05, /* IEI */
1134         0x04, /* IEDL */
1135         0x15, 0x83, /* dest port (group gfx) */
1136         0x00, 0x00  /* src port (unused) */
1137         };
1138 size_t got,r=0 /* GCC happiness */,w;
1139 ssize_t chars,bits;
1140 char gsmnetf[10];
1141 int sizex,sizey,bit;
1142
1143 #define WORD(n) (((unsigned char)buf[(n)])|(((unsigned char)buf[(n)+1])<<8))
1144
1145         if (!(f=fopen(logoname,"rb")))
1146                 error("^!Cannot open logo file \"%s\" for r/o",logoname);
1147         got=fread(buf,1,sizeof(buf),f);
1148         chkfclose(f,logoname);
1149              if (got>=20 && !memcmp(buf,"NOL",4)) {
1150                 VARPRINTF2(gsmnetf,"%03.3u%02.2u",WORD(6),WORD(8));
1151                 assert(strlen(gsmnetf)==5);
1152                 r=10;
1153                 if (verbose>=1) error(".Reading NOL file \"%s\", GSMnet \"%s\", word@4=%d..",
1154                         logoname,gsmnetf,WORD(4));
1155                 }
1156         else if (got>=16 && !memcmp(buf,"NGG",4)) {
1157                 r=6;
1158                 if (verbose>=1) error(".Reading NGG file \"%s\", word@4=%d..",
1159                         logoname,WORD(4));
1160                 }
1161         else error("!Unknown file format of logo file \"%s\"",logoname);
1162         if (gsmnet && !strtrycasecmp(gsmnet,WORD_NET)) {
1163                 if (!*gsmnetf) error("!NOL network code detection requested but NOL file not loaded, please specify network code");
1164                 gsmnet=gsmnetf;
1165                 }
1166         if (!gsmnet || !strtrycasecmp(gsmnet,WORD_GROUP) || !*gsmnet) {
1167                 error("\nSending logo as: group graphics");
1168                 gsmnet=NULL;
1169                 }
1170         else {
1171                 error("\nSending logo as: operator logo for \"%s\"",gsmnet);
1172                 bin[4]=0x82; /* dest port 0x1582 */
1173                 }
1174         
1175         sizex=WORD(r); sizey=WORD(r+2);
1176         if (verbose>=2) error(".Magic words: @+4=%d, @+6=%d, @+8=%d",
1177                         WORD(r+4),WORD(r+6),WORD(r+8));
1178         r+=10;
1179         if (sizex<1 || sizex>255
1180          || sizey<1 || sizey>255) error("!Invalid size: %dx%d",sizex,sizey);
1181         chars=((bits=sizex*sizey)+7)/8;
1182         if (r+bits>got) error("!Logo file \"%s\" too short - actual=%d, need(%dx%d)=%d",
1183                 logoname,got,sizex,sizey,r+chars);
1184         else if (r+bits<got)
1185                 if (verbose>=1) error("Ignoring trailing garbage in \"%s\", used only %d bytes",logoname,r+bits);
1186         if ((got=(7+(gsmnet?3:0)+4+chars))>140)
1187                 error("!SMS size would be %d bytes but 140 is maximum",got);
1188         w=7;
1189         if (gsmnet) {
1190                 bin[w++]=((gsmnet[1]&0x0F)<<4)|(gsmnet[0]&0x0F);
1191                 bin[w++]=0xF0                 |(gsmnet[2]&0x0F);
1192                 bin[w++]=((gsmnet[4]&0x0F)<<4)|(gsmnet[3]&0x0F);
1193                 }
1194         bin[w++]=0x00; /* RFU by Nokia */
1195         bin[w++]=sizex; bin[w++]=sizey;
1196         bin[w++]=0x01; /* one B/W plane */
1197         while (chars--) {
1198                 bin[w]=0;
1199                 for (bit=0x80;(bits>0) && (bit>0);bits--,bit>>=1) {
1200                         if (buf[r]!='0' && buf[r]!='1')
1201                                 error("!Invalid character (neither '0' nor '1')in logo file \"%s\" at offset 0x%X",
1202                                         logoname,r);
1203                         if (buf[r++]=='1') bin[w]|=bit;
1204                         }
1205                 w++;
1206                 }
1207         assert(chars==-1); assert(bits==0); assert(w==got);
1208         nokiaprep(bin,w);
1209 #undef WORD
1210 }
1211
1212 static inline void ringread(void)
1213 {
1214 FILE *f;
1215 unsigned char bin1[140]={
1216         6, /* UDH length */
1217         0x05, /* IEI */
1218         0x04, /* IEDL */
1219         0x15, 0x81, /* dest port (ring tones) */
1220         0x15, 0x81  /* src port (unused) */
1221 #define BIN1_PAYLOAD (140-7)
1222         };
1223 unsigned char binn[140]={
1224         11, /* UDH length */
1225         0x05, /* IEI */
1226         0x04, /* IEDL */
1227         0x15, 0x81, /* dest port (ring tones) */
1228         0x15, 0x81, /* src port (unused) */
1229         0x00, 0x03, /* multipart */
1230         /* 0x??, unique serial ID */
1231         /* 0x??, total messages */
1232         /* 0x??, message number (# from 1) */
1233 #define BINN_PAYLOAD (140-12)
1234         };
1235 size_t got,want;
1236 int totn,fragn;
1237 long size;
1238
1239 #define WORD(n) (((unsigned char)buf[(n)])|(((unsigned char)buf[(n)+1])<<8))
1240
1241         if (!(f=fopen(logoname,"rb")))
1242                 error("^!Cannot open logo file \"%s\" for r/o",logoname);
1243         if ((size=getfilesize(f,logoname))==-1)
1244                 error("!File size is essential to continue operation");
1245         if (size<0x103)
1246                 error("!File \"%s\" size %ld too small (must >=0x103)! Is it .000 file?",
1247                         logoname,size);
1248         if (fseek(f,0x100,SEEK_SET))
1249                 error("^Seeking error on \"%s\", ignoring",logoname);
1250         size-=0x100;
1251         if (size<=BIN1_PAYLOAD) {
1252                 if ((got=fread(bin1+7,1,size,f))!=size)
1253                         error("^Read error on \"%s\", wanted %ld, got %d",logoname,size,got);
1254                 error("\nSending ring tone \"%s\" as single SMS (size %ld, max %d)",
1255                         ringname,size,BIN1_PAYLOAD);
1256                 nokiaprep(bin1,7+size);
1257                 }
1258         else {
1259                 totn=(size+BINN_PAYLOAD-1)/BINN_PAYLOAD;
1260                 if (totn>0xFF)
1261                         error("!File size %ld too large for multi-SMS ring upload (max=%d)",
1262                                 size,BINN_PAYLOAD*0xFF);
1263                 binn[10]=totn;
1264                 if (verbose>=1)
1265                         error("\nSending ring tone \"%s\" as %d multi-SMSes (size %ld, max %d, frag %d)",
1266                                 ringname,totn,size,BIN1_PAYLOAD,BINN_PAYLOAD);
1267                 binn[9]=time(NULL)&0x100; /* rand() would be better but it is a compatibility pain */
1268                 if (verbose>=1)
1269                         error("\nUsing unique multi-SMS ID 0x%02X",(unsigned)binn[9]);
1270                 for (fragn=1;fragn<=totn;fragn++) {
1271                         binn[11]=fragn;
1272                         want=MIN(size,BINN_PAYLOAD);
1273                         if ((got=fread(binn+12,1,want,f))!=want)
1274                                 error("^Read error on \"%s\", wanted %d, got %d",logoname,want,got);
1275                         nokiaprep(binn,12+want);
1276                         size-=want;
1277                         }
1278                 }
1279         chkfclose(f,logoname);
1280 #undef WORD
1281 }
1282
1283 static inline void genpdu(void)
1284 {
1285 static unsigned char pdu[64+MAXNUMLEN/2+(MAXBODYLEN*7)/8];
1286 unsigned char *d=pdu;
1287 int i;
1288 char inb=0,outb=0,xb,*bodyr;
1289 unsigned char inreg=0 /* GCC happiness */;
1290 size_t offs=0;
1291
1292         *d++=PDU_TYPE;
1293         *d++=PDU_MR;
1294         i=prepaddr(d,phone);
1295         *d=i; d+=1+1+(i+1)/2;
1296         *d++=PDU_PID;
1297         *d++=PDU_DCS;
1298         *d++=PDU_VP;
1299         if (bodylen>MAXBODYLEN) {
1300                 error("Body too large (%d>%d), cut",bodylen,MAXBODYLEN);
1301                 body[(bodylen=MAXBODYLEN)]='\0';
1302                 }
1303         bodyr=body;
1304         *d=bodylen;
1305         assert(d<pdu+sizeof(pdu));
1306         while (bodylen || inb) {
1307                 if (!inb) {
1308                         assert(bodylen>0); assert(!!*body);
1309                         inreg=charconv(*bodyr++,offs++);
1310                         bodylen--;
1311                         inb=7;
1312                         }
1313                 if (!outb) {
1314                         *++d=0x00;
1315                         outb=8;
1316                         }
1317                 xb=MIN(inb,outb);
1318 #if 0
1319                 d4("inb=%d,outb=%d,xb=%d\n",inb,outb,xb);
1320 #endif
1321                 *d|=((inreg>>(unsigned)(7-inb))&((1<<xb)-1))<<(unsigned)(8-outb);
1322                 inb-=xb; outb-=xb;
1323                 }
1324         d++;
1325         assert(d<pdu+sizeof(pdu));
1326         pdudata=malloc(2*(d-pdu)+1);
1327         textconv(pdudata,pdu,d-pdu);
1328 }
1329
1330 static inline void preparebody(void)
1331 {
1332 FILE *fin=NULL /* GCC happiness */;
1333 char *finame;
1334
1335         if (body && readbody) {
1336                 finame=body;
1337                 body=NULL;
1338                 }
1339         else {
1340                 finame=NULL;
1341                 fin=stdin;
1342                 }
1343         if (body) return;
1344         readbody=0;
1345         if (!finame) {
1346                 if (verbose>=1)
1347                         error("\nPlease enter the SMS text body, end with EOF (ctrl-D):");
1348                 }
1349         else {
1350                 if (!(fin=fopen(finame,"rt")))
1351                         error("^!Can't open data file \"%s\" for r/o",finame);
1352                 }
1353         chk(body=malloc(BODYLOAD));
1354         bodylen=fread(body,1,BODYLOAD,fin);
1355         if (bodylen==-1)
1356                 error("^!Error reading stream \"%s\"",(finame?finame:"<stdin>"));
1357         if (finame) {
1358                 chkfclose(fin,finame);
1359                 free(finame);
1360                 }
1361 }
1362
1363 static int datawait(char immed)
1364 {
1365 int i;
1366 #ifdef HAVE_POLL
1367 struct pollfd ufd;
1368 #else /* HAVE_POLL */
1369 fd_set rfds,xfds;
1370 #endif /* HAVE_POLL */
1371
1372         assert(devfd>=0);
1373 retry:
1374         errno=0;
1375
1376 #ifdef HAVE_POLL
1377         ufd.fd=devfd;
1378         ufd.events=POLLIN;
1379         ufd.revents=0;
1380         i=poll(&ufd,1,(immed?0:-1));
1381 #else /* HAVE_POLL */
1382 #ifdef HAVE_FD_SETSIZE
1383         if (devfd>=FD_SETSIZE)
1384                 error("!Device file descriptor %d can't fit in select() FD_SETSIZE (%d)",
1385                         devfd,FD_SETSIZE);
1386 #endif /* HAVE_FD_SETSIZE */
1387         FD_ZERO(&rfds); FD_SET(devfd,&rfds);
1388         FD_ZERO(&xfds); FD_SET(devfd,&xfds);
1389         i=select(devfd+1,&rfds,NULL,&xfds,NULL);
1390 #endif /* HAVE_POLL */
1391         if (immed && i==0) return(0);
1392         if (i!=1)
1393                 error("^Failed (retval %d) while waiting for data, ignoring",i);
1394
1395 #ifdef HAVE_POLL
1396         if (ufd.revents&(POLLERR|POLLHUP))
1397 #else /* HAVE_POLL */
1398         if (FD_ISSET(devfd,&xfds))
1399 #endif /* HAVE_POLL */
1400                 error("^Error while waiting for data, ignoring");
1401
1402 #ifdef HAVE_POLL
1403         if (!(ufd.revents&POLLIN))
1404 #else /* HAVE_POLL */
1405         if (!(FD_ISSET(devfd,&rfds)))
1406 #endif /* HAVE_POLL */
1407                 {
1408                 error("^No data input after waited for data, retrying");
1409                 goto retry;
1410                 }
1411         return(1);
1412 }
1413
1414 static char *check_format(const char *fmt,const char *string)
1415 {
1416 static char err[LINE_MAX],sub[50];
1417 char *subp,cf,cs;
1418 const char *sf,*ss;
1419
1420         for (sf=fmt,ss=string;(cf=*sf) && (cs=*ss);sf++,ss++) {
1421                 subp=NULL;
1422                 switch (cf) {
1423                         case '?':
1424                                 break;
1425                         case '9':
1426                                 if (isdigit(cs)) break;
1427                                 subp="digit";
1428                                 break;
1429                         case '+':
1430                                 if (cs=='+' || cs=='-') break;
1431                                 subp="+/- sign";
1432                                 break;
1433                         default:
1434                                 if (cf==cs) break;
1435                                 VARPRINTF(sub,"'%c'",cf); subp=sub;
1436                         }
1437                 if (!subp) continue;
1438                 VARPRINTF5(err,"Expected %s, found '%c' at pos %d of string [%s], formatstring [%s]",
1439                         subp,cs,ss-string,string,fmt);
1440                 return(err);
1441                 }
1442         if (*sf) {
1443                 VARPRINTF2(err,"String too short for format, string [%s], formatstring [%s]",
1444                         string,fmt);
1445                 return(err);
1446                 }
1447         if (*ss) {
1448                 VARPRINTF2(err,"Trailing garbage in string [%s], formatstring [%s]",
1449                         string,fmt);
1450                 return(err);
1451                 }
1452         return(NULL);
1453 }
1454
1455 static char *receive_number;
1456 static time_t receive_time;
1457
1458 /* +CMT: "+420602431329",,"99/10/25,03:21:03-00" */
1459 static int receive_headerparse(char *buf)
1460 {
1461 char *s,*s1,*err;
1462 struct tm tm;
1463 static const struct {
1464         off_t strpos;
1465         off_t tmpos;
1466         int min,max;
1467         const char *name;
1468         } timeparse[]={
1469 #define TP_ENT(a,b,c,d,e) { a,offsetof(struct tm,b),c,d,e }
1470                 TP_ENT( 3,tm_year,0,99,"year"),
1471                 TP_ENT( 6,tm_mon ,1,12,"month"),
1472                 TP_ENT( 9,tm_mday,1,31,"day of month"),
1473                 TP_ENT(12,tm_hour,0,23,"hour"),
1474                 TP_ENT(15,tm_min ,0,59,"minute"),
1475                 TP_ENT(18,tm_sec ,0,59,"second"),
1476                 /* Time zone ignored */
1477                 };
1478 int i,val;
1479
1480 #define DIGIT2(s) (((s)[0]-'0')*10+((s)[1]-'0'))
1481
1482         for (s=buf;*s==' ';s++);
1483         if (*s++!='"') {
1484                 error("Cannot find initial '\"' in CMT header: %s",buf);
1485                 return(0);
1486                 }
1487         for (s1=s;*s && *s!='"';s++);
1488         if (!*s) {
1489                 error("Only one '\"' found in CMT header: %s",buf);
1490                 return(0);
1491                 }
1492         free(receive_number);
1493         chk(receive_number=malloc(s-s1+1));
1494         memcpy(receive_number,s1,s-s1); receive_number[s-s1]='\0';
1495         s++;
1496         if ((err=check_phone(receive_number)) ||
1497             (err=check_format(",,\"99/99/99,99:99:99+99\"",s))) {
1498                 error("%s in CMT header: %s",err,buf);
1499                 return(0);
1500                 }
1501         memset(&tm,0,sizeof(tm)); /* may be redundant */
1502         for (i=0;i<NELEM(timeparse);i++) {
1503                 val=DIGIT2(s+timeparse[i].strpos);
1504                 if (val<timeparse[i].min || val>timeparse[i].max) {
1505                         error("Weird value of %s, is %d but expected %d..%d, setting to %d",
1506                                 timeparse[i].name,val,timeparse[i].min,timeparse[i].max,timeparse[i].min);
1507                         val=timeparse[i].min;
1508                         }
1509                 *(int *)(((char *)&tm)+timeparse[i].tmpos)=val;
1510                 }
1511         if (tm.tm_year<70) tm.tm_year+=100;
1512         tm.tm_mon--;
1513         d7("mktime(y%dm%dd%dh%dm%ds%d)\n",
1514                 tm.tm_year,tm.tm_mon,tm.tm_mday,tm.tm_hour,tm.tm_min,tm.tm_sec);
1515         if ((receive_time=mktime(&tm))==-1) {
1516                 error("^mktime(3) failed for %s",s+2);
1517                 return(0);
1518                 }
1519         return(1);
1520 #undef DIGIT2
1521 }
1522
1523 static void receive_accept(char *bodyline)
1524 {
1525 char *buf,*s,*s1,*s2,*s3;
1526 pid_t pid;
1527 char tbuf[32];
1528 int i;
1529 FILE *f;
1530
1531         d2("receive_accept: %s\n",bodyline);
1532 #if RECEIVE_TEST
1533         pid=0;
1534 #else
1535         pid=fork();
1536 #endif
1537         if (pid>0) return; /* parent context */
1538         if (pid==-1) {
1539                 error("Can't fork(2), process spawning may block receive");
1540                 }
1541         else { /* child process */
1542                 dis_cleanup=1;
1543                 }
1544         for (s=body;*s;) {
1545                 s1=s;
1546                 do {
1547                         s1=strchr(s1+(s1!=s),'%');
1548                         } while (s1 && s1[1]!='p' && s1[1]!='T' && s1[1]!='t');
1549                 if (!s1) {
1550                         pushargstack_one(s,0);
1551                         break;
1552                         }
1553                 *s1='\0';
1554                 pushargstack_one(s,0);
1555                 *s1++='%';
1556                 s=s1;
1557                 switch (*s++) {
1558                         case 'p':
1559                                 pushargstack_one(receive_number,0);
1560                                 break;
1561                         case 'T':
1562                                 VARPRINTF(tbuf,"%ld",receive_time);
1563                                 pushargstack_one(tbuf,0);
1564                                 break;
1565                         case 't':
1566                                 if (!(s2=ctime(&receive_time))) {
1567                                         error("Failing ctime(3), ignoring substitution");
1568                                         break;
1569                                         }
1570                                 if ((s3=strchr(s2,'\n'))) *s3='\0';
1571                                 pushargstack_one(s2,0);
1572                                 break;
1573                         default: assert(0);
1574                         }
1575                 }
1576         buf=glueargstack(NULL,NULL); assert(buf);
1577         if (!(f=popen(buf,"w"))) {
1578                 error("^Failing spawn of receive command: %s",buf);
1579                 goto err;
1580                 }
1581         if (fputs(bodyline,f)<0 || putc('\n',f)!='\n')
1582                 error("^Failing write to child receive command: %s",buf);
1583         if ((i=pclose(f)))
1584                 error("^Spawned receive command failure (code %d): %s",i,buf);
1585 err:
1586         free(buf);
1587         if (pid==-1) return;
1588         exit(EXIT_SUCCESS); /* cleanup() has been disabled */
1589 }
1590
1591 static struct {
1592         char **sp;
1593         long *ip;
1594         const char *const msg;
1595         } numarg[]={
1596                 { &maxretry,&maxretryn,"maxretry" },
1597                 { &readtime,&readtimen,"readtime" },
1598                 { &chartime,&chartimen,"chartime" },
1599                 { &cmdtime ,&cmdtimen ,"cmdtime"  },
1600                 { &baud    ,&baudn    ,"baud"     },
1601         };
1602
1603 int main(int argc,char **argv)
1604 {
1605 char *s;
1606 int i;
1607 unsigned fatal=0;
1608 speed_t portbaud=0 /* GCC happiness */;
1609 enum modenum argsmode;
1610
1611         if ((s=strrchr((pname=*argv),'/'))) pname=s+1;
1612 #ifdef HAVE_ATEXIT
1613         atexit(cleanup);
1614 #else
1615         error("atexit(3) not available at compilation time, device cleanup may be missed");
1616 #endif
1617         signal(SIGTERM,(RETSIGTYPE (*)(int))cleanup);
1618         signal(SIGQUIT,(RETSIGTYPE (*)(int))cleanup);
1619         signal(SIGINT ,(RETSIGTYPE (*)(int))cleanup);
1620         signal(SIGHUP ,(RETSIGTYPE (*)(int))cleanup);
1621         assert(mode==MODE_UNKNOWN);
1622         for (i=0;i<NELEM(longopts);i++) {
1623                 if (longopts[i].val<MODE_FIRST) break;
1624                 if (!strstr(pname,longopts[i].name)) continue;
1625                 if (mode==MODE_UNKNOWN || mode==longopts[i].val) {
1626                         mode=longopts[i].val;
1627                         continue;
1628                         }
1629                 mode=MODE_UNKNOWN;
1630                 break;
1631                 }
1632         argsmode=mode;
1633         processargs(argc,argv,"<command-line>");
1634         if ((s=getenv("HOME"))) {
1635 size_t l=strlen(s);
1636 char *buf=malloc(l+50);
1637
1638                 memcpy(buf,s,l);
1639                 strcpy(buf+l,CONFIG_HOME);
1640                 readfile(buf,1);
1641                 free(buf);
1642                 }
1643         readfile(CONFIG_MAIN,1);
1644         if (verbose>=1) {
1645                 if (argsmode)
1646                         error(".Detected mode \"%s\" from my program name \"%s\"",MODE_NAME(argsmode),pname);
1647                 else
1648                         error(".Automatic mode detection unsuccessul for my progam name \"%s\"",pname);
1649                 }
1650
1651         if (!mode)
1652                 error("!Operation mode unset, use --send or similiar command, see help (-h)");
1653         error(".Running program in mode \"%s\"",MODE_NAME(mode));
1654         switch (mode) {
1655
1656                 case MODE_SEND:           /* FALLTHRU */
1657                 case MODE_SEND_MOBILDOCK: cmdline_send     (); break;
1658                 case MODE_LOGO_SEND:      cmdline_logo_send(); break;
1659                 case MODE_RING_SEND:      cmdline_ring_send(); break;
1660                 case MODE_RECEIVE:        cmdline_receive  (); break;
1661                 default: assert(0);
1662                 }
1663         cmdline_done();
1664         for (i=0;i<NELEM(nullcheck);i++) {
1665 const struct nullcheck *n=nullcheck+i;
1666
1667                 if (*n->var) continue;
1668                 if (n->reqd && !(MODE_BIT(mode)&n->reqd)) continue;
1669                 error("Missing parameter \"%s\"",n->name);
1670                 fatal++;
1671                 }
1672         if (fatal) error("!Previous error%s considered unrecoverable",(fatal==1?"":"s"));
1673         emptyclean();
1674         if (!logname) logname=DEF_LOGNAME;
1675         if (!lockfile) lockfile=DEF_LOCKFILE;
1676         if (!device) device=DEF_DEVICE;
1677
1678         for (i=0;i<NELEM(numarg);i++) {
1679 char *serr;
1680                 if (!*numarg[i].sp) continue;
1681                 *numarg[i].ip=strtol(*numarg[i].sp,&serr,0);
1682                 if (*numarg[i].ip<0 || *numarg[i].ip>=LONG_MAX || !serr || *serr)
1683                         error("!Number parse error for parameter \"%s\" of \"%s\" at: %s",
1684                                 numarg[i].msg,*numarg[i].sp,serr);
1685                 }
1686         if (readtimen==-1)
1687                 readtimen=(mode==MODE_SEND_MOBILDOCK?DEF_READTIME_MOBILDOCK:DEF_READTIME);
1688         if (mode==MODE_SEND_MOBILDOCK) mode=MODE_SEND;
1689
1690         if (!strchr(device,'/')) {
1691 size_t l=strlen(device);
1692                 chk(s=malloc(5+l+1));
1693                 strcpy(s,"/dev/");
1694                 strcpy(s+5,device);
1695                 free(device);
1696                 device=s;
1697                 }
1698         devicename=strrchr(device,'/')+1; assert(!!(devicename-1));
1699         for (i=0,s=lockfile;*s;s++) {
1700                 if (*s!='%') continue;
1701                 s++;
1702                 if (*s=='%') continue;
1703                 if (*s=='s') {
1704                         if (i) error("!Only one \"%%s\" permitted in lockfile format-string");
1705                         i=1; continue;
1706                         }
1707                 error("!Invalid format-character '%c' in lockfile format-string, only \"%%s\" allowed",*s);
1708                 }
1709         
1710         if (*logname) {
1711                 if (!(logf=fopen(logname,"a")))
1712                         error("^!Error opening log \"%s\" for append",logname);
1713                 logmsg("Starting up: " PACKAGE " " VERSION);
1714                 }
1715
1716         switch (mode) {
1717                 case MODE_SEND:
1718                         preparebody();
1719                         genpdu();
1720                         readbody=0;
1721                         break;
1722                 case MODE_LOGO_SEND:
1723                         logoread();
1724                         break;
1725                 case MODE_RING_SEND:
1726                         ringread();
1727                         break;
1728                 case MODE_RECEIVE: break;
1729                 default: assert(0);
1730                 }
1731         if (readbody)
1732                 error("Warning: -f / --file is forbidden with mode \"%s\"",MODE_NAME(mode));
1733
1734         switch (baudn) {
1735                 case  2400: portbaud= B2400; break;
1736                 case  4800: portbaud= B4800; break;
1737                 case  9600: portbaud= B9600; break;
1738                 case 19200: portbaud=B19200; break;
1739                 case 38400: portbaud=B38400; break;
1740                 case 57600: portbaud=B57600; break;
1741                 default:
1742                         error("!Specified baudrate %ld is not supported",baudn);
1743                 }
1744         if (verbose>=2) error(".Will use baudrate %ld with hexval 0x%X",baudn,portbaud);
1745                 
1746         if (lockfile && *lockfile && VARPRINTF(lockreal,lockfile,devicename)>0) {
1747 time_t start,end;
1748                 if (verbose>=1) error(".Locking device \"%s\" by \"%s\"..",device,lockreal);
1749                 time(&start);
1750                 lockdevice(0);
1751                 time(&end);
1752                 if ((end-=start)>LOCKREPORT)
1753                         logmsg("Device lock succeeded after %ld seconds",(long)end);
1754                 }
1755         if (verbose>=1) error(".Opening device \"%s\"..",device);
1756         if ((devfd=open(device,O_RDWR|O_NDELAY))<0)
1757                 error("^!Cannot open device \"%s\" for r/w access",device);
1758         
1759         if (tcgetattr(devfd,&restios))
1760                 error("^Unable to get termios settings");
1761         else {
1762                 restios.c_cflag=(restios.c_cflag&~(CBAUD|CBAUDEX))|B0|HUPCL;
1763                 restios_yes=1;
1764                 }
1765         tios.c_iflag=IGNBRK|IGNPAR|IXON|IXOFF;
1766         tios.c_oflag=0;
1767         tios.c_cflag=CS8|CREAD|CLOCAL|HUPCL|portbaud;
1768         tios.c_lflag=IEXTEN|NOFLSH;
1769         memset(tios.c_cc,_POSIX_VDISABLE,sizeof(tios.c_cc));
1770         tios.c_cc[VTIME]=0;
1771         tios.c_cc[VMIN ]=1;
1772             cfsetispeed(&tios,portbaud);
1773         if (cfsetospeed(&tios,portbaud)|cfsetispeed(&tios,portbaud))
1774                 error("^Error setting termios baudrate on device");
1775         if (tcflush(devfd,TCIOFLUSH))
1776                 error("^Error flushing termios (TCIOFLUSH) on device");
1777         if (tcsetattr(devfd,TCSANOW,&tios))
1778                 error("^!Unable to set initial termios device settings");
1779
1780         setalarm();
1781
1782 retryall:
1783                 devcmd("",NULL,"\r\nAT\033\032"); /* ESCAPE, CTRL-Z */
1784                 devcmd(NULL,NULL,"\r\nAT");
1785                 smscset();
1786                 switch (mode) {
1787                         case MODE_SEND:
1788 retrysendcmgf:
1789                                 if (!devcmd(NULL,NULL,"!\r\nAT+CMGF=0")) {
1790                                         if (!devcmd(NULL,NULL,"!\r\nAT+CMGF=1"))
1791                                                 { retrying(); goto retrysendcmgf; }
1792                 /* CMGF=1 */
1793                                         devcmd("\n> ",NULL,"\r\nAT+CMGS=\"%s\"",phone);
1794                                         s=devcmd(NULL,"\n+CMGS:","!~%s\032",body);
1795                                         }
1796                                 else {
1797                 /* CMGF=0 */
1798                                         devcmd("\n> ",NULL,"\r\nAT+CMGS=%d",(strlen(pdusmsc)+strlen(pdudata))/2);
1799                                         s=devcmd(NULL,"\n+CMGS:","!~%s%s\032",pdusmsc,pdudata);
1800                                         }
1801                                 break;
1802                         case MODE_LOGO_SEND:
1803                         case MODE_RING_SEND: {
1804 struct hexdata *hd;
1805
1806                                 restore="\r\nAT+CSMP=17,,0,0";
1807                                 devcmd(NULL,NULL,"\r\nAT+CSMP=81,,0,245");
1808                                 devcmd("\n> ",NULL,"\r\nAT+CMGS=\"%s\"",phone);
1809                                 while ((hd=hexdata)) {
1810                                         if (!(s=devcmd(NULL,"\n+CMGS:","!~%s\032",hd->data))) break;
1811                                         hexdata=hd->next;
1812                                         free(hd);
1813                                         }
1814                                 } break;
1815                         case MODE_RECEIVE:
1816                                 devcmd(NULL,NULL,"\r\nAT+CMGF=1");
1817                                 restore="\r\nAT+CNMI=,0";
1818                                 devcmd(NULL,NULL,"\r\nAT+CSDH=0");
1819                                 devcmd(NULL,NULL,"\r\nAT+CNMI=,2");
1820                                 unlockdevice(0);
1821                                 /* Never bail-out when we got up to this point */
1822                                 if (maxretryn!=-1 && verbose>=1)
1823                                         error(".Initialization successful, infinite retry count set");
1824                                 maxretryn=-1;
1825 #if RECEIVE_TEST
1826                 receive_headerparse(" \"+420602123456\",,\"99/10/25,03:21:03-00\"");
1827                 receive_accept("TESTBODY");
1828                 exit(EXIT_SUCCESS);
1829 #endif
1830                                 datawait(0);
1831                                 if (!lockdevice(1)) {
1832                                         if (verbose>=1)
1833                                                 error(".Dialout detected, waiting for lock..");
1834                                         lockdevice(0);
1835                                         goto retryall;
1836                                         }
1837                                 d1("Lock-device succeeded\n");
1838                                 do {
1839                                         d1("Reading a message for us...\n");
1840                                         if (!(s=devcmd("\r","@+CMT:"," ")))
1841                                                 goto retryall;
1842                                         if (!(i=receive_headerparse(s)))
1843                                                 error("Receive-header parsing failed on: %s",s);
1844                                         if (!(s=devcmd("\r","@\n"," ")))
1845                                                 goto retryall;
1846                                         if (i) receive_accept(s);
1847                                         if (!devcmd("\n",NULL," ")) /* eat last '\n' */
1848                                                 goto retryall;
1849                                         } while (datawait(1));
1850                                 goto retryall;
1851                                 break;
1852                         default: assert(0);
1853                         }
1854                 if (!s) { retrying(); goto retryall; }
1855
1856         while (isspace(*s)) s++;
1857         if (verbose>=1) error("\nMessage successfuly sent with MR: %s",s);
1858         devcmd(NULL,NULL,"\r\nAT");
1859
1860         logmsg("SMS sent (after %d retries), message reference: %s",retrycnt,s);
1861         return(EXIT_SUCCESS);
1862 }