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