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