OSDN Git Service

add huaweigeneric-ril
[android-x86/hardware-ril.git] / huaweigeneric-ril / atchannel.c
1 /* //device/system/reference-ril/atchannel.c
2 **
3 ** Copyright 2006, The Android Open Source Project
4 **
5 ** Licensed under the Apache License, Version 2.0 (the "License");
6 ** you may not use this file except in compliance with the License.
7 ** You may obtain a copy of the License at
8 **
9 **     http://www.apache.org/licenses/LICENSE-2.0
10 **
11 ** Unless required by applicable law or agreed to in writing, software
12 ** distributed under the License is distributed on an "AS IS" BASIS,
13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 ** See the License for the specific language governing permissions and
15 ** limitations under the License.
16 */
17
18 #include "atchannel.h"
19 #include "at_tok.h"
20
21 #include <stdio.h>
22 #include <string.h>
23 #include <pthread.h>
24 #include <ctype.h>
25 #include <stdlib.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <sys/time.h>
29 #include <time.h>
30 #include <unistd.h>
31 #include <stdarg.h>
32
33 #include <poll.h>
34
35 #define LOG_NDEBUG 0
36 #define LOG_TAG "AT"
37 #include <utils/Log.h>
38
39 #ifdef HAVE_ANDROID_OS
40 /* For IOCTL's */
41 #include <linux/omap_csmi.h>
42 #endif /*HAVE_ANDROID_OS*/
43
44 #include "misc.h"
45
46 #define MAX_AT_RESPONSE (8 * 1024)
47 #define HANDSHAKE_RETRY_COUNT 8
48 #define HANDSHAKE_TIMEOUT_MSEC 250
49 #define DEFAULT_AT_TIMEOUT_MSEC (3 * 60 * 1000)
50 #define BUFFSIZE 512
51
52 struct atcontext {
53     pthread_t tid_reader;
54     int fd;                  /* fd of the AT channel. */
55     int readerCmdFds[2];
56     int isInitialized;
57     ATUnsolHandler unsolHandler;
58
59     /* For input buffering. */
60     char ATBuffer[MAX_AT_RESPONSE+1];
61     char *ATBufferCur;
62
63     int readCount;
64
65     /*
66      * For current pending command, these are protected by commandmutex.
67      *
68      * The mutex and cond struct is memset in the getAtChannel() function,
69      * so no initializer should be needed.
70      */
71     pthread_mutex_t requestmutex;
72     pthread_mutex_t commandmutex;
73     pthread_cond_t requestcond;
74     pthread_cond_t commandcond;
75
76     ATCommandType type;
77     const char *responsePrefix;
78     const char *smsPDU;
79     ATResponse *response;
80
81     void (*onTimeout)(void);
82     void (*onReaderClosed)(void);
83     int readerClosed;
84
85     int timeoutMsec;
86 };
87
88 static struct atcontext *s_defaultAtContext = NULL;
89 static va_list empty = {0};
90
91 static pthread_key_t key;
92 static pthread_once_t key_once = PTHREAD_ONCE_INIT;
93
94 static int writeCtrlZ (const char *s);
95 static int writeline (const char *s);
96 static void onReaderClosed(void);
97
98 static void make_key(void)
99 {
100     (void) pthread_key_create(&key, NULL);
101 }
102
103 /**
104  * Set the atcontext pointer. Useful for sub-threads that needs to hold
105  * the same state information.
106  *
107  * The caller IS responsible for freeing any memory already allocated
108  * for any previous atcontexts.
109  */
110 static void setAtContext(struct atcontext *ac)
111 {
112     (void) pthread_once(&key_once, make_key);
113     (void) pthread_setspecific(key, ac);
114 }
115
116 static void ac_free(void)
117 {
118     struct atcontext *ac = NULL;
119     (void) pthread_once(&key_once, make_key);
120     if ((ac = (struct atcontext *) pthread_getspecific(key)) != NULL) {
121         free(ac);
122         ALOGD("%s() freed current thread AT context", __func__);
123     } else {
124         ALOGW("%s() No AT context exist for current thread, cannot free it",
125             __func__);
126     }
127 }
128
129 static int initializeAtContext(void)
130 {
131     struct atcontext *ac = NULL;
132
133     if (pthread_once(&key_once, make_key)) {
134         ALOGE("%s() Pthread_once failed!", __func__);
135         goto error;
136     }
137
138     ac = (struct atcontext *)pthread_getspecific(key);
139
140     if (ac == NULL) {
141         ac = (struct atcontext *) malloc(sizeof(struct atcontext));
142         if (ac == NULL) {
143             ALOGE("%s() Failed to allocate memory", __func__);
144             goto error;
145         }
146
147         memset(ac, 0, sizeof(struct atcontext));
148
149         ac->fd = -1;
150         ac->readerCmdFds[0] = -1;
151         ac->readerCmdFds[1] = -1;
152         ac->ATBufferCur = ac->ATBuffer;
153
154         if (pipe(ac->readerCmdFds)) {
155             ALOGE("%s() Failed to create pipe: %s", __func__, strerror(errno));
156             goto error;
157         }
158
159         pthread_mutex_init(&ac->commandmutex, NULL);
160         pthread_mutex_init(&ac->requestmutex, NULL);
161         pthread_cond_init(&ac->requestcond, NULL);
162         pthread_cond_init(&ac->commandcond, NULL);
163
164         ac->timeoutMsec = DEFAULT_AT_TIMEOUT_MSEC;
165
166         if (pthread_setspecific(key, ac)) {
167             ALOGE("%s() Calling pthread_setspecific failed!", __func__);
168             goto error;
169         }
170     }
171
172     ALOGI("Initialized new AT Context!");
173
174     return 0;
175
176 error:
177     ALOGE("%s() Failed initializing new AT Context!", __func__);
178     free(ac);
179     return -1;
180 }
181
182 static struct atcontext *getAtContext(void)
183 {
184     struct atcontext *ac = NULL;
185
186     (void) pthread_once(&key_once, make_key);
187
188     if ((ac = (struct atcontext *) pthread_getspecific(key)) == NULL) {
189         if (s_defaultAtContext) {
190             ALOGW("WARNING! external thread use default AT Context");
191             ac = s_defaultAtContext;
192         } else {
193             ALOGE("WARNING! %s() called from external thread with "
194                  "no defaultAtContext set!! This IS a bug! "
195                  "A crash is probably nearby!", __func__);
196         }
197     }
198
199     return ac;
200 }
201
202 /**
203  * This function will make the current at thread the default channel,
204  * meaning that calls from a thread that is not a queuerunner will
205  * be executed in this context.
206  */
207 void at_make_default_channel(void)
208 {
209     struct atcontext *ac = getAtContext();
210
211     if (ac->isInitialized)
212         s_defaultAtContext = ac;
213 }
214
215 #if AT_DEBUG
216 void  AT_DUMP(const char*  prefix, const char*  buff, int  len)
217 {
218     if (len < 0)
219         len = strlen(buff);
220     ALOGD("%.*s", len, buff);
221 }
222 #endif
223
224 #ifndef HAVE_ANDROID_OS
225 int pthread_cond_timeout_np(pthread_cond_t *cond,
226                             pthread_mutex_t * mutex,
227                             unsigned msecs)
228 {
229     struct timespec ts;
230     clock_gettime(CLOCK_REALTIME, &ts);
231
232     ts.tv_sec += msecs / 1000;
233     ts.tv_nsec += (msecs % 1000) * 1000000;
234     return pthread_cond_timedwait(cond, mutex, &ts);
235 }
236 #endif /*HAVE_ANDROID_OS*/
237
238 static void sleepMsec(long long msec)
239 {
240     struct timespec ts;
241     int err;
242
243     ts.tv_sec = (msec / 1000);
244     ts.tv_nsec = (msec % 1000) * 1000 * 1000;
245
246     do {
247         err = nanosleep (&ts, &ts);
248     } while (err < 0 && errno == EINTR);
249 }
250
251
252
253 /** Add an intermediate response to sp_response. */
254 static void addIntermediate(const char *line)
255 {
256     ATLine *p_new;
257     struct atcontext *ac = getAtContext();
258
259     p_new = (ATLine  *) malloc(sizeof(ATLine));
260
261     p_new->line = strdup(line);
262
263     /* Note: This adds to the head of the list, so the list will
264        be in reverse order of lines received. the order is flipped
265        again before passing on to the command issuer. */
266     p_new->p_next = ac->response->p_intermediates;
267     ac->response->p_intermediates = p_new;
268 }
269
270
271 /**
272  * Returns 1 if line is a final response indicating error.
273  * See 27.007 annex B.
274  * WARNING: NO CARRIER and others are sometimes unsolicited.
275  */
276 static const char * s_finalResponsesError[] = {
277     "ERROR",
278     "+CMS ERROR:",
279     "+CME ERROR:",
280     "NO CARRIER",      /* Sometimes! */
281     "NO ANSWER",
282     "NO DIALTONE",
283 };
284
285 static int isFinalResponseError(const char *line)
286 {
287     size_t i;
288
289     for (i = 0 ; i < NUM_ELEMS(s_finalResponsesError) ; i++) {
290         if (strStartsWith(line, s_finalResponsesError[i])) {
291             return 1;
292         }
293     }
294
295     return 0;
296 }
297
298 /**
299  * Returns 1 if line is a final response indicating success.
300  * See 27.007 annex B.
301  * WARNING: NO CARRIER and others are sometimes unsolicited.
302  */
303 static const char * s_finalResponsesSuccess[] = {
304     "OK",
305     "CONNECT"       /* Some stacks start up data on another channel. */
306 };
307 static int isFinalResponseSuccess(const char *line)
308 {
309     size_t i;
310
311     for (i = 0 ; i < NUM_ELEMS(s_finalResponsesSuccess) ; i++) {
312         if (strStartsWith(line, s_finalResponsesSuccess[i])) {
313             return 1;
314         }
315     }
316
317     return 0;
318 }
319
320 /**
321  * Returns 1 if line is the first line in (what will be) a two-line
322  * SMS unsolicited response.
323  */
324 static const char * s_smsUnsoliciteds[] = {
325     "+CMT:",
326     "+CDS:",
327     "+CBM:"
328 };
329 static int isSMSUnsolicited(const char *line)
330 {
331     size_t i;
332
333     for (i = 0 ; i < NUM_ELEMS(s_smsUnsoliciteds) ; i++) {
334         if (strStartsWith(line, s_smsUnsoliciteds[i])) {
335             return 1;
336         }
337     }
338
339     return 0;
340 }
341
342
343 /** Assumes s_commandmutex is held. */
344 static void handleFinalResponse(const char *line)
345 {
346     struct atcontext *ac = getAtContext();
347
348     ac->response->finalResponse = strdup(line);
349
350     pthread_cond_signal(&ac->commandcond);
351 }
352
353 static void handleUnsolicited(const char *line)
354 {
355     struct atcontext *ac = getAtContext();
356
357     if (ac->unsolHandler != NULL) {
358         ac->unsolHandler(line, NULL);
359     }
360 }
361
362 static void processLine(const char *line)
363 {
364     struct atcontext *ac = getAtContext();
365     pthread_mutex_lock(&ac->commandmutex);
366
367     if (ac->response == NULL) {
368         /* No command pending. */
369         handleUnsolicited(line);
370     } else if (isFinalResponseSuccess(line)) {
371         ac->response->success = 1;
372         handleFinalResponse(line);
373     } else if (isFinalResponseError(line)) {
374         ac->response->success = 0;
375         handleFinalResponse(line);
376     } else if (ac->smsPDU != NULL && 0 == strcmp(line, "> ")) {
377         /* See eg. TS 27.005 4.3.
378            Commands like AT+CMGS have a "> " prompt. */
379         writeCtrlZ(ac->smsPDU);
380         ac->smsPDU = NULL;
381     } else switch (ac->type) {
382         case NO_RESULT:
383             handleUnsolicited(line);
384             break;
385         case NUMERIC:
386             if (ac->response->p_intermediates == NULL
387                 && isdigit(line[0])) {
388                 addIntermediate(line);
389             } else {
390                 /* Either we already have an intermediate response or
391                    the line doesn't begin with a digit. */
392                 handleUnsolicited(line);
393             }
394             break;
395         case SINGLELINE:
396             if (ac->response->p_intermediates == NULL
397                 && strStartsWith (line, ac->responsePrefix)) {
398                 addIntermediate(line);
399             } else {
400                 /* We already have an intermediate response. */
401                 handleUnsolicited(line);
402             }
403             break;
404         case MULTILINE:
405             if (strStartsWith (line, ac->responsePrefix)) {
406                 addIntermediate(line);
407             } else {
408                 handleUnsolicited(line);
409             }
410         break;
411
412         default: /* This should never be reached */
413             ALOGE("%s() Unsupported AT command type %d", __func__, ac->type);
414             handleUnsolicited(line);
415         break;
416     }
417
418     pthread_mutex_unlock(&ac->commandmutex);
419 }
420
421
422 /**
423  * Returns a pointer to the end of the next line,
424  * special-cases the "> " SMS prompt.
425  *
426  * returns NULL if there is no complete line.
427  */
428 static char * findNextEOL(char *cur)
429 {
430     if (cur[0] == '>' && cur[1] == ' ' && cur[2] == '\0') {
431         /* SMS prompt character...not \r terminated */
432         return cur+2;
433     }
434
435     /* Find next newline */
436     while (*cur != '\0' && *cur != '\r' && *cur != '\n') cur++;
437
438     return *cur == '\0' ? NULL : cur;
439 }
440
441
442 /**
443  * Reads a line from the AT channel, returns NULL on timeout.
444  * Assumes it has exclusive read access to the FD.
445  *
446  * This line is valid only until the next call to readline.
447  *
448  * This function exists because as of writing, android libc does not
449  * have buffered stdio.
450  */
451
452 static const char *readline(void)
453 {
454     ssize_t count;
455
456     char *p_read = NULL;
457     char *p_eol = NULL;
458     char *ret = NULL;
459
460     struct atcontext *ac = getAtContext();
461     read(ac->fd,NULL,0);
462
463     /* This is a little odd. I use *s_ATBufferCur == 0 to mean
464      * "buffer consumed completely". If it points to a character,
465      * then the buffer continues until a \0.
466      */
467     if (*ac->ATBufferCur == '\0') {
468         /* Empty buffer. */
469         ac->ATBufferCur = ac->ATBuffer;
470         *ac->ATBufferCur = '\0';
471         p_read = ac->ATBuffer;
472     } else {   /* *s_ATBufferCur != '\0' */
473         /* There's data in the buffer from the last read. */
474
475         /* skip over leading newlines */
476         while (*ac->ATBufferCur == '\r' || *ac->ATBufferCur == '\n')
477             ac->ATBufferCur++;
478
479         p_eol = findNextEOL(ac->ATBufferCur);
480
481         if (p_eol == NULL) {
482             /* A partial line. Move it up and prepare to read more. */
483             size_t len;
484
485             len = strlen(ac->ATBufferCur);
486
487             memmove(ac->ATBuffer, ac->ATBufferCur, len + 1);
488             p_read = ac->ATBuffer + len;
489             ac->ATBufferCur = ac->ATBuffer;
490         }
491         /* Otherwise, (p_eol !- NULL) there is a complete line
492            that will be returned from the while () loop below. */
493     }
494
495     while (p_eol == NULL) {
496         int err;
497         struct pollfd pfds[2];
498
499         /* This condition should be synchronized with the read function call
500          * size argument below.
501          */
502         if (0 >= MAX_AT_RESPONSE - (p_read - ac->ATBuffer) - 2) {
503             ALOGE("%s() ERROR: Input line exceeded buffer", __func__);
504             /* Ditch buffer and start over again. */
505             ac->ATBufferCur = ac->ATBuffer;
506             *ac->ATBufferCur = '\0';
507             p_read = ac->ATBuffer;
508         }
509
510         /* If our fd is invalid, we are probably closed. Return. */
511         if (ac->fd < 0)
512             return NULL;
513
514         pfds[0].fd = ac->fd;
515         pfds[0].events = POLLIN | POLLERR;
516
517         pfds[1].fd = ac->readerCmdFds[0];
518         pfds[1].events = POLLIN;
519
520         err = poll(pfds, 2, -1);
521
522         if (err < 0) {
523             ALOGE("%s() poll: error: %s", __func__, strerror(errno));
524             return NULL;
525         }
526
527         if (pfds[1].revents & POLLIN) {
528             char buf[10];
529
530             /* Just drain it. We don't care, this is just for waking up. */
531             read(pfds[1].fd, &buf, 1);
532             continue;
533         }
534
535         if (pfds[0].revents & POLLERR) {
536             ALOGE("%s() POLLERR event! Returning...", __func__);
537             return NULL;
538         }
539
540         if (!(pfds[0].revents & POLLIN))
541             continue;
542
543         do
544             /* The size argument should be synchronized to the ditch buffer
545              * condition above.
546              */
547             count = read(ac->fd, p_read,
548                          MAX_AT_RESPONSE - (p_read - ac->ATBuffer) - 2);
549
550         while (count < 0 && errno == EINTR);
551
552         if (count > 0) {
553             AT_DUMP( "<< ", p_read, count );
554             ac->readCount += count;
555
556             /* Implementation requires extra EOS or EOL to get it right if
557              * there are no trailing newlines in the read buffer. Adding extra
558              * EOS does not harm even if there actually were trailing EOLs.
559              */
560             p_read[count] = '\0';
561             p_read[count+1] = '\0';
562
563             /* Skip over leading newlines. */
564             while (*ac->ATBufferCur == '\r' || *ac->ATBufferCur == '\n')
565                 ac->ATBufferCur++;
566
567             p_eol = findNextEOL(ac->ATBufferCur);
568             p_read += count;
569         } else if (count <= 0) {
570             /* Read error encountered or EOF reached. */
571             if (count == 0)
572                 ALOGD("%s() atchannel: EOF reached.", __func__);
573             else
574                 ALOGD("%s() atchannel: read error %s", __func__, strerror(errno));
575
576             return NULL;
577         }
578     }
579
580     /* A full line in the buffer. Place a \0 over the \r and return. */
581
582     ret = ac->ATBufferCur;
583     *p_eol = '\0';
584
585     /* The extra EOS added after read takes care of the case when there is no
586      * valid data after p_eol.
587      */
588     ac->ATBufferCur = p_eol + 1;     /* This will always be <= p_read,
589                                         and there will be a \0 at *p_read. */
590
591     ALOGI("AT(%d)< %s", ac->fd, ret);
592     return ret;
593 }
594
595 static void onReaderClosed(void)
596 {
597     struct atcontext *ac = getAtContext();
598     if (ac->onReaderClosed != NULL && ac->readerClosed == 0) {
599
600         pthread_mutex_lock(&ac->commandmutex);
601
602         ac->readerClosed = 1;
603
604         pthread_cond_signal(&ac->commandcond);
605
606         pthread_mutex_unlock(&ac->commandmutex);
607
608         ac->onReaderClosed();
609     }
610 }
611
612 static void *readerLoop(void *arg)
613 {
614     struct atcontext *ac = NULL;
615
616     ALOGI("Entering readerloop!");
617
618     setAtContext((struct atcontext *) arg);
619     ac = getAtContext();
620
621     for (;;) {
622         const char * line;
623
624         line = readline();
625
626         if (line == NULL)
627             break;
628
629         if(isSMSUnsolicited(line)) {
630             char *line1;
631             const char *line2;
632
633             /* The scope of string returned by 'readline()' is valid only
634                until next call to 'readline()' hence making a copy of line
635                before calling readline again. */
636             line1 = strdup(line);
637             line2 = readline();
638
639             if (line2 == NULL) {
640                 free(line1);
641                 break;
642             }
643
644             if (ac->unsolHandler != NULL)
645                 ac->unsolHandler(line1, line2);
646
647             free(line1);
648         } else
649             processLine(line);
650         }
651
652     onReaderClosed();
653     ALOGI("Exiting readerloop!");
654     return NULL;
655 }
656
657 /**
658  * Sends string s to the radio with a \r appended.
659  * Returns AT_ERROR_* on error, 0 on success.
660  *
661  * This function exists because as of writing, android libc does not
662  * have buffered stdio.
663  */
664 static int writeline (const char *s)
665 {
666     size_t cur = 0;
667     size_t len = strlen(s);
668     ssize_t written;
669
670     struct atcontext *ac = getAtContext();
671
672     if (ac->fd < 0 || ac->readerClosed > 0) {
673         return AT_ERROR_CHANNEL_CLOSED;
674     }
675
676     ALOGD("AT(%d)> %s", ac->fd, s);
677
678     AT_DUMP( ">> ", s, strlen(s) );
679
680     /* The main string. */
681     while (cur < len) {
682         do {
683             written = write (ac->fd, s + cur, len - cur);
684         } while (written < 0 && errno == EINTR);
685
686         if (written < 0) {
687             return AT_ERROR_GENERIC;
688         }
689
690         cur += written;
691     }
692
693     /* The \r  */
694
695     do {
696         written = write (ac->fd, "\r" , 1);
697     } while ((written < 0 && errno == EINTR) || (written == 0));
698
699     if (written < 0) {
700         return AT_ERROR_GENERIC;
701     }
702
703     return 0;
704 }
705
706 static int writeCtrlZ (const char *s)
707 {
708     size_t cur = 0;
709     size_t len = strlen(s);
710     ssize_t written;
711
712     struct atcontext *ac = getAtContext();
713
714     if (ac->fd < 0 || ac->readerClosed > 0)
715         return AT_ERROR_CHANNEL_CLOSED;
716
717     ALOGD("AT> %s^Z\n", s);
718
719     AT_DUMP( ">* ", s, strlen(s) );
720
721     /* The main string. */
722     while (cur < len) {
723         do {
724             written = write (ac->fd, s + cur, len - cur);
725         } while (written < 0 && errno == EINTR);
726
727         if (written < 0)
728             return AT_ERROR_GENERIC;
729
730         cur += written;
731     }
732
733     /* the ^Z  */
734     do {
735         written = write (ac->fd, "\032" , 1);
736     } while ((written < 0 && errno == EINTR) || (written == 0));
737
738     if (written < 0)
739         return AT_ERROR_GENERIC;
740
741     return 0;
742 }
743
744 static void clearPendingCommand(void)
745 {
746     struct atcontext *ac = getAtContext();
747
748     if (ac->response != NULL)
749         at_response_free(ac->response);
750
751     ac->response = NULL;
752     ac->responsePrefix = NULL;
753     ac->smsPDU = NULL;
754     }
755
756 static AT_Error merror(int type, int error)
757 {
758     switch(type) {
759     case AT_ERROR :
760         return (AT_Error)(AT_ERROR_BASE + error);
761     case CME_ERROR :
762         return (AT_Error)(CME_ERROR_BASE + error);
763     case CMS_ERROR:
764         return (AT_Error)(CMS_ERROR_BASE + error);
765     case GENERIC_ERROR:
766         return (AT_Error)(GENERIC_ERROR_BASE + error);
767     default:
768         return (AT_Error)(GENERIC_ERROR_UNSPECIFIED);
769     }
770 }
771
772 static AT_Error at_get_error(const ATResponse *p_response)
773 {
774     int ret;
775     int err;
776     char *p_cur;
777
778     if (p_response == NULL)
779         return merror(GENERIC_ERROR, GENERIC_ERROR_UNSPECIFIED);
780
781     if (p_response->success > 0)
782         return AT_NOERROR;
783
784     if (p_response->finalResponse == NULL)
785         return AT_ERROR_INVALID_RESPONSE;
786
787     if (isFinalResponseSuccess(p_response->finalResponse))
788         return AT_NOERROR;
789
790     p_cur = p_response->finalResponse;
791     err = at_tok_start(&p_cur);
792     if (err < 0)
793         return merror(GENERIC_ERROR, GENERIC_ERROR_UNSPECIFIED);
794
795     err = at_tok_nextint(&p_cur, &ret);
796     if (err < 0)
797         return merror(GENERIC_ERROR, GENERIC_ERROR_UNSPECIFIED);
798
799     if(strStartsWith(p_response->finalResponse, "+CME ERROR:"))
800         return merror(CME_ERROR, ret);
801     else if (strStartsWith(p_response->finalResponse, "+CMS ERROR:"))
802         return merror(CMS_ERROR, ret);
803     else if (strStartsWith(p_response->finalResponse, "ERROR:"))
804         return merror(GENERIC_ERROR, GENERIC_ERROR_RESPONSE);
805     else if (strStartsWith(p_response->finalResponse, "+NO CARRIER:"))
806         return merror(GENERIC_ERROR, GENERIC_NO_CARRIER_RESPONSE);
807     else if (strStartsWith(p_response->finalResponse, "+NO ANSWER:"))
808         return merror(GENERIC_ERROR, GENERIC_NO_ANSWER_RESPONSE);
809     else if (strStartsWith(p_response->finalResponse, "+NO DIALTONE:"))
810         return merror(GENERIC_ERROR, GENERIC_NO_DIALTONE_RESPONSE);
811     else
812         return merror(GENERIC_ERROR, GENERIC_ERROR_UNSPECIFIED);
813 }
814
815 /**
816  * Starts AT handler on stream "fd'.
817  * returns 0 on success, -1 on error.
818  */
819 int at_open(int fd, ATUnsolHandler h)
820 {
821     int ret;
822     pthread_attr_t attr;
823
824     struct atcontext *ac = NULL;
825
826     if (initializeAtContext()) {
827         ALOGE("%s() InitializeAtContext failed!", __func__);
828         goto error;
829     }
830
831     ac = getAtContext();
832
833     ac->fd = fd;
834     ac->isInitialized = 1;
835     ac->unsolHandler = h;
836     ac->readerClosed = 0;
837
838     ac->responsePrefix = NULL;
839     ac->smsPDU = NULL;
840     ac->response = NULL;
841
842     pthread_attr_init (&attr);
843     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
844
845     ret = pthread_create(&ac->tid_reader, &attr, readerLoop, ac);
846
847     if (ret < 0) {
848         perror ("pthread_create");
849         goto error;
850     }
851
852
853     return 0;
854 error:
855     ac_free();
856     return -1;
857 }
858
859 /* FIXME is it ok to call this from the reader and the command thread? */
860 void at_close(void)
861 {
862     struct atcontext *ac = getAtContext();
863
864     if (ac->fd >= 0) {
865         if (close(ac->fd) != 0)
866             ALOGE("%s() FAILED to close fd %d!", __func__, ac->fd);
867     }
868     ac->fd = -1;
869
870     pthread_mutex_lock(&ac->commandmutex);
871
872     ac->readerClosed = 1;
873
874     pthread_cond_signal(&ac->commandcond);
875
876     pthread_mutex_unlock(&ac->commandmutex);
877
878     /* Kick readerloop. */
879     write(ac->readerCmdFds[1], "x", 1);
880 }
881
882 static ATResponse *at_response_new(void)
883 {
884     return (ATResponse *) calloc(1, sizeof(ATResponse));
885 }
886
887 void at_response_free(ATResponse *p_response)
888 {
889     ATLine *p_line;
890
891     if (p_response == NULL) return;
892
893     p_line = p_response->p_intermediates;
894
895     while (p_line != NULL) {
896         ATLine *p_toFree;
897
898         p_toFree = p_line;
899         p_line = p_line->p_next;
900
901         free(p_toFree->line);
902         free(p_toFree);
903     }
904
905     free (p_response->finalResponse);
906     free (p_response);
907 }
908
909 /**
910  * The line reader places the intermediate responses in reverse order,
911  * here we flip them back.
912  */
913 static void reverseIntermediates(ATResponse *p_response)
914 {
915     ATLine *pcur,*pnext;
916
917     pcur = p_response->p_intermediates;
918     p_response->p_intermediates = NULL;
919
920     while (pcur != NULL) {
921         pnext = pcur->p_next;
922         pcur->p_next = p_response->p_intermediates;
923         p_response->p_intermediates = pcur;
924         pcur = pnext;
925     }
926 }
927
928 /**
929  * Internal send_command implementation.
930  * Doesn't lock or call the timeout callback.
931  *
932  * timeoutMsec == 0 means infinite timeout.
933  */
934 static int at_send_command_full_nolock (const char *command, ATCommandType type,
935                     const char *responsePrefix, const char *smspdu,
936                     long long timeoutMsec, ATResponse **pp_outResponse)
937 {
938     int err = AT_NOERROR;
939
940     struct atcontext *ac = getAtContext();
941
942     /* Default to NULL, to allow caller to free securely even if
943      * no response will be set below */
944     if (pp_outResponse != NULL)
945         *pp_outResponse = NULL;
946
947     /* FIXME This is to prevent future problems due to calls from other threads; should be revised. */
948     while (pthread_mutex_trylock(&ac->requestmutex) == EBUSY)
949         pthread_cond_wait(&ac->requestcond, &ac->commandmutex);
950
951     if(ac->response != NULL) {
952         err = AT_ERROR_COMMAND_PENDING;
953         goto finally;
954     }
955
956     ac->type = type;
957     ac->responsePrefix = responsePrefix;
958     ac->smsPDU = smspdu;
959     ac->response = at_response_new();
960     if (ac->response == NULL) {
961         err = AT_ERROR_MEMORY_ALLOCATION;
962         goto finally;
963     }
964
965     err = writeline (command);
966
967     if (err != AT_NOERROR)
968         goto finally;
969
970     while (ac->response->finalResponse == NULL && ac->readerClosed == 0) {
971         if (timeoutMsec != 0)
972             err = pthread_cond_timeout_np(&ac->commandcond, &ac->commandmutex, timeoutMsec);
973         else
974             err = pthread_cond_wait(&ac->commandcond, &ac->commandmutex);
975
976         if (err == ETIMEDOUT) {
977             err = AT_ERROR_TIMEOUT;
978             goto finally;
979         }
980         }
981
982     if (ac->response->success == 0) {
983         err = at_get_error(ac->response);
984     }
985
986     if (pp_outResponse == NULL)
987         at_response_free(ac->response);
988     else {
989         /* Line reader stores intermediate responses in reverse order. */
990         reverseIntermediates(ac->response);
991         *pp_outResponse = ac->response;
992     }
993
994     ac->response = NULL;
995
996     if(ac->readerClosed > 0) {
997         err = AT_ERROR_CHANNEL_CLOSED;
998         goto finally;
999     }
1000
1001 finally:
1002     clearPendingCommand();
1003
1004     pthread_cond_broadcast(&ac->requestcond);
1005     pthread_mutex_unlock(&ac->requestmutex);
1006
1007     return err;
1008 }
1009
1010 /**
1011  * Internal send_command implementation.
1012  *
1013  * timeoutMsec == 0 means infinite timeout.
1014  */
1015 static int at_send_command_full (const char *command, ATCommandType type,
1016                     const char *responsePrefix, const char *smspdu,
1017                     long long timeoutMsec, ATResponse **pp_outResponse, int useap, va_list ap)
1018 {
1019     int err;
1020
1021     struct atcontext *ac = getAtContext();
1022     static char strbuf[BUFFSIZE];
1023     const char *ptr;
1024
1025     if (0 != pthread_equal(ac->tid_reader, pthread_self()))
1026         /* Cannot be called from reader thread. */
1027         return AT_ERROR_INVALID_THREAD;
1028
1029     pthread_mutex_lock(&ac->commandmutex);
1030     if (useap) {
1031         if (!vsnprintf(strbuf, BUFFSIZE, command, ap)) {
1032            pthread_mutex_unlock(&ac->commandmutex);
1033            return AT_ERROR_STRING_CREATION;
1034     }
1035         ptr = strbuf;
1036     } else
1037         ptr = command;
1038
1039     err = at_send_command_full_nolock(ptr, type,
1040                     responsePrefix, smspdu,
1041                     timeoutMsec, pp_outResponse);
1042
1043     pthread_mutex_unlock(&ac->commandmutex);
1044
1045     if (err == AT_ERROR_TIMEOUT && ac->onTimeout != NULL)
1046         ac->onTimeout();
1047
1048     return err;
1049 }
1050
1051 /* Only call this from onTimeout, since we're not locking or anything. */
1052 void at_send_escape (void)
1053 {
1054     struct atcontext *ac = getAtContext();
1055     int written;
1056
1057     do
1058         written = write (ac->fd, "\033" , 1);
1059     while ((written < 0 && errno == EINTR) || (written == 0));
1060 }
1061
1062 /**
1063  * Issue a single normal AT command with no intermediate response expected.
1064  *
1065  * "command" should not include \r.
1066  */
1067 int at_send_command (const char *command, ...)
1068 {
1069     int err;
1070
1071     struct atcontext *ac = getAtContext();
1072     va_list ap;
1073     va_start(ap, command);
1074
1075     err = at_send_command_full (command, NO_RESULT, NULL,
1076             NULL, ac->timeoutMsec, NULL, 1, ap);
1077     va_end(ap);
1078
1079     if (err != AT_NOERROR)
1080         ALOGI(" --- %s", at_str_err(-err));
1081
1082     return -err;
1083 }
1084
1085 int at_send_command_raw (const char *command, ATResponse **pp_outResponse)
1086 {
1087     struct atcontext *ac = getAtContext();
1088     int err;
1089
1090     err = at_send_command_full (command, MULTILINE, "",
1091             NULL, ac->timeoutMsec, pp_outResponse, 0, empty);
1092
1093     /* Don't check for intermediate responses as it is unknown if any
1094      * intermediate responses are expected. Don't free the response, instead,
1095      * let calling function free the allocated response.
1096      */
1097
1098     if (err != AT_NOERROR)
1099         ALOGI(" --- %s", at_str_err(-err));
1100
1101     return -err;
1102 }
1103
1104 int at_send_command_singleline (const char *command,
1105                                 const char *responsePrefix,
1106                                  ATResponse **pp_outResponse, ...)
1107 {
1108     int err;
1109
1110     struct atcontext *ac = getAtContext();
1111     va_list ap;
1112     va_start(ap, pp_outResponse);
1113
1114     err = at_send_command_full (command, SINGLELINE, responsePrefix,
1115                                     NULL, ac->timeoutMsec, pp_outResponse, 1, ap);
1116
1117     if (err == AT_NOERROR && pp_outResponse != NULL
1118             && (*pp_outResponse) != NULL
1119             && (*pp_outResponse)->p_intermediates == NULL)
1120         /* Command with pp_outResponse must have an intermediate response */
1121         err = AT_ERROR_INVALID_RESPONSE;
1122
1123     /* Free response in case of error */
1124     if (err != AT_NOERROR && pp_outResponse != NULL
1125             && (*pp_outResponse) != NULL) {
1126         at_response_free(*pp_outResponse);
1127         *pp_outResponse = NULL;
1128     }
1129
1130     va_end(ap);
1131
1132     if (err != AT_NOERROR)
1133         ALOGI(" --- %s", at_str_err(-err));
1134
1135     return -err;
1136 }
1137
1138 int at_send_command_numeric (const char *command,
1139                                  ATResponse **pp_outResponse)
1140 {
1141     int err;
1142
1143     struct atcontext *ac = getAtContext();
1144
1145     err = at_send_command_full (command, NUMERIC, NULL,
1146                                 NULL, ac->timeoutMsec, pp_outResponse, 0, empty);
1147
1148     if (err == AT_NOERROR && pp_outResponse != NULL
1149             && (*pp_outResponse) != NULL
1150             && (*pp_outResponse)->p_intermediates == NULL)
1151         /* Command with pp_outResponse must have an intermediate response */
1152         err = AT_ERROR_INVALID_RESPONSE;
1153
1154     /* Free response in case of error */
1155     if (err != AT_NOERROR && pp_outResponse != NULL
1156             && (*pp_outResponse) != NULL) {
1157         at_response_free(*pp_outResponse);
1158         *pp_outResponse = NULL;
1159     }
1160
1161     if (err != AT_NOERROR)
1162         ALOGI(" --- %s", at_str_err(-err));
1163
1164     return -err;
1165 }
1166
1167
1168 int at_send_command_sms (const char *command,
1169                                 const char *pdu,
1170                                 const char *responsePrefix,
1171                                  ATResponse **pp_outResponse)
1172 {
1173     int err;
1174
1175     struct atcontext *ac = getAtContext();
1176
1177     err = at_send_command_full (command, SINGLELINE, responsePrefix,
1178                                     pdu, ac->timeoutMsec, pp_outResponse, 0, empty);
1179
1180     if (err == AT_NOERROR && pp_outResponse != NULL
1181             && (*pp_outResponse) != NULL
1182             && (*pp_outResponse)->p_intermediates == NULL)
1183         /* Command with pp_outResponse must have an intermediate response */
1184         err = AT_ERROR_INVALID_RESPONSE;
1185
1186     /* Free response in case of error */
1187     if (err != AT_NOERROR && pp_outResponse != NULL
1188             && (*pp_outResponse) != NULL) {
1189         at_response_free(*pp_outResponse);
1190         *pp_outResponse = NULL;
1191     }
1192
1193     if (err != AT_NOERROR)
1194         ALOGI(" --- %s", at_str_err(-err));
1195
1196     return -err;
1197 }
1198
1199
1200 int at_send_command_multiline (const char *command,
1201                                 const char *responsePrefix,
1202                                  ATResponse **pp_outResponse, ...)
1203 {
1204     int err;
1205
1206     struct atcontext *ac = getAtContext();
1207     va_list ap;
1208     va_start(ap, pp_outResponse);
1209
1210     err = at_send_command_full (command, MULTILINE, responsePrefix,
1211                                     NULL, ac->timeoutMsec, pp_outResponse, 1, ap);
1212     va_end(ap);
1213
1214     /* Free response in case of error */
1215     if (err != AT_NOERROR && pp_outResponse != NULL
1216             && (*pp_outResponse) != NULL) {
1217         at_response_free(*pp_outResponse);
1218         *pp_outResponse = NULL;
1219     }
1220
1221     if (err != AT_NOERROR)
1222         ALOGI(" --- %s", at_str_err(-err));
1223
1224     return -err;
1225 }
1226
1227 /**
1228  * Set the default timeout. Let it be reasonably high, some commands
1229  * take their time. Default is 10 minutes.
1230  */
1231 void at_set_timeout_msec(int timeout)
1232 {
1233     struct atcontext *ac = getAtContext();
1234
1235     ac->timeoutMsec = timeout;
1236 }
1237
1238 /** This callback is invoked on the command thread. */
1239 void at_set_on_timeout(void (*onTimeout)(void))
1240 {
1241     struct atcontext *ac = getAtContext();
1242
1243     ac->onTimeout = onTimeout;
1244 }
1245
1246
1247 /*
1248  * This callback is invoked on the reader thread (like ATUnsolHandler), when the
1249  * input stream closes before you call at_close (not when you call at_close()).
1250  * You should still call at_close(). It may also be invoked immediately from the
1251  * current thread if the read channel is already closed.
1252  */
1253 void at_set_on_reader_closed(void (*onClose)(void))
1254 {
1255     struct atcontext *ac = getAtContext();
1256
1257     ac->onReaderClosed = onClose;
1258 }
1259
1260
1261 /**
1262  * Periodically issue an AT command and wait for a response.
1263  * Used to ensure channel has start up and is active.
1264  */
1265 int at_handshake(void)
1266 {
1267     int i;
1268     int err = 0;
1269
1270     struct atcontext *ac = getAtContext();
1271
1272     if (0 != pthread_equal(ac->tid_reader, pthread_self()))
1273         /* Cannot be called from reader thread. */
1274         return AT_ERROR_INVALID_THREAD;
1275
1276     pthread_mutex_lock(&ac->commandmutex);
1277
1278     for (i = 0 ; i < HANDSHAKE_RETRY_COUNT ; i++) {
1279         /* Some stacks start with verbose off. */
1280         err = at_send_command_full_nolock ("ATE0Q0V1", NO_RESULT,
1281                     NULL, NULL, HANDSHAKE_TIMEOUT_MSEC, NULL);
1282
1283         if (err == 0)
1284             break;
1285     }
1286
1287     if (err == 0) {
1288         /* Pause for a bit to let the input buffer drain any unmatched OK's
1289            (they will appear as extraneous unsolicited responses). */
1290         ALOGD("%s() pausing %d ms to drain unmatched OK's...",
1291              __func__, HANDSHAKE_TIMEOUT_MSEC);
1292         sleepMsec(HANDSHAKE_TIMEOUT_MSEC);
1293     }
1294
1295     pthread_mutex_unlock(&ac->commandmutex);
1296
1297     return err;
1298 }
1299
1300 AT_Error at_get_at_error(int error)
1301 {
1302     error = -error;
1303     if (error >= AT_ERROR_BASE && error < AT_ERROR_TOP)
1304         return (AT_Error)(error - AT_ERROR_BASE);
1305     else
1306         return AT_ERROR_NON_AT;
1307     }
1308
1309 AT_CME_Error at_get_cme_error(int error)
1310 {
1311     error = -error;
1312     if (error >= CME_ERROR_BASE && error < CME_ERROR_TOP)
1313         return (AT_CME_Error)(error - CME_ERROR_BASE);
1314     else
1315         return CME_ERROR_NON_CME;
1316     }
1317
1318 AT_CMS_Error at_get_cms_error(int error)
1319 {
1320     error = -error;
1321     if (error >= CMS_ERROR_BASE && error < CMS_ERROR_TOP)
1322         return (AT_CMS_Error)(error - CMS_ERROR_BASE);
1323     else
1324         return CMS_ERROR_NON_CMS;
1325 }
1326
1327 AT_Generic_Error at_get_generic_error(int error)
1328 {
1329     error = -error;
1330     if (error >= GENERIC_ERROR_BASE && error < GENERIC_ERROR_TOP)
1331         return (AT_Generic_Error)(error - GENERIC_ERROR_BASE);
1332     else
1333         return GENERIC_ERROR_NON_GENERIC;
1334     }
1335
1336 AT_Error_type at_get_error_type(int error)
1337 {
1338     error = -error;
1339     if (error == AT_NOERROR)
1340         return NONE_ERROR;
1341
1342     if (error > AT_ERROR_BASE && error <= AT_ERROR_TOP)
1343         return AT_ERROR;
1344
1345     if (error >= CME_ERROR_BASE && error <= CME_ERROR_TOP)
1346         return CME_ERROR;
1347
1348     if (error >= CMS_ERROR_BASE && error <= CMS_ERROR_TOP)
1349         return CMS_ERROR;
1350
1351     if (error >= GENERIC_ERROR_BASE && error <= GENERIC_ERROR_TOP)
1352         return GENERIC_ERROR;
1353
1354     return UNKNOWN_ERROR;
1355     }
1356
1357 #define quote(x) #x
1358
1359 const char *at_str_err(int error)
1360 {
1361     const char *s = "--UNKNOWN--";
1362
1363     error = -error;
1364     switch(error) {
1365 #define AT(name, num) case num + AT_ERROR_BASE: s = quote(AT_##name); break;
1366 #define CME(name, num) case num + CME_ERROR_BASE: s = quote(CME_##name); break;
1367 #define CMS(name, num) case num + CMS_ERROR_BASE: s = quote(CMS_##name); break;
1368 #define GENERIC(name, num) case num + GENERIC_ERROR_BASE: s = quote(GENERIC_##name); break;
1369     mbm_error
1370 #undef AT
1371 #undef CME
1372 #undef CMS
1373 #undef GENERIC
1374 }
1375
1376     return s;
1377 }