1#include<stdio.h>
2#include<stdlib.h>
3#include"data.h"
4
5
6
7#define MYPORT 3570
8#define INOTIFY_PORT 3678
9#define BACKLOG 100 /* max listen num*/
10int no_config;
11int exit_loop = 0;
12int stop_progress;
13char username[256];
14char password[256];
15
16int is_renamed = 1;
17int access_token_expired;
18
19char *Clientfp="*";
20double start_time;
21
22#define MAXSIZE 512
23
24int write_trans_excep_log(char *fullname,int type,char *msg)
25{
26    FILE *fp = 0;
27    //int len;
28    char ctype[16] = {0};
29
30    if(type == 1)
31        strcpy(ctype,"Error");
32    else if(type == 2)
33        strcpy(ctype,"Info");
34    else if(type == 3)
35        strcpy(ctype,"Warning");
36
37
38    //printf("trans_excep_file=%s\n",trans_excep_file);
39
40    if(access(trans_excep_file,0) == 0)
41        fp = fopen(trans_excep_file,"a");
42    else
43        fp = fopen(trans_excep_file,"w");
44
45
46    if(fp == NULL)
47    {
48        printf("open %s fail\n",trans_excep_file);
49        return -1;
50    }
51
52    //len = strlen(mount_path);
53    fprintf(fp,"TYPE:%s\nUSERNAME:%s\nFILENAME:%s\nMESSAGE:%s\n",ctype,username,fullname,msg);
54    //fprintf(fp,"ERR_CODE:%d\nMOUNT_PATH:%s\nFILENAME:%s\nRULENUM:%d\n",
55                //err_code,mount_path,fullname+len,0);
56    fclose(fp);
57    return 0;
58}
59
60//int write_conflict_log(char *prename, char *conflict_name,int index)
61//{
62//    //wd_DEBUG("oldname=%s,newname=%s\n",prename,conflict_name);
63//    FILE *fp;
64
65//    if(access(g_pSyncList[index]->conflict_file,F_OK))
66//    {
67//        fp = fopen(g_pSyncList[index]->conflict_file,"w");
68//    }
69//    else
70//    {
71//        fp = fopen(g_pSyncList[index]->conflict_file,"a");
72//    }
73
74//     if(NULL == fp)
75//     {
76//         printf("open %s failed\n",g_pSyncList[index]->conflict_file);
77//         return -1;
78//     }
79
80//     fprintf(fp,"%s is download from server,%s is local file and rename from %s\n",prename,conflict_name,prename);
81//     fclose(fp);
82
83//     return 0;
84//}
85
86char *write_error_message(char *format,...)
87{
88    int size=256;
89    char *p=(char *)malloc(size);
90    memset(p,0,size);
91    va_list ap;
92    va_start(ap,format);
93    vsnprintf(p,size,format,ap);
94    va_end(ap);
95    return p;
96}
97
98#define GMTOFF(t) ((t).tm_gmtoff)
99
100static const char short_months[12][4] = {
101    "Jan", "Feb", "Mar", "Apr", "May", "Jun",
102    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
103};
104
105/* RFC1123: Sun, 06 Nov 1994 08:49:37 GMT */
106#define RFC1123_FORMAT "%3s, %02d %3s %4d %02d:%02d:%02d GMT"
107
108time_t ne_rfc1123_parse(const char *date)
109{
110    struct tm gmt = {0};
111    char wkday[4], mon[4];
112    int n;
113    time_t result;
114
115    /*  it goes: Sun, 06 Nov 1994 08:49:37 GMT */
116    n = sscanf(date, RFC1123_FORMAT,
117               wkday, &gmt.tm_mday, mon, &gmt.tm_year, &gmt.tm_hour,
118               &gmt.tm_min, &gmt.tm_sec);
119    /* Is it portable to check n==7 here? */
120    gmt.tm_year -= 1900;
121    for (n=0; n<12; n++)
122        if (strcmp(mon, short_months[n]) == 0)
123            break;
124    /* tm_mon comes out as 12 if the month is corrupt, which is desired,
125     * since the mktime will then fail */
126    gmt.tm_mon = n;
127    gmt.tm_isdst = -1;
128    result = mktime(&gmt);
129    //printf("%ld\n",GMTOFF(gmt));
130    return result + GMTOFF(gmt);
131}
132
133void buffer_free(char *b) {
134        if (!b) return;
135
136        free(b);
137        b = NULL;
138}
139
140char *parse_name_from_path(const char *path)
141{
142    char *name;
143    char *p;
144
145    p = strrchr(path,'/');
146
147    if( p == NULL)
148    {
149        //free(name);
150        return NULL;
151    }
152
153    p++;
154
155    name = (char *)malloc(sizeof(char)*(strlen(p)+2));
156    memset(name,0,strlen(p)+2);
157
158    strcpy(name,p);
159
160    return name;
161}
162void cjson_change_to_cloudfile(cJSON *q)
163{
164    //printf("q->string=%s\n",q->string);
165    if(strcmp(q->string,"bytes")==0)
166    {
167        FolderTmp->size=q->valueint;
168        //wd_DEBUG("%s:%lld\n",q->string,FolderTmp->size);
169    }
170    else if(strcmp(q->string,"path")==0)
171    {
172        FolderTmp->href=(char *)malloc(sizeof(char)*(strlen(q->valuestring)+1));
173        strcpy(FolderTmp->href,q->valuestring);
174        FolderTmp->name=parse_name_from_path(FolderTmp->href);
175        //wd_DEBUG("%s:%s\n",q->string,FolderTmp->href);
176        //wd_DEBUG("%s:%s\n",q->string,FolderTmp->name);
177    }
178    else if(strcmp(q->string,"is_dir")==0)
179    {
180        FolderTmp->isFolder=q->type;
181        //wd_DEBUG("%s:%d\n",q->string,FolderTmp->isFolder);
182    }
183    else if(strcmp(q->string,"modified")==0)
184    {
185        strcpy(FolderTmp->tmptime,q->valuestring);
186        FolderTmp->mtime=ne_rfc1123_parse(FolderTmp->tmptime);
187        //wd_DEBUG("%s:%s\n",q->string,FolderTmp->tmptime);
188    }
189}
190char *cJSON_parse_name(cJSON *json)
191{
192    char *name;
193    cJSON *q;
194    q=json->child;
195    int i=0;
196    while(q!=NULL)
197    {
198        if(strcmp(q->string,"path")==0)
199        {
200            wd_DEBUG("path : %s\n",q->valuestring);
201            //name=malloc(strlen(q->valuestring)+1);
202            //name=parse_name_from_path(q->valuestring);
203            //printf("name : %s\n",name);
204            return q->valuestring;
205        }
206        q=q->next;
207    }
208}
209time_t cJSON_printf_expires(cJSON *json)
210{
211    if(json)
212    {
213        time_t mtime=(time_t)-1;
214        cJSON *q;
215        q=json->child;
216        while(q!=NULL)
217        {
218            if(strcmp(q->string,"expires") == 0)
219            {
220                mtime=ne_rfc1123_parse(q->valuestring);
221            }
222            q=q->next;
223        }
224        return mtime;
225    }
226    else
227        return (time_t)-1;
228}
229
230int cJSON_printf_dir(cJSON *json)
231{
232    int flag = 0;
233
234    cJSON *q;
235    q=json->child;
236    while(q!=NULL)
237    {
238        if(strcmp(q->string,"is_deleted") == 0)
239        {
240            flag = q->type;
241            return flag;
242        }
243        q=q->next;
244    }
245    return flag;
246
247}
248
249time_t cJSON_printf_mtime(cJSON *json)
250{
251    if(json)
252    {
253        time_t mtime=(time_t)-1;
254        cJSON *q;
255        q=json->child;
256        while(q!=NULL)
257        {
258            if(strcmp(q->string,"modified") == 0)
259            {
260                mtime=ne_rfc1123_parse(q->valuestring);
261            }
262            else if(strcmp(q->string,"is_deleted") == 0)
263            {
264                if(q->type)
265                    return (time_t)-1;
266            }
267            q=q->next;
268        }
269        return mtime;
270    }
271    else
272        return (time_t)-1;
273}
274/*
275 FileTail_one is not only file list ,it is also folder list
276*/
277int cJSON_printf_one(cJSON *json)
278{
279    if(json)
280    {
281        cJSON *p,*q,*m;
282        q=json->child;
283        int i=0;
284        while(q!=NULL)
285        {
286            //printf("%s:\n",q->string);
287            if(strcmp(q->string,"contents")==0)
288            {
289                if(q->child!=NULL){
290                    p=q->child;m=p->child;
291                    while(p!=NULL)
292                    {
293                        FolderTmp = (CloudFile *)malloc(sizeof(CloudFile));
294                        memset(FolderTmp,0,sizeof(CloudFile));
295                        FolderTmp->href=NULL;
296
297                        m=p->child;i++;
298                        while(m!=NULL)
299                        {
300                            //printf("%s:\n",m->string);
301                            cjson_change_to_cloudfile(m);
302                            m=m->next;
303                        }
304                        //if(FolderTmp->isFolder==0)
305                        //{
306                        FileTail_one->next = FolderTmp;
307                        FileTail_one = FolderTmp;
308                        FileTail_one->next = NULL;
309                        //}
310                        p=p->next;
311                    }
312                    break;
313                }
314                else
315                    wd_DEBUG("this is empty folder\n");
316            }
317            q=q->next;
318        }
319    }
320
321}
322time_t cJSON_printf(cJSON *json,char *string)
323{
324    if(json)
325    {
326        cJSON *p,*q,*m;
327        q=json->child;
328        int i=0;
329        while(q!=NULL)
330        {
331            //printf("%s:\n",q->string);
332            if(strcmp(q->string,"contents")==0)
333            {
334                if(strcmp(string,"contents")==0)
335                {
336                    if(q->child!=NULL){
337                        p=q->child;m=p->child;
338                        while(p!=NULL)
339                        {
340                            FolderTmp = (CloudFile *)malloc(sizeof(CloudFile));
341                            memset(FolderTmp,0,sizeof(CloudFile));
342                            FolderTmp->href=NULL;
343
344                            m=p->child;i++;
345                            while(m!=NULL)
346                            {
347                                //printf("%s:\n",m->string);
348                                cjson_change_to_cloudfile(m);
349                                m=m->next;
350                            }
351                            if(FolderTmp->isFolder==0)
352                            {
353                                TreeFileTail->next = FolderTmp;
354                                TreeFileTail = FolderTmp;
355                                TreeFileTail->next = NULL;
356                            }
357                            else if(FolderTmp->isFolder==1)
358                            {
359                                TreeFolderTail->next = FolderTmp;
360                                TreeFolderTail = FolderTmp;
361                                TreeFolderTail->next = NULL;
362                            }
363                            p=p->next;
364                        }
365                        break;
366                    }
367                    else
368                    {
369                        //wd_DEBUG("this is empty folder\n");
370                    }
371                }
372            }
373            else if(strcmp(q->string,"modified") == 0)
374            {
375                if(strcmp(string,"modified") == 0)
376                {
377                    time_t mtime=ne_rfc1123_parse(q->valuestring);
378                    return mtime;
379                }
380            }
381            else if(strcmp(q->string,"quota_info") == 0)
382            {
383                //wd_DEBUG("q->string = %s\n",q->string);
384                if(strcmp(string,"quota_info") == 0)
385                {
386                    if(q->child != NULL)
387                    {
388                        p=q->child;m=p->child;
389                        while(p!=NULL)
390                        {
391                            //wd_DEBUG("p->string = %s\n",p->string);
392                            cjson_to_space(p);
393                            p=p->next;
394                        }
395                    }
396                }
397            }
398            q=q->next;
399        }
400    }
401    else
402        return (time_t)-1;
403
404}
405
406void cjson_to_space(cJSON *q)
407{
408    //printf("q->string = %s,q->valueint = %d,q->valuedouble = %lf,q->valuelong = %lld\n",q->string,q->valueint,q->valuedouble,q->valuelong);
409    if(strcmp(q->string,"shared") == 0)
410    {
411        server_shared=q->valuelong;
412    }
413    else if(strcmp(q->string,"quota") == 0)
414    {
415        server_quota=q->valuelong;
416    }
417    else if(strcmp(q->string,"normal") == 0)
418    {
419        server_normal=q->valuelong;
420    }
421}
422cJSON *doit(char *text)
423{
424    char *out;cJSON *json;
425
426    json=cJSON_Parse(text);
427    if (!json) {wd_DEBUG("Error before: [%s]\n",cJSON_GetErrorPtr());return NULL;}
428    else
429    {
430        return json;
431        //cJSON_printf(json);
432        //cJSON_Delete(json);
433        //printf("%s\n",out);
434        //free(out);
435    }
436}
437
438/* Read a file, parse, render back, etc. */
439cJSON *dofile(char *filename)
440{
441    cJSON *json;
442    FILE *f=fopen(filename,"rb");fseek(f,0,SEEK_END);long len=ftell(f);fseek(f,0,SEEK_SET);
443    char *data=malloc(len+1);fread(data,1,len,f);fclose(f);
444    json=doit(data);
445    free(data);
446    if(json)
447        return json;
448    else
449        return NULL;
450}
451#ifdef OAuth1
452int open_login_page_first()
453{
454    char Myurl[MAXSIZE];
455    memset(Myurl,0,sizeof(Myurl));
456
457    //const char url[]="https://www.dropbox.com/login?cont=https%3A//www.dropbox.com/1/oauth/authorize%3Foauth_token%3Dss4olgz45siiwdd&signup_tag=oauth&signup_data=177967";
458    sprintf(Myurl,"%s","https://www.dropbox.com/login");
459    //sprintf(Myurl,"%s%s%s","https://www.dropbox.com/login?cont=https%3A//www.dropbox.com/1/oauth/authorize%3Foauth_token\%3D",auth->tmp_oauth_token,"&signup_tag=oauth&signup_data=177967");
460    wd_DEBUG("Myurl:%s\n",Myurl);
461    CURL *curl;
462    CURLcode res;
463    FILE *fp;
464
465    //curl_global_init(CURL_GLOBAL_ALL);
466    curl=curl_easy_init();
467    if(curl){
468        struct curl_slist *headers_l=NULL;
469        static const char header1_l[]="Host:www.dropbox.com";
470        static const char header2_l[]="Mozilla/5.0 (Windows NT 6.1; rv:17.0) Gecko/20100101 Firefox/17.0";
471        static const char header3_l[]="Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
472        static const char header4_l[]="zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3";
473        //static const char header5_l[]="Accept-Encoding:gzip, deflate";
474        static const char header6_l[]="Connection:keep-alive";
475        //static const char header7_l[]="Referer:https://www.box.net/api/1.0/auth/a26uln89kmbh0h97e0zxl6jffxnef19f";
476        //static const char header8_l[]="Content-Type:application/x-www-form-urlencoded";
477        //static const char header9_l[]="Content-Length:237";
478
479        headers_l=curl_slist_append(headers_l,header1_l);
480        headers_l=curl_slist_append(headers_l,header2_l);
481        headers_l=curl_slist_append(headers_l,header3_l);
482        headers_l=curl_slist_append(headers_l,header4_l);
483        //headers_l=curl_slist_append(headers_l,header5_l);
484        headers_l=curl_slist_append(headers_l,header6_l);
485        //headers_l=curl_slist_append(headers_l,header7_l);
486        //headers_l=curl_slist_append(headers_l,header8_l);
487        //headers_l=curl_slist_append(headers_l,header9_l);
488        curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,0L);
489        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
490        curl_easy_setopt(curl,CURLOPT_URL,Myurl);
491        //curl_easy_setopt(curl,CURLOPT_VERBOSE,1);
492        curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headers_l);
493
494        //curl_easy_setopt(curl,CURLOPT_COOKIEJAR,"/tmp/cookie_open.txt");
495        curl_easy_setopt(curl,CURLOPT_COOKIEJAR,Con(TMP_R,cookie_open.txt));
496
497        //#ifdef SKIP_PEER_VERIFICATION
498        curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,0);
499        //#endif
500
501#ifdef SKIP_HOSTNAME_VERFICATION
502        curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,0L);
503#endif
504
505        fp=fopen(Con(TMP_R,xmldate1.xml),"w");
506
507        //fp1=fopen("file.txt","w");
508        if(fp==NULL){
509            curl_easy_cleanup(curl);
510            curl_slist_free_all(headers_l);
511            //curl_global_cleanup();
512            return -1;
513        }
514        curl_easy_setopt(curl,CURLOPT_CONNECTTIMEOUT,60);
515        //curl_easy_setopt(curl,CURLOPT_WRITEHEADER,fp1);
516        curl_easy_setopt(curl,CURLOPT_WRITEDATA,fp);
517        res=curl_easy_perform(curl);
518        fclose(fp);
519        curl_easy_cleanup(curl);
520        curl_slist_free_all(headers_l);
521        if(res != 0){
522            //curl_global_cleanup();
523            wd_DEBUG("open_login_page [%d] failed!\n",res);
524            return -1;
525        }
526    }
527    else
528        wd_DEBUG("url is wrong!!!");
529
530    //curl_global_cleanup();
531
532
533}
534int
535        login_first(void){
536
537    CURL *curl;
538    CURLcode res;
539    FILE *fp;
540    char Myurl[MAXSIZE]="\0";
541    //char url[]="https://www.box.net/api/1.0/auth/";
542    //sprintf(Myurl,"%s%s%s","https://www.dropbox.com/login?cont=https%3A//www.dropbox.com/1/oauth/authorize%3Foauth_token\%3D",auth->tmp_oauth_token,"&signup_tag=oauth&signup_data=177967");
543    char *data=parse_login_page();
544    //sprintf(Myurl,"%s?%s%s","https://www.dropbox.com/1/oauth/authorize","oauth_token=",auth->tmp_oauth_token);
545    sprintf(Myurl,"%s","https://www.dropbox.com/login");
546    struct curl_slist *headerlist=NULL;
547    static const char buf[]="Expect:";
548    //printf("data=%s\n",data);
549    //char *data=parse_login_page();
550
551    //curl_global_init(CURL_GLOBAL_ALL);
552    curl=curl_easy_init();
553    headerlist=curl_slist_append(headerlist,buf);
554
555    if(curl){
556        curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,0L);
557        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
558        curl_easy_setopt(curl,CURLOPT_URL,Myurl);
559        //curl_easy_setopt(curl,CURLOPT_URL,url);
560        //curl_easy_setopt(curl,CURLOPT_VERBOSE,1);
561        curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headerlist);
562        curl_easy_setopt(curl,CURLOPT_POSTFIELDS,data);
563
564        curl_easy_setopt(curl,CURLOPT_COOKIEFILE,Con(TMP_R,cookie_open.txt));//send first saved cookie
565        curl_easy_setopt(curl,CURLOPT_COOKIEJAR,Con(TMP_R,cookie_login.txt));
566
567        curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,0);
568
569
570//#ifdef SKIP_HOSTNAME_VERFICATION
571//        curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,0L);
572//#endif
573        fp=fopen(Con(TMP_R,xmldate2.xml),"w");
574
575        if(fp==NULL){
576            curl_easy_cleanup(curl);
577            curl_slist_free_all(headerlist);
578            free(data);
579            //curl_global_cleanup();
580            return -1;
581        }
582
583        curl_easy_setopt(curl,CURLOPT_WRITEDATA,fp);
584
585        res=curl_easy_perform(curl);
586
587        curl_easy_cleanup(curl);
588        fclose(fp);
589        curl_slist_free_all(headerlist);
590        //curl_global_cleanup();
591
592        if(res != 0){
593
594            free(data);
595            wd_DEBUG("login_first [%d] failed!\n",res);
596            return -1;
597        }
598
599    }
600    free(data);
601    return 0;
602}
603
604char *parse_login_page()
605{
606    FILE *fp;
607    char *p,*m;
608    char *s="name=\"t\" value=";
609    char buf[1024],buff[100];
610    char cont[256]="\0";
611    char *data=NULL;
612    data=(char *)malloc(sizeof(char *)*1024);
613    memset(data,0,1024);
614    char *url="https://www.dropbox.com/1/oauth/authorize";
615    sprintf(cont,"%s?oauth_token=%s",url,auth->tmp_oauth_token);
616    //sprintf(cont,"%s?oauth_token=%s",url,"s1unnz0qytb4j35");
617    memset(buf,'\0',sizeof(buf));
618    memset(buff,'\0',sizeof(buff));
619
620    fp=fopen(Con(TMP_R,xmldate1.xml),"r");
621
622    while(!feof(fp)){
623        fgets(buf,1024,fp);
624        p=strstr(buf,s);
625        if(p!=NULL){
626            //strcat(buff,p);
627            m=p;
628            p=NULL;
629            break;
630        }
631    }
632    m=m+strlen(s)+1;
633    p=strchr(m,'"');
634    strncpy(buff,m,strlen(m)-strlen(p));
635    char *cont_tmp=oauth_url_escape(cont);
636    char *usr_tmp=oauth_url_escape(asus_cfg.user);
637    char *pwd_tmp=oauth_url_escape(asus_cfg.pwd);
638    //sprintf(data,"t=%s&lhs_type=default&cont=%s&signup_tag=oauth&signup_data=177967&login_email=%s&login_password=%s&%s&%s&%s",
639    //        buff,oauth_url_escape(cont),oauth_url_escape(info->usr),oauth_url_escape(info->pwd),"login_submit=1","remember_me=on","login_submit_dummy=Sign+in");
640#if 1
641    sprintf(data,"t=%s&lhs_type=default&cont=%s&signup_tag=oauth&signup_data=177967&login_email=%s&login_password=%s&%s&%s&%s",
642            buff,cont_tmp,usr_tmp,pwd_tmp,"login_submit=1","remember_me=on","login_submit_dummy=Sign+in");
643#else
644    sprintf(data,"t=%s&cont=%s&signup_tag=oauth&signup_data=177967&display=desktop&login_email=%s&login_password=%s&%s&%s&%s",
645            buff,cont_tmp,usr_tmp,pwd_tmp,"login_submit=1","remember_me=on","login_submit_dummy=Sign+in");
646#endif
647    //printf("m=%s\nbuff=%s\ndata=%s\n",m,buff,data);
648    fclose(fp);
649    free(cont_tmp);
650    free(usr_tmp);
651    free(pwd_tmp);
652    return data;
653
654}
655char *parse_cookie()
656{
657    FILE *fp;
658
659    fp=fopen(Con(TMP_R,/cookie_login.txt),"r");
660
661    char buf[1024]="\0";
662    const char *m="	";
663    char *p;
664    char *s="gvc";
665
666    while(!feof(fp)){
667        fgets(buf,1024,fp);
668        //printf("buf=%s\n",buf);
669        p=strstr(buf,s);
670        if(p!=NULL){
671            //strcat(buff,p);
672            break;
673        }
674    }
675    fgets(buf,1024,fp);
676    //printf("buf=%s\n",buf);
677    char *cookie;
678    cookie=malloc(128);
679    memset(cookie,0,128);
680    p=strtok(buf,m);
681
682    int i=0;
683    while(p!=NULL)
684    {
685        switch (i)
686        {
687        case 6:
688            strcpy(cookie,p);
689            break;
690        case 1:
691            break;
692        default:
693            break;
694        }
695        i++;
696        p=strtok(NULL,m);
697    }
698    //printf("%c\n",cookie[strlen(buf)+1]);
699    if(cookie[strlen(buf)+2] == '\n')
700    {
701        cookie[strlen(buf)+2] = '\0';
702    }
703    fclose(fp);
704    //printf("cookie=%s\n",cookie);
705    //free(cookie);
706    return cookie;
707
708}
709int login_second()
710{
711    CURL *curl;
712    CURLcode res;
713    FILE *fp;
714    char Myurl[MAXSIZE]="\0";
715    //char url[]="https://www.box.net/api/1.0/auth/";
716    //sprintf(Myurl,"%s%s%s","https://www.dropbox.com/login?cont=https%3A//www.dropbox.com/1/oauth/authorize%3Foauth_token\%3D",auth->tmp_oauth_token,"&signup_tag=oauth&signup_data=177967");
717    //char *data=parse_login_page();
718    char *data=malloc(256);
719    memset(data,0,256);
720    char *cookie=parse_cookie();
721#if 1
722    sprintf(data,"t=%s&allow_access=Allow&oauth_token=%s&display&osx_protocol",cookie,auth->tmp_oauth_token);
723#else
724    sprintf(data,"t=%s&allow_access=Allow&saml_assertion&embedded&osx_protocol&oauth_token=%s&display&oauth_callback&user_id=150377145",cookie,auth->tmp_oauth_token);
725#endif
726    //sprintf(Myurl,"%s?%s%s","https://www.dropbox.com/1/oauth/authorize","oauth_token=",auth->tmp_oauth_token);
727#if 1
728    sprintf(Myurl,"%s","https://www.dropbox.com/1/oauth/authorize");
729#else
730    sprintf(Myurl,"%s","https://www.dropbox.com/1/oauth/authorize_submit");
731#endif
732    struct curl_slist *headerlist=NULL;
733    static const char buf[]="Expect:";
734    //printf("data=%s\n",data);
735    //char *data=parse_login_page();
736
737    //curl_global_init(CURL_GLOBAL_ALL);
738    curl=curl_easy_init();
739    headerlist=curl_slist_append(headerlist,buf);
740
741    if(curl){
742        curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,0L);
743        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
744        curl_easy_setopt(curl,CURLOPT_URL,Myurl);
745        //curl_easy_setopt(curl,CURLOPT_URL,url);
746        //curl_easy_setopt(curl,CURLOPT_VERBOSE,1);
747        curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headerlist);
748        curl_easy_setopt(curl,CURLOPT_POSTFIELDS,data);
749
750
751        curl_easy_setopt(curl,CURLOPT_COOKIEFILE,Con(TMP_R,cookie_login.txt));//send first saved cookie
752        curl_easy_setopt(curl,CURLOPT_COOKIEJAR,Con(TMP_R,tmp/cookie_login_2.txt));
753
754
755        curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,0);
756
757
758#ifdef SKIP_HOSTNAME_VERFICATION
759        curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,0L);
760#endif
761
762        fp=fopen(Con(TMP_R,xmldate3.xml),"w");
763
764
765        if(fp==NULL){
766            curl_easy_cleanup(curl);
767            free(data);
768            free(cookie);
769            curl_slist_free_all(headerlist);
770            //curl_global_cleanup();
771            return -1;
772        }
773
774        curl_easy_setopt(curl,CURLOPT_WRITEDATA,fp);
775
776        res=curl_easy_perform(curl);
777
778        curl_easy_cleanup(curl);
779        fclose(fp);
780        curl_slist_free_all(headerlist);
781        //curl_global_cleanup();
782        if(res != 0){
783            free(data);
784            free(cookie);
785            wd_DEBUG("login_second [%d] failed!\n",res);
786            return -1;
787        }
788
789    }
790
791    free(data);
792    free(cookie);
793    return 0;
794}
795
796char *pare_login_second_response()
797{
798    FILE *f=fopen(Con(TMP_R,xmldate3.xml),"rb");fseek(f,0,SEEK_END);long len=ftell(f);fseek(f,0,SEEK_SET);
799    char *data=malloc(len+1);fread(data,1,len,f);fclose(f);
800    char *s="name=\"user_id\" value=\"";
801    char *sb="\"";
802    char *p = NULL;
803    char *pt = NULL;
804    char *user_id = NULL;
805    int user_id_length;
806    p=strstr(data,s);
807    if(p!=NULL){
808        //printf("buf=%s\n",buf);
809        p+=strlen(s);
810        pt = strstr(p,sb);
811        user_id_length = strlen(p) - strlen(pt);
812        user_id = malloc(user_id_length+1);
813        memset(user_id,0,user_id_length+1);
814        printf("p=%s\n",p);
815        printf("pt=%s\n",pt);
816        snprintf(user_id,user_id_length+1,"%s",p);
817    }
818    my_free(data);
819
820
821//    FILE *fp = NULL;
822//    fp = fopen(Con(TMP_R,xmldate3.xml),"r");
823//    char buf[512] ="\0";
824//    char *s="name=\"user_id\" value=\"";
825//    char *sb="\"";
826//    char *p = NULL;
827//    char *pt = NULL;
828//    char *user_id = NULL;
829//    int user_id_length;
830//    while(!feof(fp)){
831//        fgets(buf,512,fp);
832//        printf("buf=%s\n",buf);
833//        p=strstr(buf,s);
834//        if(p!=NULL){
835//            printf("buf=%s\n",buf);
836//            p+=strlen(s);
837//            pt = strstr(p,sb);
838//            user_id_length = strlen(p) - strlen(pt);
839//            user_id = malloc(user_id_length+1);
840//            memset(user_id,0,user_id_length+1);
841//            printf("p=%s\n",p);
842//            printf("pt=%s\n",pt);
843//            snprintf(user_id,user_id_length+1,"%s",p);
844//            break;
845//        }
846//    }
847//    fclose(fp);
848    wd_DEBUG("user_id = %s\n",user_id);
849    return user_id;
850}
851
852int login_second_submit()
853{
854    CURL *curl;
855    CURLcode res;
856    FILE *fp;
857    char Myurl[MAXSIZE]="\0";
858    //char url[]="https://www.box.net/api/1.0/auth/";
859    //sprintf(Myurl,"%s%s%s","https://www.dropbox.com/login?cont=https%3A//www.dropbox.com/1/oauth/authorize%3Foauth_token\%3D",auth->tmp_oauth_token,"&signup_tag=oauth&signup_data=177967");
860    //char *data=parse_login_page();
861    char *data=malloc(256);
862    memset(data,0,256);
863    char *cookie=parse_cookie();
864    char *user_id = pare_login_second_response();
865#if 0
866    sprintf(data,"t=%s&allow_access=Allow&oauth_token=%s&display&osx_protocol",cookie,auth->tmp_oauth_token);
867#else
868    sprintf(data,"t=%s&allow_access=Allow&saml_assertion&embedded&osx_protocol&oauth_token=%s&display&oauth_callback&user_id=%s",cookie,auth->tmp_oauth_token,user_id);
869#endif
870    //sprintf(Myurl,"%s?%s%s","https://www.dropbox.com/1/oauth/authorize","oauth_token=",auth->tmp_oauth_token);
871#if 0
872    sprintf(Myurl,"%s","https://www.dropbox.com/1/oauth/authorize");
873#else
874    sprintf(Myurl,"%s","https://www.dropbox.com/1/oauth/authorize_submit");
875#endif
876    free(user_id);
877    struct curl_slist *headerlist=NULL;
878    static const char buf[]="Expect:";
879    //printf("data=%s\n",data);
880    //char *data=parse_login_page();
881
882    //curl_global_init(CURL_GLOBAL_ALL);
883    curl=curl_easy_init();
884    headerlist=curl_slist_append(headerlist,buf);
885
886    if(curl){
887        curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,0L);
888        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
889        curl_easy_setopt(curl,CURLOPT_URL,Myurl);
890        //curl_easy_setopt(curl,CURLOPT_URL,url);
891        //curl_easy_setopt(curl,CURLOPT_VERBOSE,1);
892        curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headerlist);
893        curl_easy_setopt(curl,CURLOPT_POSTFIELDS,data);
894
895
896        curl_easy_setopt(curl,CURLOPT_COOKIEFILE,Con(TMP_R,cookie_login.txt));//send first saved cookie
897        curl_easy_setopt(curl,CURLOPT_COOKIEJAR,Con(TMP_R,tmp/cookie_login_3.txt));
898
899
900        curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,0);
901
902
903#ifdef SKIP_HOSTNAME_VERFICATION
904        curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,0L);
905#endif
906
907        fp=fopen(Con(TMP_R,xmldate4.xml),"w");
908
909
910        if(fp==NULL){
911            curl_easy_cleanup(curl);
912            free(data);
913            free(cookie);
914            curl_slist_free_all(headerlist);
915            //curl_global_cleanup();
916            return -1;
917        }
918
919        curl_easy_setopt(curl,CURLOPT_WRITEDATA,fp);
920
921        res=curl_easy_perform(curl);
922
923        curl_easy_cleanup(curl);
924        fclose(fp);
925        curl_slist_free_all(headerlist);
926        //curl_global_cleanup();
927        if(res != 0){
928            free(data);
929            free(cookie);
930            wd_DEBUG("login_second_submit [%d] failed!\n",res);
931            return -1;
932        }
933
934    }
935
936    free(data);
937    free(cookie);
938    return 0;
939}
940int get_access_token()
941{
942    CURL *curl;
943    CURLcode res;
944    FILE *fp;
945    char *header;
946    static const char buf[]="Expect:";
947    header=makeAuthorize(2);
948    struct curl_slist *headerlist=NULL;
949    curl=curl_easy_init();
950    headerlist=curl_slist_append(headerlist,header);
951    if(curl){
952        curl_easy_setopt(curl,CURLOPT_URL,"https://api.dropbox.com/1/oauth/access_token");
953        CURL_DEBUG;
954        curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headerlist);
955        curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,0L);
956        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
957        //curl_easy_setopt(curl,CURLOPT_POSTFIELDS,"");
958        //curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,0);
959
960        fp=fopen(Con(TMP_R,data_2.txt),"w");
961
962        curl_easy_setopt(curl,CURLOPT_WRITEDATA,fp);
963        res=curl_easy_perform(curl);
964
965        curl_easy_cleanup(curl);
966        fclose(fp);
967        curl_slist_free_all(headerlist);
968        if(res!=0){
969            free(header);
970            wd_DEBUG("get_access_token [%d] failed!\n",res);
971            return res;
972        }
973    }
974    free(header);
975    int status;
976    status=parse(Con(TMP_R,data_2.txt),2);
977    if(status==-1)
978        return -1;
979    return 0;
980}
981#endif
982int api_accout_info()
983{
984    CURL *curl;
985    CURLcode res;
986    FILE *fp;
987    char *header;
988    static const char buf[]="Expect:";
989#ifdef OAuth1
990    header=makeAuthorize(3);
991#else
992    header=makeAuthorize(1);
993#endif
994    struct curl_slist *headerlist=NULL;
995    curl=curl_easy_init();
996    headerlist=curl_slist_append(headerlist,header);
997    if(curl){
998        curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,0L);
999        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
1000        curl_easy_setopt(curl,CURLOPT_URL,"https://api.dropbox.com/1/account/info");
1001        CURL_DEBUG;
1002        curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headerlist);
1003        //curl_easy_setopt(curl,CURLOPT_POSTFIELDS,"");
1004        //curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,0);
1005        fp=fopen(Con(TMP_R,data_3.txt),"w");
1006        curl_easy_setopt(curl,CURLOPT_TIMEOUT,90);
1007        curl_easy_setopt(curl,CURLOPT_WRITEDATA,fp);
1008        res=curl_easy_perform(curl);
1009
1010        curl_easy_cleanup(curl);
1011        fclose(fp);
1012        curl_slist_free_all(headerlist);
1013        if(res!=0){
1014            free(header);
1015            wd_DEBUG("get server space failed , id [%d] !\n",res);
1016            return -1;
1017        }
1018    }
1019    free(header);
1020    return 0;
1021}
1022int api_metadata_one(char *phref,cJSON *(*cmd_data)(char *filename))
1023{
1024    CURL *curl;
1025    CURLcode res;
1026    FILE *fp;
1027    char *myUrl;
1028    char *phref_tmp=oauth_url_escape(phref);
1029    myUrl=(char *)malloc(sizeof(char)*(strlen(phref_tmp)+128));
1030    memset(myUrl,0,strlen(phref_tmp)+128);
1031    sprintf(myUrl,"%s%s","https://api.dropbox.com/1/metadata/dropbox",phref_tmp);
1032    free(phref_tmp);
1033    char *header;
1034#ifdef OAuth1
1035    header=makeAuthorize(3);
1036#else
1037    header=makeAuthorize(1);
1038#endif
1039    struct curl_slist *headerlist=NULL;
1040    curl=curl_easy_init();
1041    headerlist=curl_slist_append(headerlist,header);
1042    if(curl){
1043        curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,0L);
1044        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
1045        //curl_easy_setopt(curl,CURLOPT_URL,"https://api.dropbox.com/1/metadata/dropbox/oauth_plaintext_example/main.py?list=true&rev=120e60305d");
1046        //curl_easy_setopt(curl,CURLOPT_URL,"https://api.dropbox.com/1/metadata/dropbox/main");
1047        curl_easy_setopt(curl,CURLOPT_URL,myUrl);
1048        CURL_DEBUG;
1049        curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headerlist);
1050        //curl_easy_setopt(curl,CURLOPT_POSTFIELDS,"");
1051        //curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,0);
1052        fp=fopen(Con(TMP_R,data_one.txt),"w");
1053        curl_easy_setopt(curl,CURLOPT_TIMEOUT,90);
1054        curl_easy_setopt(curl,CURLOPT_WRITEDATA,fp);
1055        res=curl_easy_perform(curl);
1056
1057        curl_easy_cleanup(curl);
1058        fclose(fp);
1059        curl_slist_free_all(headerlist);
1060        if(res!=0){
1061            free(header);
1062            free(myUrl);
1063            wd_DEBUG("api_metadata_one [%d] failed!\n",res);
1064            return -1;
1065        }
1066    }
1067    free(myUrl);
1068    free(header);
1069    cJSON *json;
1070    json=cmd_data(Con(TMP_R,data_one.txt));
1071    if(json){
1072        cJSON_printf_one(json);
1073        cJSON_Delete(json);
1074        return 0;
1075    }else
1076        return -1;
1077}
1078int api_metadata_test_dir(char *phref,proc_pt cmd_data)
1079{
1080    CURL *curl;
1081    CURLcode res;
1082    FILE *fp;
1083    FILE *hd;
1084    char *myUrl;
1085    myUrl=(char *)malloc(sizeof(char)*(strlen(phref)+128));
1086    memset(myUrl,0,strlen(phref)+128);
1087    sprintf(myUrl,"%s%s%s","https://api.dropbox.com/1/metadata/dropbox",phref,"?list=false&include_deleted=true");
1088    char *header;
1089#ifdef OAuth1
1090    header=makeAuthorize(3);
1091#else
1092    header=makeAuthorize(1);
1093#endif
1094    struct curl_slist *headerlist=NULL;
1095    curl=curl_easy_init();
1096    headerlist=curl_slist_append(headerlist,header);
1097    if(curl){
1098        //curl_easy_setopt(curl,CURLOPT_URL,"https://api.dropbox.com/1/metadata/dropbox/oauth_plaintext_example/main.py?list=true&rev=120e60305d");
1099        //curl_easy_setopt(curl,CURLOPT_URL,"https://api.dropbox.com/1/metadata/dropbox/main");
1100        curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,0L);
1101        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
1102        curl_easy_setopt(curl,CURLOPT_URL,myUrl);
1103        curl_easy_setopt(curl,CURLOPT_VERBOSE,1);
1104        curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headerlist);
1105        //curl_easy_setopt(curl,CURLOPT_POSTFIELDS,"");
1106        //curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,0);
1107        fp=fopen(Con(TMP_R,data_test_dir.txt),"w");
1108        hd=fopen(Con(TMP_R,data_test_dir_header.txt),"w+");
1109        curl_easy_setopt(curl,CURLOPT_WRITEDATA,fp);
1110        curl_easy_setopt(curl,CURLOPT_WRITEHEADER,hd);
1111        res=curl_easy_perform(curl);
1112
1113        curl_easy_cleanup(curl);
1114        fclose(fp);
1115        curl_slist_free_all(headerlist);
1116        if(res!=0){
1117            fclose(hd);
1118            free(header);
1119            free(myUrl);
1120            wd_DEBUG("api_metadata_test [%d] failed!\n",res);
1121            return -1;
1122        }
1123        else
1124        {
1125            rewind(hd);
1126            char tmp[256]="\0";
1127            while(!feof(hd))
1128            {
1129                fgets(tmp,sizeof(tmp),hd);
1130                printf("tmp_ : %s\n",tmp);
1131                if(strstr(tmp,"404") != NULL)
1132                {
1133                    free(myUrl);
1134                    free(header);
1135                    fclose(hd);
1136                    return -1;
1137                }
1138                else if(strstr(tmp,"200 OK") != NULL)
1139                    break;
1140            }
1141            fclose(hd);
1142        }
1143    }
1144    free(myUrl);
1145    free(header);
1146
1147    int rs = 0;
1148    cJSON *json;
1149    json=cmd_data(Con(TMP_R,data_test_dir.txt));
1150    if(json){
1151        rs = cJSON_printf_dir(json);
1152        cJSON_Delete(json);
1153        return rs;
1154    }else
1155        return -1;
1156}
1157int api_metadata_test(char *phref)
1158{
1159    CURL *curl;
1160    CURLcode res;
1161    FILE *fp;
1162    char *myUrl;
1163    myUrl=(char *)malloc(sizeof(char)*(strlen(phref)+128));
1164    memset(myUrl,0,strlen(phref)+128);
1165    sprintf(myUrl,"%s%s%s","https://api.dropbox.com/1/metadata/dropbox",phref,"?list=true&include_deleted=true");
1166    char *header;
1167#ifdef OAuth1
1168    header=makeAuthorize(3);
1169#else
1170    header=makeAuthorize(1);
1171#endif
1172    struct curl_slist *headerlist=NULL;
1173    curl=curl_easy_init();
1174    headerlist=curl_slist_append(headerlist,header);
1175    if(curl){
1176        //curl_easy_setopt(curl,CURLOPT_URL,"https://api.dropbox.com/1/metadata/dropbox/oauth_plaintext_example/main.py?list=true&rev=120e60305d");
1177        //curl_easy_setopt(curl,CURLOPT_URL,"https://api.dropbox.com/1/metadata/dropbox/main");
1178        curl_easy_setopt(curl,CURLOPT_URL,myUrl);
1179        curl_easy_setopt(curl,CURLOPT_VERBOSE,1);
1180        curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headerlist);
1181        //curl_easy_setopt(curl,CURLOPT_POSTFIELDS,"");
1182        //curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,0);
1183        fp=fopen(Con(TMP_R,data_test.txt),"w");
1184        curl_easy_setopt(curl,CURLOPT_WRITEDATA,fp);
1185        res=curl_easy_perform(curl);
1186
1187        curl_easy_cleanup(curl);
1188        fclose(fp);
1189        curl_slist_free_all(headerlist);
1190        if(res!=0){
1191            free(header);
1192            free(myUrl);
1193            wd_DEBUG("api_metadata_test [%d] failed!\n",res);
1194            return -1;
1195        }
1196    }
1197    free(myUrl);
1198    free(header);
1199    return 0;
1200}
1201//int api_metadata(char *phref,cJSON *(*cmd_data)(char *filename))
1202int api_metadata(char *phref,proc_pt cmd_data)
1203{
1204    CURL *curl;
1205    CURLcode res;
1206    FILE *fp;
1207    FILE *hd;
1208    char *myUrl;
1209    char *phref_tmp=oauth_url_escape(phref);
1210    //wd_DEBUG("get %s metadata\n",phref);
1211    myUrl=(char *)malloc(sizeof(char)*(strlen(phref_tmp)+128));
1212    memset(myUrl,0,strlen(phref_tmp)+128);
1213
1214    sprintf(myUrl,"%s%s","https://api.dropbox.com/1/metadata/dropbox",phref_tmp);
1215    //sprintf(myUrl,"%s","https://sp.yostore.net/member/requestservicegateway/");
1216    free(phref_tmp);
1217    char *header;
1218#ifdef OAuth1
1219    header=makeAuthorize(3);
1220#else
1221    header=makeAuthorize(1);
1222#endif
1223    //curl_global_init(CURL_GLOBAL_ALL);
1224    struct curl_slist *headerlist=NULL;
1225    curl=curl_easy_init();
1226    headerlist=curl_slist_append(headerlist,header);
1227    if(curl){
1228        curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,0L);
1229        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
1230        //curl_easy_setopt(curl,CURLOPT_URL,"https://api.dropbox.com/1/metadata/dropbox/oauth_plaintext_example/main.py?list=true&rev=120e60305d");
1231        //curl_easy_setopt(curl,CURLOPT_URL,"https://api.dropbox.com/1/metadata/dropbox/main");
1232        curl_easy_setopt(curl,CURLOPT_URL,myUrl);
1233        CURL_DEBUG;
1234        curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headerlist);
1235        //curl_easy_setopt(curl,CURLOPT_POSTFIELDS,"");
1236        //curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,0);
1237        //fp=fopen("/tmp/data_5.txt","w");
1238        fp=fopen(Con(TMP_R,data_5.txt),"w");
1239        hd=fopen(Con(TMP_R,data_check_access_token.txt),"w");
1240        curl_easy_setopt(curl,CURLOPT_TIMEOUT,90);
1241        curl_easy_setopt(curl,CURLOPT_WRITEDATA,fp);
1242        curl_easy_setopt(curl,CURLOPT_WRITEHEADER,hd);
1243        res=curl_easy_perform(curl);
1244
1245        //wd_DEBUG("res = %d\n",res);
1246        curl_easy_cleanup(curl);
1247        fclose(fp);
1248        curl_slist_free_all(headerlist);
1249        //curl_global_cleanup();
1250        if(res!=0){
1251            fclose(hd);
1252            free(header);
1253            free(myUrl);
1254            wd_DEBUG("api_metadata %s [%d] failed!\n",phref,res);
1255            return -1;
1256        }
1257        else
1258        {
1259            rewind(hd);
1260            char tmp[256]="\0";
1261            fgets(tmp,sizeof(tmp),hd);
1262            wd_DEBUG("tmp:%s\n",tmp);
1263            if(strstr(tmp,"401")!=NULL)
1264            {
1265                write_log(S_ERROR,"Access token has expired,please re-authenticate!","",0);
1266                exit_loop = 1;
1267                access_token_expired = 1;
1268                fclose(hd);
1269                free(header);
1270                free(myUrl);
1271                return -1;
1272            }
1273            fclose(hd);
1274
1275        }
1276    }
1277    free(myUrl);
1278    free(header);
1279    cJSON *json;
1280    json=cmd_data(Con(TMP_R,data_5.txt));
1281    if(json)
1282    {
1283        cJSON_printf(json,"contents");
1284        cJSON_Delete(json);
1285        return 0;
1286    }
1287    else
1288    {
1289        /*the file contents is error*/
1290        return -1;
1291    }
1292
1293}
1294/*
1295oldname & newname both server path
1296*/
1297int api_move(char *oldname,char *newname,int index,int is_changed_time,char *newname_r)
1298{
1299    CURL *curl;
1300    CURLcode res;
1301    FILE *fp;
1302    FILE *hd;
1303    char *header;
1304    char *data;
1305    hd=fopen(Con(TMP_R,data_hd.txt),"w+");
1306    char *oldname_tmp=oauth_url_escape(oldname);
1307    char *newname_tmp=oauth_url_escape(newname);
1308    data=(char*)malloc(sizeof(char *)*(64+strlen(oldname_tmp)+strlen(newname_tmp)));
1309    memset(data,0,64+strlen(oldname_tmp)+strlen(newname_tmp));
1310
1311    sprintf(data,"root=%s&from_path=%s&to_path=%s","dropbox",oldname_tmp,newname_tmp);
1312    free(oldname_tmp);
1313    free(newname_tmp);
1314    static const char buf[]="Expect:";
1315#ifdef OAuth1
1316    header=makeAuthorize(3);
1317#else
1318    header=makeAuthorize(1);
1319#endif
1320    struct curl_slist *headerlist=NULL;
1321    curl=curl_easy_init();
1322    headerlist=curl_slist_append(headerlist,header);
1323    if(curl){
1324        curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,0L);
1325        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
1326        curl_easy_setopt(curl,CURLOPT_URL,"https://api.dropbox.com/1/fileops/move");
1327        CURL_DEBUG;
1328        curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headerlist);
1329        curl_easy_setopt(curl,CURLOPT_POSTFIELDS,data);
1330        //curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,0);
1331        fp=fopen(Con(TMP_R,data_4.txt),"w");
1332        curl_easy_setopt(curl,CURLOPT_TIMEOUT,90);
1333        curl_easy_setopt(curl,CURLOPT_WRITEDATA,fp);
1334        curl_easy_setopt(curl,CURLOPT_WRITEHEADER,hd);
1335        res=curl_easy_perform(curl);
1336
1337        curl_easy_cleanup(curl);
1338        curl_slist_free_all(headerlist);
1339        fclose(fp);
1340        if(res!=0){
1341
1342            fclose(hd);
1343            free(header);
1344            free(data);
1345            wd_DEBUG("rename %s failed,id [%d]!\n",oldname,res);
1346            return res;
1347        }
1348        else
1349        {
1350            rewind(hd);
1351            char tmp[256]="\0";
1352            fgets(tmp,sizeof(tmp),hd);
1353            wd_DEBUG("tmp:%s\n",tmp);
1354            if(strstr(tmp,"404")!=NULL)
1355            {
1356                if(newname_r == NULL)  //newname_r is local new name
1357                {
1358                    char *localpath=serverpath_to_localpath(newname,index);
1359                    if(test_if_dir(localpath))
1360                    {
1361
1362                        wd_DEBUG("it is folder\n");
1363
1364                        res=dragfolder(localpath,index);
1365                        if(res != 0)
1366                        {
1367
1368                            wd_DEBUG("dragfolder %s failed status = %d\n",localpath,res);
1369                            //write_system_log("error","uploadfile fail");
1370
1371                            fclose(hd);
1372                            free(header);
1373                            free(data);
1374                            free(localpath);
1375                            return res;
1376                        }
1377                    }
1378                    else
1379                    {
1380
1381                        wd_DEBUG("it is file\n");
1382
1383
1384                        res=upload_file(localpath,newname,1,index);
1385                        if(res!=0)
1386                        {
1387
1388                            fclose(hd);
1389                            free(header);
1390                            free(data);
1391                            free(localpath);
1392                            return res;
1393                        }
1394                        else
1395                        {
1396                            cJSON *json = dofile(Con(TMP_R,upload_chunk_commit.txt));
1397                            time_t mtime=cJSON_printf(json,"modified");
1398                            cJSON_Delete(json);
1399
1400                            ChangeFile_modtime(localpath,mtime);
1401                        }
1402                    }
1403                    free(localpath);
1404                }
1405                else
1406                {
1407                    //char *localpath=serverpath_to_localpath(newname_r,index);
1408                    char *localpath = newname_r;
1409                    if(test_if_dir(localpath))
1410                    {
1411
1412                        wd_DEBUG("it is folder\n");
1413
1414                        res=dragfolder_old_dir(localpath,index,newname);
1415                        if(res != 0)
1416                        {
1417
1418                            wd_DEBUG("dragfolder %s failed status = %d\n",localpath,res);
1419                            //write_system_log("error","uploadfile fail");
1420
1421                            fclose(hd);
1422                            free(header);
1423                            free(data);
1424                            //free(localpath);
1425                            return res;
1426                        }
1427                    }
1428                    else
1429                    {
1430                        wd_DEBUG("it is file\n");
1431
1432                        res=upload_file(localpath,newname,1,index);
1433                        if(res!=0)
1434                        {
1435                            fclose(hd);
1436                            free(header);
1437                            free(data);
1438                            //free(localpath);
1439                            return res;
1440                        }
1441                        else
1442                        {
1443                            cJSON *json = dofile(Con(TMP_R,upload_chunk_commit.txt));
1444                            time_t mtime=cJSON_printf(json,"modified");
1445                            cJSON_Delete(json);
1446
1447                            ChangeFile_modtime(localpath,mtime);
1448                        }
1449                    }
1450                    //free(localpath);
1451                }
1452
1453            }
1454            else if(strstr(tmp,"200")!=NULL)
1455            {
1456                if(is_changed_time)
1457                {
1458                    char *localpath=serverpath_to_localpath(newname,index);
1459                    cJSON *json = dofile(Con(TMP_R,data_4.txt));
1460                    time_t mtime=cJSON_printf(json,"modified");
1461                    cJSON_Delete(json);
1462                    if(test_if_dir(localpath))
1463                    {
1464                        dragfolder_rename(localpath,index,mtime);
1465                    }
1466                    else
1467                    {
1468                        ChangeFile_modtime(localpath,mtime);
1469                    }
1470                    free(localpath);
1471                }
1472            }
1473            else if(strstr(tmp,"403")!=NULL)
1474            {
1475                //cJSON *json = dofile(Con(TMP_R,data_4.txt));
1476                char *server_conflcit_name=get_server_exist(newname,index);
1477                printf("server_conflict_name=%s\n",server_conflcit_name);
1478                if(server_conflcit_name)
1479                {
1480                    deal_big_low_conflcit(server_conflcit_name,oldname,newname,newname_r,index);
1481                    free(server_conflcit_name);
1482                }
1483                else
1484                {
1485                    fclose(hd);
1486                    free(header);
1487                    free(data);
1488                    return -1;
1489                }
1490                //cJSON_Delete(json);
1491            }
1492        }
1493    }
1494
1495    fclose(hd);
1496    wd_DEBUG("rename ok\n");
1497    free(header);
1498    free(data);
1499    return 0;
1500}
1501/*
1502fullname=>local
1503filename=>server
1504*/
1505int api_download(char *fullname,char *filename,int index)
1506{
1507    if(access(fullname,F_OK) == 0)
1508    {
1509
1510        wd_DEBUG("Local has %s\n",fullname);
1511
1512        unlink(fullname);
1513        add_action_item("remove",fullname,g_pSyncList[index]->server_action_list);
1514    }
1515
1516    char *temp_suffix = ".asus.td";
1517    char *Localfilename_tmp=(char *)malloc(sizeof(char)*(strlen(fullname)+strlen(temp_suffix)+2));
1518    memset(Localfilename_tmp,0,strlen(fullname)+strlen(temp_suffix)+2);
1519    sprintf(Localfilename_tmp,"%s%s",fullname,temp_suffix);
1520    CURL *curl;
1521    CURLcode res;
1522    FILE *fp;
1523    FILE *hd;
1524    hd=fopen(Con(TMP_R,api_download_header.txt),"w+");
1525    //FILE *hd;
1526    char *myUrl;
1527    char *filename_tmp=oauth_url_escape(filename);
1528    myUrl=(char *)malloc(sizeof(char)*(strlen(filename_tmp)+128));
1529    memset(myUrl,0,strlen(filename_tmp)+128);
1530
1531    sprintf(myUrl,"%s%s","https://api-content.dropbox.com/1/files/dropbox",filename_tmp);
1532    free(filename_tmp);
1533    char *header;
1534    static const char buf[]="Expect:";
1535#ifdef OAuth1
1536    header=makeAuthorize(3);
1537#else
1538    header=makeAuthorize(1);
1539#endif
1540    struct curl_slist *headerlist=NULL;
1541    curl=curl_easy_init();
1542    headerlist=curl_slist_append(headerlist,header);
1543    write_log(S_DOWNLOAD,"",fullname,index);
1544    if(curl){
1545        curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,0L);
1546        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
1547        curl_easy_setopt(curl,CURLOPT_URL,myUrl);
1548        CURL_DEBUG;
1549        curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headerlist);
1550        //curl_easy_setopt(curl,CURLOPT_POSTFIELDS,"");
1551        //curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,0);
1552        //curl_easy_setopt(curl,CURLOPT_TIMEOUT,15);
1553        curl_easy_setopt(curl,CURLOPT_NOPROGRESS,0L);
1554        curl_easy_setopt(curl,CURLOPT_PROGRESSFUNCTION,my_progress_func);
1555        curl_easy_setopt(curl,CURLOPT_PROGRESSDATA,Clientfp);
1556        curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,my_write_func);
1557
1558        curl_easy_setopt(curl,CURLOPT_LOW_SPEED_LIMIT,1);
1559        curl_easy_setopt(curl,CURLOPT_LOW_SPEED_TIME,30);
1560
1561
1562        fp=fopen(Localfilename_tmp,"w");
1563        //fp=fopen("/tmp/dropbox_download.txt","w+");
1564        curl_easy_setopt(curl,CURLOPT_WRITEDATA,fp);
1565        curl_easy_setopt(curl,CURLOPT_WRITEHEADER,hd);
1566        res=curl_easy_perform(curl);
1567
1568        curl_easy_cleanup(curl);
1569        fclose(fp);
1570
1571        curl_slist_free_all(headerlist);
1572        if(res!=0){
1573            fclose(hd);
1574
1575            free(header);
1576            free(myUrl);
1577            wd_DEBUG("download %s failed,id:[%d]!\n",filename,res);
1578            unlink(Localfilename_tmp);
1579            free(Localfilename_tmp);
1580            char *error_message=write_error_message("download %s failed",filename);
1581            write_log(S_ERROR,error_message,"",index);
1582            free(error_message);
1583            if(res == 7)
1584            {
1585                //write_log(S_ERROR,"Could not connect to server!","",index);
1586                return COULD_NOT_CONNECNT_TO_SERVER;
1587            }
1588            else
1589            {
1590                return res;
1591            }
1592        }
1593        else
1594        {
1595            rewind(hd);
1596            char tmp_name[256]="\0";
1597            fgets(tmp_name,sizeof(tmp_name),hd);
1598            wd_DEBUG("tmp:%s\n",tmp_name);
1599            fclose(hd);
1600            if(strstr(tmp_name,"404")!=NULL)
1601            {
1602                unlink(Localfilename_tmp);
1603            }
1604            else
1605            {
1606                if(rename(Localfilename_tmp,fullname)!=0)
1607                {
1608                    unlink(Localfilename_tmp);
1609                    return -1;
1610                }
1611            }
1612        }
1613    }
1614    free(Localfilename_tmp);
1615    free(header);
1616    free(myUrl);
1617    if(finished_initial)
1618        write_log(S_SYNC,"","",index);
1619    else
1620        write_log(S_INITIAL,"","",index);
1621    return 0;
1622}
1623
1624//int get_file_size(char *filename)
1625//{
1626//    int file_len = 0;
1627//    int fd = 0;
1628
1629//    fd = open(filename, O_RDONLY);
1630//    if(fd < 0)
1631//    {
1632//        perror("open");
1633//        /*
1634//         fix below bug:
1635//            1.create file a;
1636//            2.rename a-->b;
1637//            final open() 'a' failed ,will exit();
1638//        */
1639//        //exit(-1);
1640//        return -1;
1641//    }
1642
1643//    file_len = lseek(fd, 0, SEEK_END);
1644//    //wd_DEBUG("file_len is %d\n",file_len);
1645//    if(file_len < 0)
1646//    {
1647//        perror("lseek");
1648//        exit(-1);
1649//    }
1650//    close(fd);
1651//    return file_len;
1652//}
1653
1654long long int
1655        get_file_size(const char *file)
1656{
1657    struct stat file_info;
1658
1659    if( !(file || *file) )
1660        return 0;
1661
1662    if( file[0] == '-' )
1663        return 0;
1664
1665    if( stat(file, &file_info) == -1 )
1666        return 0;
1667    else
1668        return(file_info.st_size);
1669}
1670
1671int api_upload_put_test(char *filename,char *serverpath,int flag)
1672{
1673    CURL *curl;
1674    CURLcode res;
1675    FILE *fp;
1676    FILE *fp_1;
1677    FILE *fp_hd;
1678
1679    struct stat filestat;
1680    unsigned long int filesize;
1681
1682    if( stat(filename,&filestat) == -1)
1683    {
1684        //perror("stat:");
1685        wd_DEBUG("servr sapce full stat error:%s file not exist\n",filename);
1686        return -1;
1687    }
1688
1689    filesize = filestat.st_size;
1690
1691    filesize = filesize / 1024 / 1024;
1692
1693    fp_1=fopen(filename,"rb");
1694    long long int size=get_file_size(filename);
1695
1696    char *header;
1697    static const char buf[]="Content-Type: test/plain";
1698#ifdef OAuth1
1699    header=makeAuthorize(4);
1700#else
1701    header=makeAuthorize(2);
1702#endif
1703    struct curl_slist *headerlist=NULL;
1704    char header_l[]="Content-Length: ";
1705    char header1_l[128]="\0";
1706
1707    sprintf(header1_l,"%s%d\n",header_l,size);
1708
1709    header1_l[strlen(header1_l)-1]='\0';
1710    curl=curl_easy_init();
1711
1712    char myUrl[1024]="\0";
1713    wd_DEBUG("serverpath = %s\n",serverpath);
1714    if(flag)
1715        sprintf(myUrl,"%s%s?%s&%s","https://api-content.dropbox.com/1/files_put/dropbox",serverpath,header,"overwrite=true");
1716    else
1717        sprintf(myUrl,"%s%s?%s&%s","https://api-content.dropbox.com/1/files_put/dropbox",serverpath,header,"overwrite=false");
1718
1719    if(curl){
1720        curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,0L);
1721        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
1722        curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
1723        curl_easy_setopt(curl,CURLOPT_URL,myUrl);
1724        CURL_DEBUG;
1725        curl_easy_setopt(curl,CURLOPT_READDATA,fp_1);
1726        curl_easy_setopt(curl,CURLOPT_UPLOAD,1L);
1727
1728        curl_easy_setopt(curl, CURLOPT_INFILESIZE,filestat.st_size);
1729
1730
1731        curl_easy_setopt(curl,CURLOPT_NOPROGRESS,0L);
1732        curl_easy_setopt(curl,CURLOPT_PROGRESSFUNCTION,my_progress_func);
1733        curl_easy_setopt(curl,CURLOPT_PROGRESSDATA,Clientfp);
1734
1735        curl_easy_setopt(curl,CURLOPT_LOW_SPEED_LIMIT,1);
1736        curl_easy_setopt(curl,CURLOPT_LOW_SPEED_TIME,30);
1737
1738        fp=fopen(Con(TMP_R,upload_chunk_commit.txt),"w");
1739        curl_easy_setopt(curl,CURLOPT_WRITEDATA,fp);
1740        fp_hd=fopen(Con(TMP_R,upload_header.txt),"w+");
1741        curl_easy_setopt(curl,CURLOPT_WRITEHEADER,fp_hd);
1742
1743        //start_time = time(NULL);
1744        res=curl_easy_perform(curl);
1745
1746        curl_easy_cleanup(curl);
1747        if(res==0)
1748        {
1749            rewind(fp_hd);
1750            char tmp_[256];
1751            while(!feof(fp_hd))
1752            {
1753                fgets(tmp_,sizeof(tmp_),fp_hd);
1754                printf("tmp_ : %s\n",tmp_);
1755                if(strstr(tmp_,"507 Quota Error") != NULL)
1756                    printf("server space not enough\n");
1757            }
1758        }
1759        fclose(fp_hd);
1760        fclose(fp);
1761        fclose(fp_1);
1762    }
1763    free(header);
1764    return 0;
1765}
1766int api_upload_put(char *filename,char *serverpath,int flag,int index)
1767{
1768    CURL *curl;
1769    CURLcode res;
1770    FILE *fp;
1771    FILE *fp_1;
1772    FILE *fp_hd;
1773    struct stat filestat;
1774    unsigned long int filesize;
1775
1776    if( stat(filename,&filestat) == -1)
1777    {
1778        //perror("stat:");
1779        wd_DEBUG("servr sapce full stat error:%s file not exist\n",filename);
1780        return -1;
1781    }
1782
1783    filesize = filestat.st_size;
1784
1785    filesize = filesize / 1024 / 1024;
1786
1787    fp_1=fopen(filename,"rb");
1788    if(fp_1 == NULL)
1789    {
1790        wd_DEBUG("Local has no %s\n",filename);
1791        return LOCAL_FILE_LOST;
1792    }
1793
1794    long long int size=get_file_size(filename);
1795    //printf("size=%d,filesize=%lu\n",size,filesize);
1796    char *header;
1797    static const char buf[]="Content-Type: test/plain";
1798#ifdef OAuth1
1799    header=makeAuthorize(4);
1800#else
1801    header=makeAuthorize(2);
1802#endif
1803    struct curl_slist *headerlist=NULL;
1804    char header_l[]="Content-Length: ";
1805    char header1_l[128]="\0";
1806    //sprintf(header1_l,"%s%lu\n",header_l,filesize);
1807    sprintf(header1_l,"%s%d\n",header_l,size);
1808    //printf("%d\n",strlen(header1_l));
1809    //printf("%c\n",header1_l[strlen(header1_l)-2]);
1810    header1_l[strlen(header1_l)-1]='\0';
1811    curl=curl_easy_init();
1812    //headerlist=curl_slist_append(headerlist,header1_l);
1813    char myUrl[1024]="\0";
1814    wd_DEBUG("serverpath = %s\n",serverpath);
1815    if(flag)
1816        sprintf(myUrl,"%s%s?%s&%s","https://api-content.dropbox.com/1/files_put/dropbox",serverpath,header,"overwrite=true");
1817    else
1818        sprintf(myUrl,"%s%s?%s&%s","https://api-content.dropbox.com/1/files_put/dropbox",serverpath,header,"overwrite=false");
1819    //headerlist=curl_slist_append(headerlist,header);
1820    //headerlist=curl_slist_append(headerlist,buf);
1821    //headerlist=curl_slist_append(headerlist,buf);
1822
1823    if(LOCAL_FILE.path != NULL)
1824        free(LOCAL_FILE.path);
1825    LOCAL_FILE.path = (char*)malloc(sizeof(char)*(strlen(filename) + 1));
1826    sprintf(LOCAL_FILE.path,"%s",filename);
1827    LOCAL_FILE.index = index;
1828
1829    fp=fopen(Con(TMP_R,upload_chunk_commit.txt),"w");
1830    fp_hd=fopen(Con(TMP_R,upload_header.txt),"w+");
1831
1832    if(curl){
1833        curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,0L);
1834        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
1835        curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
1836        curl_easy_setopt(curl,CURLOPT_URL,myUrl);
1837        CURL_DEBUG;
1838        //curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headerlist);
1839        curl_easy_setopt(curl,CURLOPT_READDATA,fp_1);
1840        curl_easy_setopt(curl,CURLOPT_UPLOAD,1L);
1841        //curl_easy_setopt(curl,CURLOPT_PUT,1L);
1842        //curl_easy_setopt(curl,CURLOPT_TIMEOUT,15);
1843        curl_easy_setopt(curl,CURLOPT_CONNECTTIMEOUT,10);//upload time_out
1844        //curl_easy_setopt(curl,CURLOPT_INFILESIZE_LARGE,(curl_off_t)size);//put Content-Length
1845        curl_easy_setopt(curl, CURLOPT_INFILESIZE,filestat.st_size);
1846        //curl_easy_setopt(curl,CURLOPT_INFILESIZE_LARGE,size);
1847        //curl_easy_setopt(curl,CURLOPT_POSTFIELDS,data);
1848        //curl_easy_setopt(curl,CURLOPT_POSTFIELDSIZE,size);
1849        //curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,0);
1850
1851        curl_easy_setopt(curl,CURLOPT_NOPROGRESS,0L);
1852        curl_easy_setopt(curl,CURLOPT_PROGRESSFUNCTION,my_progress_func);
1853        curl_easy_setopt(curl,CURLOPT_PROGRESSDATA,Clientfp);
1854        curl_easy_setopt(curl,CURLOPT_READFUNCTION, my_read_func);
1855
1856
1857        curl_easy_setopt(curl,CURLOPT_LOW_SPEED_LIMIT,1);
1858        curl_easy_setopt(curl,CURLOPT_LOW_SPEED_TIME,30);
1859
1860
1861        curl_easy_setopt(curl,CURLOPT_WRITEDATA,fp);
1862
1863        curl_easy_setopt(curl,CURLOPT_WRITEHEADER,fp_hd);
1864        //start_time = time(NULL);
1865        res=curl_easy_perform(curl);
1866
1867        curl_easy_cleanup(curl);
1868        fclose(fp);
1869        fclose(fp_1);
1870        if(res!=0){
1871            fclose(fp_hd);
1872            free(header);
1873            wd_DEBUG("upload %s failed,id is [%d]!\n",filename,res);
1874            char *error_message=write_error_message("upload %s failed",filename);
1875            write_log(S_ERROR,error_message,"",index);
1876            free(error_message);
1877            if( res == 7 )
1878            {
1879                /*
1880                    action_item *item;
1881                    item = get_action_item("upload",filename,g_pSyncList[index]->unfinished_list,index);
1882                    if(item == NULL)
1883                    {
1884                        add_action_item("upload",filename,g_pSyncList[index]->unfinished_list);
1885                    }
1886                    */
1887                //write_log(S_ERROR,"Could not connect to server!","",index);
1888                return COULD_NOT_CONNECNT_TO_SERVER;
1889            }
1890            else if( res == 28)
1891            {
1892                /*
1893                    action_item *item;
1894                    item = get_action_item("upload",filename,g_pSyncList[index]->unfinished_list,index);
1895                    if(item == NULL)
1896                    {
1897                        add_action_item("upload",filename,g_pSyncList[index]->unfinished_list);
1898                    }
1899                    */
1900                //write_log(S_ERROR,"Could not connect to server!","",index);
1901                return CONNECNTION_TIMED_OUT;
1902            }
1903            else if( res == 35 )
1904            {
1905                /*
1906                    action_item *item;
1907                    item = get_action_item("upload",filename,g_pSyncList[index]->unfinished_list,index);
1908                    if(item == NULL)
1909                    {
1910                        add_action_item("upload",filename,g_pSyncList[index]->unfinished_list);
1911                    }
1912                    */
1913                return INVALID_ARGUMENT;
1914            }
1915            else
1916                return res;
1917        }
1918        else
1919        {
1920            free(header);
1921            rewind(fp_hd);
1922            char tmp_[256];
1923            while(!feof(fp_hd))
1924            {
1925                fgets(tmp_,sizeof(tmp_),fp_hd);
1926                if(strstr(tmp_,"507 Quota Error") != NULL)
1927                {
1928                    write_log(S_ERROR,"server space is not enough!","",index);
1929                    action_item *item;
1930                    item = get_action_item("upload",filename,g_pSyncList[index]->up_space_not_enough_list,index);
1931                    if(item == NULL)
1932                    {
1933                        add_action_item("upload",filename,g_pSyncList[index]->up_space_not_enough_list);
1934                    }
1935                    fclose(fp_hd);
1936                    return SERVER_SPACE_NOT_ENOUGH;
1937                }
1938            }
1939            fclose(fp_hd);
1940        }
1941    }
1942    return 0;
1943}
1944int api_upload_post()
1945{
1946    CURL *curl;
1947    CURLcode res;
1948    FILE *fp;
1949    FILE *fp_1;
1950
1951    struct stat filestat;
1952    unsigned long int filesize;
1953
1954    if( stat("cookie_login.txt",&filestat) == -1)
1955    {
1956        //perror("stat:");
1957        wd_DEBUG("servr sapce full stat error:%s file not exist\n","cookie_login.txt");
1958        return -1;
1959    }
1960
1961    filesize = filestat.st_size;
1962
1963    filesize = filesize / 1024 / 1024;
1964
1965    fp_1=fopen("cookie_login.txt","rb+");
1966    long long int size=get_file_size("cookie_login.txt");
1967    wd_DEBUG("size=%d,filesize=%lu\n",size,filesize);
1968    char *header;
1969    static const char buf[]="Content-Type: test/plain";
1970#ifdef OAuth1
1971    header=makeAuthorize(4);
1972#else
1973    header=makeAuthorize(2);
1974#endif
1975    struct curl_slist *headerlist=NULL;
1976    char header_l[]="Content-Length: ";
1977    char header1_l[128]="\0";
1978    //sprintf(header1_l,"%s%lu\n",header_l,filesize);
1979    sprintf(header1_l,"%s%d\n",header_l,size);
1980    wd_DEBUG("%d\n",strlen(header1_l));
1981    //wd_DEBUG("%c\n",header1_l[strlen(header1_l)-2]);
1982    header1_l[strlen(header1_l)-1]='\0';
1983    curl=curl_easy_init();
1984    //headerlist=curl_slist_append(headerlist,header1_l);
1985    char myUrl[256]="\0";
1986    sprintf(myUrl,"%s?%s","https://api-content.dropbox.com/1/files/dropbox/oauth_plaintext_example",header);
1987    //headerlist=curl_slist_append(headerlist,buf);
1988
1989    //headerlist=curl_slist_append(headerlist,buf);
1990    if(curl){
1991        curl_easy_setopt(curl,CURLOPT_URL,myUrl);
1992        //curl_easy_setopt(curl,CURLOPT_VERBOSE,1);
1993        //curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headerlist);
1994        //curl_easy_setopt(curl,CURLOPT_READDATA,fp_1);
1995        //curl_easy_setopt(curl,CURLOPT_UPLOAD,1L);//put
1996        curl_easy_setopt(curl,CURLOPT_POST,1L);
1997        //curl_easy_setopt(curl,CURLOPT_TIMEOUT,15);
1998        //curl_easy_setopt(curl,CURLOPT_INFILESIZE_LARGE,(curl_off_t)size);//put Content-Length
1999        curl_easy_setopt(curl,CURLOPT_POSTFIELDS,fp_1);
2000        curl_easy_setopt(curl,CURLOPT_POSTFIELDSIZE_LARGE,(curl_off_t)size);
2001        //curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,0);
2002        fp=fopen("upload.txt","w");
2003        curl_easy_setopt(curl,CURLOPT_WRITEDATA,fp);
2004
2005        res=curl_easy_perform(curl);
2006
2007        curl_easy_cleanup(curl);
2008        fclose(fp);
2009        fclose(fp_1);
2010        if(res!=0){
2011            wd_DEBUG("delete [%d] failed!\n",res);
2012            return -1;
2013        }
2014    }
2015    free(header);
2016}
2017
2018int my_progress_func(char *clientfp,double t,double d,double ultotal,double ulnow){
2019    //printf("%g/%g(%g%%)\n",d,t,d*100.0/t);
2020#if 1
2021    int sec;
2022    double  elapsed = 0;
2023    elapsed = time(NULL) - start_time;
2024    sec = (int)elapsed;
2025    if( sec > 0 )
2026    {
2027        //double progress = ulnow*100.0/ultoal;
2028        if(sec % 5 == 0)
2029            wd_DEBUG("@%s %g / %g (%g %%)\n", clientfp, ulnow, ultotal, ulnow*100.0/ultotal);
2030    }
2031#endif
2032
2033#if 1
2034    if(t > 1 && d > 10) // download
2035        wd_DEBUG("@@%s %10.0f / %10.0f (%g %%)\n", clientfp, d, t, d*100.0/t);
2036    else//upload
2037    {
2038        if(exit_loop==1){
2039            return -1;
2040        }
2041        wd_DEBUG("@@@%s %10.0f / %10.0f (%g %%)\n", clientfp, ulnow, ultotal, ulnow*100.0/ultotal);
2042    }
2043#endif
2044    return 0;
2045}
2046
2047size_t my_write_func(void *ptr, size_t size, size_t nmemb, FILE *stream)
2048
2049{
2050    if(exit_loop==1){
2051        return -1;
2052    }
2053    wd_DEBUG("download!\n");
2054    int len ;
2055    len = fwrite(ptr, size, nmemb, stream);
2056    //printf("write len is %d\n",len);
2057    return len;
2058
2059}
2060
2061size_t my_read_func(void *ptr, size_t size, size_t nmemb, FILE *stream)
2062{
2063    if(exit_loop==1){
2064        return -1;
2065    }
2066
2067    struct stat info;
2068    char *ret = NULL;
2069    int status = stat(LOCAL_FILE.path,&info);
2070    if(status == -1)
2071    {
2072        usleep(1000*100);
2073        ret = search_newpath(LOCAL_FILE.path,LOCAL_FILE.index);
2074        if(ret == NULL)
2075        {
2076            return -1;
2077        }
2078        else
2079        {
2080            if(LOCAL_FILE.path != NULL)
2081                free(LOCAL_FILE.path);
2082            LOCAL_FILE.path = (char *)malloc(sizeof(char)*(strlen(ret) + 1));
2083            sprintf(LOCAL_FILE.path,"%s",ret);
2084            free(ret);
2085        }
2086    }
2087
2088    int len;
2089    len = fread(ptr, size, nmemb, stream);
2090    //DEBUG("\rread len:%d   path:%s",len,LOCAL_FILE.path);
2091    return len;
2092}
2093
2094int api_upload_chunk_put(char *buffer,char *upload_id,unsigned long offset,unsigned long chunk,int index,char *filepath)
2095{
2096    wd_DEBUG("upload_id: %s\n",upload_id);
2097    FILE *fp;
2098    FILE *fp_2;
2099    fp_2=fopen(Con(TMP_R,swap),"w+");
2100    char *header;
2101#ifdef OAuth1
2102    header=makeAuthorize(4);
2103#else
2104    header=makeAuthorize(2);
2105#endif
2106
2107    fwrite(buffer,4000000/10,10,fp_2);
2108    rewind(fp_2);
2109    CURL *curl;
2110    CURLcode res;
2111    struct curl_slist *headerlist=NULL;
2112
2113    curl=curl_easy_init();
2114    //char myUrl[2046]="\0";
2115    char *myUrl=(char *)malloc(2046);
2116    memset(myUrl,0,2046);
2117    //char range[256] = {0};
2118    if( upload_id ==NULL )
2119        sprintf(myUrl,"%s?%s","https://api-content.dropbox.com/1/chunked_upload",header);
2120    else
2121    {
2122        sprintf(myUrl,"%s?upload_id=%s&offset=%lu&%s","https://api-content.dropbox.com/1/chunked_upload",upload_id,chunk,header);
2123    }
2124    wd_DEBUG("myUrl: %s\n",myUrl);
2125    //headerlist=curl_slist_append(headerlist,header);
2126
2127    if(LOCAL_FILE.path != NULL)
2128        free(LOCAL_FILE.path);
2129    LOCAL_FILE.path = (char*)malloc(sizeof(char)*(strlen(filepath) + 1));
2130    sprintf(LOCAL_FILE.path,"%s",filepath);
2131    LOCAL_FILE.index = index;
2132
2133    if(curl){
2134        curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,0L);
2135        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
2136        curl_easy_setopt(curl,CURLOPT_URL,myUrl);
2137        CURL_DEBUG;
2138        //curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headerlist);
2139        curl_easy_setopt(curl,CURLOPT_READDATA,fp_2);
2140        curl_easy_setopt(curl,CURLOPT_UPLOAD,1L);
2141        curl_easy_setopt(curl,CURLOPT_PUT,1L);
2142        //curl_easy_setopt(curl,CURLOPT_TIMEOUT,10);//download time_out
2143        curl_easy_setopt(curl,CURLOPT_CONNECTTIMEOUT,10);//upload time_out
2144        curl_easy_setopt(curl,CURLOPT_INFILESIZE_LARGE,(curl_off_t)offset);//put Content-Length
2145        //if( offset > 0)
2146        //sprintf(range,"0-%lu",offset);
2147        //curl_easy_setopt(curl, CURLOPT_RANGE,range);
2148        //curl_easy_setopt(curl, CURLOPT_RESUME_FROM_LARGE,(curl_off_t)0);
2149        fp=fopen(Con(TMP_R,upload_chunk_1.txt),"w+");
2150        curl_easy_setopt(curl,CURLOPT_NOPROGRESS,0L);
2151        curl_easy_setopt(curl,CURLOPT_PROGRESSFUNCTION,my_progress_func);
2152        curl_easy_setopt(curl,CURLOPT_PROGRESSDATA,Clientfp);
2153
2154        curl_easy_setopt(curl,CURLOPT_READFUNCTION, my_read_func);
2155        curl_easy_setopt(curl,CURLOPT_WRITEDATA,fp);
2156
2157        curl_easy_setopt(curl,CURLOPT_LOW_SPEED_LIMIT,1);
2158        curl_easy_setopt(curl,CURLOPT_LOW_SPEED_TIME,30);
2159        //curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,my_write_func);
2160
2161
2162        res=curl_easy_perform(curl);
2163        curl_easy_cleanup(curl);
2164        fclose(fp);
2165        fclose(fp_2);
2166        if(res!=CURLE_OK){
2167            free(header);
2168            free(myUrl);
2169            wd_DEBUG("upload fail,id is %d!\n",res);
2170            char *error_message=write_error_message("upload %s failed",filepath);
2171            write_log(S_ERROR,error_message,"",index);
2172            free(error_message);
2173            if( res == 7 )
2174            {
2175                /*
2176                    action_item *item;
2177                    item = get_action_item("upload",filepath,g_pSyncList[index]->unfinished_list,index);
2178                    if(item == NULL)
2179                    {
2180                        add_action_item("upload",filepath,g_pSyncList[index]->unfinished_list);
2181                    }
2182                    */
2183                return COULD_NOT_CONNECNT_TO_SERVER;
2184            }
2185            else if( res == 28)
2186            {
2187                /*
2188                    action_item *item;
2189                    item = get_action_item("upload",filepath,g_pSyncList[index]->unfinished_list,index);
2190                    if(item == NULL)
2191                    {
2192                        add_action_item("upload",filepath,g_pSyncList[index]->unfinished_list);
2193                    }
2194                    */
2195                return CONNECNTION_TIMED_OUT;
2196            }
2197            else if( res == 35 )
2198            {
2199                /*
2200                    action_item *item;
2201                    item = get_action_item("upload",filepath,g_pSyncList[index]->unfinished_list,index);
2202                    if(item == NULL)
2203                    {
2204                        add_action_item("upload",filepath,g_pSyncList[index]->unfinished_list);
2205                    }*/
2206                return INVALID_ARGUMENT;
2207            }
2208            else
2209                return res;
2210
2211        }
2212    }
2213    free(header);
2214    free(myUrl);
2215    return 0;
2216}
2217char *get_upload_id()
2218{
2219    FILE *fp;
2220    fp=fopen(Con(TMP_R,upload_chunk_1.txt),"r");
2221    if(fp==NULL)
2222    {
2223        wd_DEBUG("open %s fialed\n","upload_chunk_1.txt");
2224        return NULL;
2225    }
2226    char buff[1024]="\0";
2227    char *p=NULL,*m=NULL;
2228    char *upload_id;
2229    upload_id=(char *)malloc(sizeof(char *)*512);
2230    memset(upload_id,0,512);
2231    fgets(buff,sizeof(buff),fp);
2232    p=strstr(buff,"upload_id");
2233    p=p+strlen("upload_id")+4;
2234    m=strchr(p,'"');
2235    snprintf(upload_id,strlen(p)-strlen(m)+1,"%s",p);
2236    //strncpy(upload_id,p,strlen(p)-strlen(m));
2237    wd_DEBUG("upload_id : %s,%d\n",upload_id,strlen(upload_id));
2238    //wd_DEBUG("upload_id : %c\n",upload_id[21]);
2239    if(upload_id[strlen(upload_id)] == '\0')
2240    {
2241        //wd_DEBUG("111\n");
2242        upload_id[strlen(upload_id)] = '\0';
2243    }
2244    fclose(fp);
2245    //printf("upload_id : %s,%d\n",upload_id,strlen(upload_id));
2246    //printf("upload_id : %c\n",upload_id[strlen(upload_id)]);
2247    return upload_id;
2248}
2249int api_upload_chunk_commit(char *upload_id,char *filename,int flag,int index)
2250{
2251    FILE *fp;
2252    FILE *fp_hd;
2253    char *header;
2254#ifdef OAuth1
2255    header=makeAuthorize(4);
2256#else
2257    header=makeAuthorize(2);
2258#endif
2259    CURL *curl;
2260    CURLcode res;
2261    struct curl_slist *headerlist=NULL;
2262
2263    curl=curl_easy_init();
2264    char *data=malloc(256);
2265    memset(data,0,256);
2266    if(flag)
2267        sprintf(data,"upload_id=%s",upload_id);
2268    else
2269        sprintf(data,"overwrite=false&upload_id=%s",upload_id);
2270    char myUrl[2046]="\0";
2271    sprintf(myUrl,"%s%s?upload_id=%s&%s","https://api-content.dropbox.com/1/commit_chunked_upload/dropbox",filename,upload_id,header);
2272    //headerlist=curl_slist_append(headerlist,header);
2273
2274    if(curl){
2275        curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,0L);
2276        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
2277        curl_easy_setopt(curl,CURLOPT_URL,myUrl);
2278        CURL_DEBUG;
2279        //curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headerlist);
2280        //curl_easy_setopt(curl,CURLOPT_READDATA,fp_2);
2281        //curl_easy_setopt(curl,CURLOPT_UPLOAD,1L);
2282        curl_easy_setopt(curl,CURLOPT_POST,1L);
2283        curl_easy_setopt(curl,CURLOPT_POSTFIELDS,data);
2284        //curl_easy_setopt(curl,CURLOPT_TIMEOUT,15);
2285        //curl_easy_setopt(curl,CURLOPT_INFILESIZE_LARGE,(curl_off_t)offset);//put Content-Length
2286        //if( offset > 0)
2287        //sprintf(range,"0-%lu",offset);
2288        //curl_easy_setopt(curl, CURLOPT_RANGE,range);
2289        //curl_easy_setopt(curl, CURLOPT_RESUME_FROM_LARGE,(curl_off_t)0);
2290        fp=fopen(Con(TMP_R,upload_chunk_commit.txt),"w");
2291        //curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,my_write_func);
2292        curl_easy_setopt(curl,CURLOPT_TIMEOUT,90);
2293        curl_easy_setopt(curl,CURLOPT_WRITEDATA,fp);
2294
2295        fp_hd=fopen(Con(TMP_R,upload_header.txt),"w+");
2296        curl_easy_setopt(curl,CURLOPT_WRITEHEADER,fp_hd);
2297
2298        res=curl_easy_perform(curl);
2299        curl_easy_cleanup(curl);
2300        fclose(fp);
2301        if(res!=0){
2302            fclose(fp_hd);
2303            free(header);
2304            free(data);
2305            wd_DEBUG("upload %s failed,id is [%d]!\n",filename,res);
2306            char *error_message=write_error_message("upload %s failed",filename);
2307            write_log(S_ERROR,error_message,"",index);
2308            free(error_message);
2309            if( res == 7 )
2310            {
2311                /*
2312                    action_item *item;
2313                    item = get_action_item("upload",filename,g_pSyncList[index]->unfinished_list,index);
2314                    if(item == NULL)
2315                    {
2316                        add_action_item("upload",filename,g_pSyncList[index]->unfinished_list);
2317                    }*/
2318
2319                return COULD_NOT_CONNECNT_TO_SERVER;
2320            }
2321            else if( res == 28)
2322            {
2323                /*
2324                    action_item *item;
2325                    item = get_action_item("upload",filename,g_pSyncList[index]->unfinished_list,index);
2326                    if(item == NULL)
2327                    {
2328                        add_action_item("upload",filename,g_pSyncList[index]->unfinished_list);
2329                    }
2330                    */
2331
2332                return CONNECNTION_TIMED_OUT;
2333            }
2334            else if( res == 35 )
2335            {
2336                /*
2337                    action_item *item;
2338                    item = get_action_item("upload",filename,g_pSyncList[index]->unfinished_list,index);
2339                    if(item == NULL)
2340                    {
2341                        add_action_item("upload",filename,g_pSyncList[index]->unfinished_list);
2342                    }
2343                    */
2344                return INVALID_ARGUMENT;
2345            }
2346            else
2347                return res;
2348        }
2349        else
2350        {
2351            free(header);
2352            free(data);
2353            rewind(fp_hd);
2354            char tmp_[256];
2355            while(!feof(fp_hd))
2356            {
2357                fgets(tmp_,sizeof(tmp_),fp_hd);
2358                if(strstr(tmp_,"507 Quota Error") != NULL)
2359                {
2360                    write_log(S_ERROR,"server space is not enough!","",index);
2361                    action_item *item;
2362                    item = get_action_item("upload",filename,g_pSyncList[index]->up_space_not_enough_list,index);
2363                    if(item == NULL)
2364                    {
2365                        add_action_item("upload",filename,g_pSyncList[index]->up_space_not_enough_list);
2366                    }
2367                    fclose(fp_hd);
2368                    return SERVER_SPACE_NOT_ENOUGH;
2369                }
2370            }
2371            fclose(fp_hd);
2372        }
2373    }
2374    return 0;
2375}
2376/*
2377 1=>enough
2378 0=>not enough
2379 status=>get accout_info fail
2380*/
2381int is_server_enough(char *filename)
2382{
2383    long long int size_lo=get_file_size(filename);
2384    if(size_lo == -1)
2385        return -1;
2386    int status;
2387    status=api_accout_info();
2388    long long int size_server;
2389    if(status == 0)
2390    {
2391        cJSON *json = dofile(Con(TMP_R,data_3.txt));
2392        cJSON_printf(json,"quota_info");
2393        cJSON_Delete(json);
2394        //printf("%lld %lld %lld\n",server_quota,server_shared,server_normal);
2395        size_server=server_quota-server_shared;
2396        size_server-=server_normal;
2397        //size_server=(server_quota-server_shared-server_normal);
2398        wd_DEBUG("server free space is %lld\n",size_server);
2399
2400        if(size_server> size_lo)
2401        {
2402
2403            wd_DEBUG("server freespace is enough!\n");
2404
2405            return 1;
2406        }
2407        else
2408        {
2409
2410            wd_DEBUG("server freespace is not enough!\n");
2411
2412            return 0;
2413        }
2414    }
2415    return status;
2416
2417}
2418int free_upload_chunk_info()
2419{
2420    if(upload_chunk != NULL)
2421    {
2422        if(upload_chunk->upload_id != NULL)
2423            free(upload_chunk->upload_id);
2424        if(upload_chunk->filename != NULL)
2425            free(upload_chunk->filename);
2426        free(upload_chunk);
2427        upload_chunk = NULL;
2428    }
2429    return 1;
2430}
2431
2432int add_upload_chunked_info(char *filename,char *upload_id,unsigned long offset,unsigned long chunk,time_t expires)
2433{
2434    upload_chunk = (Upload_chunked *)malloc(sizeof(Upload_chunked));
2435    memset(upload_chunk,0,sizeof(upload_chunk));
2436    upload_chunk->filename = (char *)malloc(sizeof(char)*(strlen(filename)+1));
2437    memset(upload_chunk->filename,'\0',strlen(filename)+1);
2438    sprintf(upload_chunk->filename,"%s",filename);
2439    upload_chunk->upload_id = (char *)malloc(sizeof(char)*(strlen(upload_id)+1));
2440    memset(upload_chunk->upload_id,'\0',strlen(upload_id)+1);
2441    sprintf(upload_chunk->upload_id,"%s",upload_id);
2442    upload_chunk->chunk = chunk;
2443    upload_chunk->offset = offset;
2444    upload_chunk->expires = expires;
2445    return 1;
2446}
2447
2448int api_upload_chunk_continue(char *filename,int index,int flag,char *serverpath,unsigned long size)
2449{
2450    wd_DEBUG("api_upload_chunk_continue\n");
2451    int res=0;
2452    unsigned long offset=4*1000*1000;//4M chunk
2453    unsigned long chunk = 0;
2454    FILE *fp_1;
2455    char *upload_id = (char *)malloc(sizeof(char)*(strlen(upload_chunk->upload_id)+1));
2456    time_t expires = upload_chunk->expires;
2457    memset(upload_id,'\0',strlen(upload_chunk->upload_id)+1);
2458    sprintf(upload_id,"%s",upload_chunk->upload_id);
2459    char *buffer = malloc(4000000);
2460    fp_1=fopen(filename,"r");
2461
2462    if(fp_1 == NULL)
2463    {
2464        wd_DEBUG("open %s failed\n",filename);
2465        return -1;
2466    }
2467    fseek(fp_1,upload_chunk->chunk,SEEK_SET);
2468
2469    chunk = upload_chunk->chunk;
2470    while(chunk+offset <= size)
2471    {
2472        memset(buffer,0,4000000);
2473        fread(buffer,sizeof(buffer)/10,10,fp_1);
2474        res=api_upload_chunk_put(buffer,upload_id,offset,chunk,index,filename);
2475        if(res != 0)
2476        {
2477            free_upload_chunk_info();
2478            add_upload_chunked_info(filename,upload_id,offset,chunk,expires);
2479
2480            fclose(fp_1);
2481            free(upload_id);
2482            free(buffer);
2483            return res;
2484        }
2485        chunk=chunk+offset;
2486    }
2487    offset = size-chunk;
2488    memset(buffer,0,4000000);
2489    fread(buffer,sizeof(buffer)/10,10,fp_1);
2490    res = api_upload_chunk_put(buffer,upload_id,offset,chunk,index,filename);
2491    if(res != 0)
2492    {
2493        free_upload_chunk_info();
2494        add_upload_chunked_info(filename,upload_id,offset,chunk,expires);
2495        fclose(fp_1);
2496        free(buffer);
2497        free(upload_id);
2498        return res;
2499    }
2500    char *serverpath_encode=oauth_url_escape(serverpath);
2501    res=api_upload_chunk_commit(upload_id,serverpath_encode,flag,index);
2502    free(serverpath_encode);
2503    if(res != 0)
2504    {
2505        free_upload_chunk_info();
2506        fclose(fp_1);
2507        free(upload_id);
2508        free(buffer);
2509        return res;
2510    }
2511
2512    free_upload_chunk_info();
2513    free(buffer);
2514    free(upload_id);
2515    fclose(fp_1);
2516    return 0;
2517}
2518
2519int api_upload_chunk(char *filename,int index,int flag,char *serverpath,unsigned long size)
2520{
2521    int res=0;
2522    unsigned long offset=4*1000*1000;//4M chunk
2523    unsigned long chunk = 0;
2524    FILE *fp_1;
2525    char *upload_id;
2526    fp_1=fopen(filename,"r");
2527
2528    if(fp_1 == NULL)
2529    {
2530        wd_DEBUG("open %s failed\n",filename);
2531        return -1;
2532    }
2533    char *buffer = malloc(4000000);
2534    memset(buffer,0,4000000);
2535    fread(buffer,sizeof(buffer)/10,10,fp_1);
2536    //fwrite(buffer,sizeof(buffer)/10,10,fp_2);
2537    //rewind(fp_2);
2538    //printf("buffer : %s\n",buffer);
2539    start_time = time(NULL);
2540    res = api_upload_chunk_put(buffer,NULL,offset,0,index,filename);//offset :Content-length;chunk :offset
2541    if(res != 0)
2542    {
2543        fclose(fp_1);
2544        free(buffer);
2545        return res;
2546    }
2547
2548    /*
2549    do{
2550        res=api_upload_chunk_put(buffer,NULL,offset,0);//offset :Content-length;chunk :offset
2551    }while(res!=0&&res==7||res==35||res==28);
2552*/
2553    upload_id = get_upload_id();
2554    if(upload_id == NULL)
2555    {
2556        fclose(fp_1);
2557        free(buffer);
2558        return -1;
2559    }
2560    cJSON *json = dofile(Con(TMP_R,upload_chunk_1.txt));
2561    time_t mtime=cJSON_printf_expires(json);
2562    cJSON_Delete(json);
2563    wd_DEBUG("filename chunked file expires : %d\n",mtime);
2564    //exit(1);
2565    chunk = offset;
2566    while(chunk+offset <= size)
2567    {
2568        memset(buffer,0,4000000);
2569        fread(buffer,sizeof(buffer)/10,10,fp_1);
2570        res=api_upload_chunk_put(buffer,upload_id,offset,chunk,index,filename);
2571        if(res != 0)
2572        {
2573            free_upload_chunk_info();
2574            add_upload_chunked_info(filename,upload_id,offset,chunk,mtime);
2575
2576            fclose(fp_1);
2577            free(upload_id);
2578            free(buffer);
2579            return res;
2580        }
2581        /*
2582        do{
2583            res=api_upload_chunk_put(buffer,upload_id,offset,chunk);
2584        }while(res!=0&&res==7||res==35||res==28);
2585        */
2586        chunk=chunk+offset;
2587    }
2588    offset=size-chunk;
2589    memset(buffer,0,4000000);
2590    fread(buffer,sizeof(buffer)/10,10,fp_1);
2591    res=api_upload_chunk_put(buffer,upload_id,offset,chunk,index,filename);
2592    if(res!=0)
2593    {
2594        free_upload_chunk_info();
2595        add_upload_chunked_info(filename,upload_id,offset,chunk,mtime);
2596        fclose(fp_1);
2597        free(upload_id);
2598        free(buffer);
2599        return res;
2600    }
2601    /*
2602    do{
2603        res=api_upload_chunk_put(buffer,upload_id,offset,chunk);
2604    }while(res!=0&&res==7||res==35||res==28);
2605    */
2606    char *serverpath_encode=oauth_url_escape(serverpath);
2607    res=api_upload_chunk_commit(upload_id,serverpath_encode,flag,index);
2608    free(serverpath_encode);
2609    if(res!=0)
2610    {
2611        fclose(fp_1);
2612        free(upload_id);
2613        free(buffer);
2614        return res;
2615    }
2616
2617    free_upload_chunk_info();
2618    free(upload_id);
2619    free(buffer);
2620    fclose(fp_1);
2621    return 0;
2622}
2623/*
2624 filename=>local full filename
2625 serverpath=>server full filename
2626 third para:ture or false
2627 ture=>server filename will be overwrite
2628 false=>server filename will not overwrite,but local filename will be rename ,ex xxx.txt=>xxx(1).txt
2629 */
2630int upload_file(char *filename,char *serverpath,int flag,int index)
2631{
2632
2633
2634    wd_DEBUG("*****************Upload***************\n");
2635
2636    if(access(filename,F_OK) != 0)
2637    {
2638
2639        wd_DEBUG("Local has no %s\n",filename);
2640        //add_action_item("upload",filename,g_pSyncList[index]->access_failed_list);
2641        return LOCAL_FILE_LOST;
2642    }
2643#if 1
2644    int server_enough;
2645    server_enough=is_server_enough(filename);
2646    if(server_enough != 1)
2647    {
2648        if(server_enough == 0)
2649        {
2650            write_log(S_ERROR,"server space is not enough!","",index);
2651            action_item *item;
2652            item = get_action_item("upload",filename,g_pSyncList[index]->up_space_not_enough_list,index);
2653            if(item == NULL)
2654            {
2655                add_action_item("upload",filename,g_pSyncList[index]->up_space_not_enough_list);
2656            }
2657            return SERVER_SPACE_NOT_ENOUGH;
2658        }
2659        else
2660        {
2661            return server_enough;
2662        }
2663    }
2664#endif
2665    unsigned long MAX_FILE_SIZE=140*1000*1000;
2666
2667    int res=0;
2668
2669    write_log(S_UPLOAD,"",filename,index);
2670
2671    long long int size = get_file_size(filename);
2672    if( size == -1)
2673    {
2674        if(access(filename,F_OK) != 0)
2675        {
2676
2677            wd_DEBUG("Local has no %s\n",filename);
2678            //add_action_item("upload",filename,g_pSyncList[index]->access_failed_list);
2679            return LOCAL_FILE_LOST;
2680        }
2681    }
2682    if( size >= MAX_FILE_SIZE )
2683    {
2684        //vpOkR7xVrTZKrFl05pPSww
2685        if(upload_chunk != NULL)
2686        {
2687            time_t cur_ts = time(NULL);
2688            time_t expires = upload_chunk->expires;
2689            if(strcmp(filename,upload_chunk->filename) == 0 || expires == -1 || cur_ts < expires)
2690            {
2691                res = api_upload_chunk_continue(filename,index,flag,serverpath,size);
2692                if(res != 0)
2693                {
2694                    return res;
2695                }
2696            }
2697            else
2698            {
2699                free_upload_chunk_info();
2700                res = api_upload_chunk(filename,index,flag,serverpath,size);
2701                if(res != 0)
2702                {
2703                    return res;
2704                }
2705            }
2706        }
2707        else
2708        {
2709            res = api_upload_chunk(filename,index,flag,serverpath,size);
2710            if(res != 0)
2711            {
2712                return res;
2713            }
2714        }
2715    }
2716    else
2717    {
2718        char *serverpath_encode=oauth_url_escape(serverpath);
2719        res=api_upload_put(filename,serverpath_encode,flag,index);
2720        free(serverpath_encode);
2721        if(res!=0)
2722        {
2723            return res;
2724        }
2725    }
2726    if(finished_initial)
2727        write_log(S_SYNC,"","",index);
2728    else
2729        write_log(S_INITIAL,"","",index);
2730    return 0;
2731    //fclose(fp_2);
2732
2733}
2734int api_delete(char *herf,int index)
2735{
2736    CURL *curl;
2737    CURLcode res;
2738    FILE *fp;
2739    char *herf_tmp=oauth_url_escape(herf);
2740    char *data=(char *)malloc(sizeof(char)*(strlen(herf_tmp)+64));
2741    memset(data,0,strlen(herf_tmp)+64);
2742
2743    sprintf(data,"%s%s","root=dropbox&path=",herf_tmp);
2744    free(herf_tmp);
2745    //char data[]="root=dropbox&path=/main.py";
2746    char *header;
2747#ifdef OAuth1
2748    header=makeAuthorize(3);
2749#else
2750    header=makeAuthorize(1);
2751#endif
2752    struct curl_slist *headerlist=NULL;
2753    curl=curl_easy_init();
2754    headerlist=curl_slist_append(headerlist,header);
2755    if(curl){
2756        curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,0L);
2757        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
2758        curl_easy_setopt(curl,CURLOPT_URL,"https://api.dropbox.com/1/fileops/delete");
2759        CURL_DEBUG;
2760        curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headerlist);
2761        curl_easy_setopt(curl,CURLOPT_POSTFIELDS,data);
2762        //curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,0);
2763        fp=fopen(Con(TMP_R,api_delete.txt),"w");
2764        curl_easy_setopt(curl,CURLOPT_TIMEOUT,90);
2765        curl_easy_setopt(curl,CURLOPT_WRITEDATA,fp);
2766        res=curl_easy_perform(curl);
2767
2768        curl_easy_cleanup(curl);
2769        fclose(fp);
2770        curl_slist_free_all(headerlist);
2771        if(res!=0){
2772            free(header);
2773            free(data);
2774            char error_info[100];
2775            memset(error_info,0,sizeof(error_info));
2776            sprintf(error_info,"%s%s","delete fail ",herf);
2777            wd_DEBUG("delete %s failed,id [%d]!\n",herf,res);
2778            return res;
2779        }
2780    }
2781    free(header);
2782    free(data);
2783    return 0;
2784}
2785/*
2786 lcoalpath=>local name
2787 folderpath=>server path
2788*/
2789int api_create_folder(char *localpath,char *foldername)
2790{
2791
2792    wd_DEBUG("****************create_folder****************\n");
2793
2794    if(access(localpath,0) != 0)
2795    {
2796
2797        wd_DEBUG("Local has no %s\n",localpath);
2798
2799        return LOCAL_FILE_LOST;
2800    }
2801
2802    CURL *curl;
2803    CURLcode res;
2804    FILE *fp;
2805    fp=fopen(Con(TMP_R,create_folder.txt),"w");
2806
2807    FILE *fp_hd;
2808    fp_hd=fopen(Con(TMP_R,create_folder_header.txt),"w");
2809
2810    //char data[]="root=dropbox&path=/main";
2811    char *foldername_tmp=oauth_url_escape(foldername);
2812    char *data=(char *)malloc(sizeof(char)*(strlen(foldername_tmp)+32));
2813    memset(data,0,strlen(foldername_tmp)+32);
2814    sprintf(data,"%s%s","root=dropbox&path=",foldername_tmp);
2815    free(foldername_tmp);
2816    char *header;
2817#ifdef OAuth1
2818    header=makeAuthorize(3);
2819#else
2820    header=makeAuthorize(1);
2821#endif
2822    struct curl_slist *headerlist=NULL;
2823    curl=curl_easy_init();
2824    headerlist=curl_slist_append(headerlist,header);
2825    if(curl){
2826        curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,0L);
2827        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
2828        curl_easy_setopt(curl,CURLOPT_URL,"https://api.dropbox.com/1/fileops/create_folder");
2829        CURL_DEBUG;
2830        curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headerlist);
2831        curl_easy_setopt(curl,CURLOPT_POSTFIELDS,data);
2832        //curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,0);
2833
2834        curl_easy_setopt(curl,CURLOPT_TIMEOUT,90);
2835        curl_easy_setopt(curl,CURLOPT_WRITEDATA,fp);
2836        curl_easy_setopt(curl,CURLOPT_WRITEHEADER,fp_hd);
2837        res=curl_easy_perform(curl);
2838
2839        curl_easy_cleanup(curl);
2840        fclose(fp);
2841        fclose(fp_hd);
2842        curl_slist_free_all(headerlist);
2843        if(res!=0){
2844            free(header);
2845            free(data);
2846            wd_DEBUG("create %s failed,is [%d] !\n",foldername,res);
2847            return res;
2848        }
2849        else
2850        {
2851            /*deal big or small case sentive problem,will return 403*/
2852            if(parse_create_folder(Con(TMP_R,create_folder_header.txt)))
2853            {
2854#ifndef MULTI_PATH
2855                char *server_conflcit_name=get_server_exist(foldername,0);
2856                if(server_conflcit_name)
2857                {
2858                    char *local_conflcit_name = serverpath_to_localpath(server_conflcit_name,0);
2859                    char *g_newname = get_confilicted_name_case(local_conflcit_name,1);
2860                    my_free(local_conflcit_name);
2861
2862                    updata_socket_list(localpath,g_newname,0);
2863
2864                    if(access(localpath,0) == 0)
2865                    {
2866                        add_action_item("rename",g_newname,g_pSyncList[0]->server_action_list);
2867                        rename(localpath,g_newname);
2868                    }
2869
2870                    char *s_newname = localpath_to_serverpath(g_newname,0);
2871                    int status=0;
2872                    do
2873                    {
2874                        status = api_create_folder(g_newname,s_newname);
2875                    }while(status != 0 && !exit_loop);
2876                    my_free(g_newname);
2877                    my_free(s_newname);
2878                }
2879#endif
2880            }
2881        }
2882    }
2883    free(header);
2884    free(data);
2885    return 0;
2886}
2887int parse_config_mutidir(char *path,struct asus_config *config)
2888{
2889    FILE *fp;
2890    wd_DEBUG("filename:%s\n",path);
2891    char buf[512];
2892    char *buffer = buf;
2893    char *p;
2894    int i = 0;
2895    int k = 0;
2896    int j = 0;
2897
2898    //memset(username, 0, sizeof(username));
2899    //memset(password, 0, sizeof(password));
2900    memset(buf,0,sizeof(buf));
2901
2902    if (access(path,0) == 0)
2903    {
2904        if(( fp = fopen(path,"r"))==NULL)
2905        {
2906            fprintf(stderr,"read Cloud error");
2907            return -1;
2908        }
2909        else
2910        {
2911            while(fgets(buffer,512,fp)!=NULL)
2912            {
2913                if(buffer[strlen(buffer)-1] == '\n')
2914                {
2915                    buffer[strlen(buffer)-1] = '\0';
2916                }
2917                p=buffer;
2918                printf("p is %s,outer is %s\n",p,buffer);
2919                switch (i)
2920                {
2921                case 0 :
2922                    config->type = atoi(p);
2923                    //printf("config->type:%d\n",config->type);
2924                    break;
2925                case 1:
2926                    config->enable = atoi(p);
2927                    //printf("config->enable:%d\n",config->enable);
2928                    break;
2929                case 2:
2930                    strncpy(config->user,p,strlen(p));
2931                    if(config->user[strlen(config->user)-1]=='\n')
2932                    {
2933                        //printf("aaaa\n");
2934                        config->user[strlen(config->user)-1]='\0';
2935                    }
2936                    //printf("%d\n",strlen(config->user));
2937                    //printf("config->user:%c\n",config->user[strlen(config->user)-2]);
2938                    break;
2939                    case 3:
2940
2941                    strncpy(config->pwd,p,strlen(p));
2942                    if(config->pwd[strlen(config->pwd)-1]=='\n')
2943                    {
2944                        //printf("aaaa\n");
2945                        config->pwd[strlen(config->pwd)-1]='\0';
2946                    }
2947                    //printf("%d\n",strlen(config->pwd));
2948                    //printf("config->user:%c\n",config->pwd[8]);
2949                    break;
2950                    case 4:
2951                    //printf("case is %d,p is %s\n",i,p);
2952                    config->dir_number = atoi(p);
2953                    config->prule = (struct asus_rule **)malloc(sizeof(struct asus_rule*)*config->dir_number);
2954                    if(NULL == config->prule)
2955                    {
2956                        return -1;
2957                    }
2958                    break;
2959                    default:
2960                    k = j / 2 ;
2961                    if(i % 2 == 1)
2962                    {
2963                        config->prule[k] = (struct asus_rule*)malloc(sizeof(struct asus_rule));
2964                        config->prule[k]->rule = atoi(p);
2965                    }
2966                    else
2967                    {
2968                        char *dp;
2969                        strcpy(config->prule[k]->path,p);
2970                        dp=strrchr(config->prule[k]->path,'/');
2971                        //strncpy(config->prule[k]->base_path,config->prule[k]->path,strlen(config->prule[k]->path)-strlen(dp));
2972                        snprintf(config->prule[k]->base_path,strlen(config->prule[k]->path)-strlen(dp)+1,"%s",config->prule[k]->path);
2973                        config->prule[k]->base_path_len=strlen(config->prule[k]->path)-strlen(dp);
2974                        //dp++;
2975                        strcpy(config->prule[k]->rooturl,dp);
2976                        config->prule[k]->rooturl_len=strlen(dp);
2977                    }
2978                    j++;
2979                    break;
2980//                    case 4:
2981//                    config->ismuti = atoi(p);
2982//                    //printf("config->user:%d\n",config->ismuti);
2983//                    break;
2984//                    case 5:
2985//                    //printf("case is %d,p is %s\n",i,p);
2986//                    config->dir_number = atoi(p);
2987//                    config->prule = (struct asus_rule **)malloc(sizeof(struct asus_rule*)*config->dir_number);
2988//                    if(NULL == config->prule)
2989//                    {
2990//                        return -1;
2991//                    }
2992//                    break;
2993//                    default:
2994//                    k = j / 2 ;
2995//                    if(i % 2 == 0)
2996//                    {
2997//                        config->prule[k] = (struct asus_rule*)malloc(sizeof(struct asus_rule));
2998//                        config->prule[k]->rule = atoi(p);
2999//                    }
3000//                    else
3001//                    {
3002//                        char *dp;
3003//                        strcpy(config->prule[k]->path,p);
3004//                        dp=strrchr(config->prule[k]->path,'/');
3005//                        //strncpy(config->prule[k]->base_path,config->prule[k]->path,strlen(config->prule[k]->path)-strlen(dp));
3006//                        snprintf(config->prule[k]->base_path,strlen(config->prule[k]->path)-strlen(dp)+1,"%s",config->prule[k]->path);
3007//                        config->prule[k]->base_path_len=strlen(config->prule[k]->path)-strlen(dp);
3008//                        //dp++;
3009//                        strcpy(config->prule[k]->rooturl,dp);
3010//                    }
3011//                    j++;
3012//                    break;
3013                }
3014                i++;
3015            }
3016
3017            fclose(fp);
3018            return 0;
3019        }
3020    }
3021    else
3022        return -1;
3023
3024}
3025void init_globar_var()
3026{
3027#if TOKENFILE
3028    sync_disk_removed = 0;
3029    disk_change = 0;
3030#endif
3031    upload_chunk = NULL;
3032    access_token_expired = 0;
3033    exit_loop = 0;
3034    stop_progress = 0;
3035    finished_initial=0;
3036    sprintf(log_path,"/tmp/smartsync/.logs");
3037    my_mkdir("/tmp/smartsync");
3038    my_mkdir("/tmp/smartsync/dropbox");
3039    my_mkdir("/tmp/smartsync/dropbox/config");
3040    my_mkdir("/tmp/smartsync/dropbox/script");
3041    my_mkdir("/tmp/smartsync/dropbox/temp");
3042#ifdef NVRAM_
3043    my_mkdir("/tmp/smartsync/script");
3044#endif
3045    my_mkdir(TMP_R);
3046    my_mkdir("/tmp/smartsync/.logs");
3047    sprintf(general_log,"%s/dropbox",log_path);
3048    sprintf(trans_excep_file,"%s/dropbox_errlog",log_path);
3049
3050    pthread_mutex_init(&mutex, NULL);
3051    pthread_mutex_init(&mutex_socket, NULL);
3052    pthread_mutex_init(&mutex_receve_socket, NULL);
3053    pthread_mutex_init(&mutex_log, NULL);
3054    //pthread_mutex_init(&mutex_sync, NULL);
3055    pthread_cond_init(&cond, NULL);
3056    pthread_cond_init(&cond_socket, NULL);
3057    pthread_cond_init(&cond_log, NULL);
3058    memset(&asus_cfg,'\0',sizeof(struct asus_config));
3059#if TOKENFILE
3060    memset(&asus_cfg_stop,0,sizeof(struct asus_config));
3061    if(initial_tokenfile_info_data(&tokenfile_info_start) == NULL)
3062    {
3063        return;
3064    }
3065#endif
3066}
3067void read_config()
3068{
3069#if TOKENFILE
3070#ifdef NVRAM_
3071    if(convert_nvram_to_file_mutidir(CONFIG_PATH,&asus_cfg) == -1)
3072    {
3073        wd_DEBUG("convert_nvram_to_file fail\n");
3074        return;
3075    }
3076#else
3077#ifndef WIN_32
3078    if(create_webdav_conf_file(&asus_cfg) == -1)
3079    {
3080        wd_DEBUG("create_dropbox_conf_file fail\n");
3081        return;
3082    }
3083#endif
3084#endif
3085#endif
3086    int i;
3087    if(parse_config_mutidir(CONFIG_PATH,&asus_cfg) == -1)
3088    {
3089        wd_DEBUG("parse_config_mutidir fail\n");
3090        no_config = 1;
3091        return;
3092    }
3093//    wd_DEBUG("%d,%s,%s,%d,%d,%d\n",asus_cfg.type,asus_cfg.user,asus_cfg.pwd,
3094//             asus_cfg.enable,asus_cfg.ismuti,asus_cfg.dir_number);
3095    wd_DEBUG("%d,%s,%s,%d,%d\n",asus_cfg.type,asus_cfg.user,asus_cfg.pwd,
3096             asus_cfg.enable,asus_cfg.dir_number);
3097
3098    //conflict_log = (char **)malloc(sizeof(char *)*asus_cfg.dir_number);
3099
3100    for(i=0;i<asus_cfg.dir_number;i++)
3101    {
3102        //int len = strlen(".smartsync")+strlen("dropbox")+asus_cfg.prule[i]->base_path_len+
3103        //conflict_log[i] = my_str_malloc()
3104        write_log(S_INITIAL,"","",i);
3105        wd_DEBUG("rule is %d,path is %s,rooturl is %s\n",asus_cfg.prule[i]->rule,asus_cfg.prule[i]->path,asus_cfg.prule[i]->rooturl);
3106
3107    //printf("base_path:%s,base_path_len:%d\n",asus_cfg.prule[0]->base_path,asus_cfg.prule[0]->base_path_len);
3108    }
3109    strcpy(username,asus_cfg.user);
3110    strcpy(password,asus_cfg.pwd);
3111    wd_DEBUG("222\n");
3112    if( strlen(username) == 0 )
3113    {
3114
3115        wd_DEBUG("username is blank ,please input your username and passwrod\n");
3116
3117        no_config = 1;
3118    }
3119
3120//    if(!no_config)
3121//    {
3122//        for(i=0;i<asus_cfg.dir_number;i++)
3123//            my_mkdir_r(asus_cfg.prule[i]->path);
3124//    }
3125
3126    no_config = 0 ;
3127    exit_loop = 0;
3128
3129}
3130
3131int sync_initial_again(int index)
3132{
3133    int i,status,ret;
3134
3135    i = index;
3136
3137    ret = 1;
3138    if(exit_loop == 0)
3139    {
3140#ifdef MULTI_PATH
3141            if(api_metadata_test_dir(asus_cfg.prule[i]->rooturl,dofile)!=0)
3142            {
3143                wd_DEBUG("\nserver sync path is not exist,need create\n");
3144                api_create_folder(asus_cfg.prule[i]->base_path,asus_cfg.prule[i]->rooturl);
3145                //exit(0);
3146            }
3147#endif
3148        free_server_tree(g_pSyncList[i]->ServerRootNode);
3149        g_pSyncList[i]->ServerRootNode = NULL;
3150
3151        g_pSyncList[i]->ServerRootNode = create_server_treeroot();
3152#ifdef MULTI_PATH
3153        status = browse_to_tree(asus_cfg.prule[i]->rooturl,g_pSyncList[i]->ServerRootNode);
3154#else
3155        status = browse_to_tree("/",g_pSyncList[i]->ServerRootNode);
3156#endif
3157
3158        usleep(1000*200);
3159        if(status != 0)
3160            return status;
3161
3162        if(exit_loop == 0)
3163        {
3164
3165            if(test_if_dir_empty(asus_cfg.prule[i]->path))
3166            {
3167
3168                g_pSyncList[i]->init_completed=1;
3169                g_pSyncList[i]->OldServerRootNode = g_pSyncList[i]->ServerRootNode;
3170                ret = 0;
3171            }
3172            else
3173            {
3174
3175                wd_DEBUG("######## init sync folder,please wait......#######\n");
3176
3177                if(g_pSyncList[i]->ServerRootNode->Child != NULL)
3178                {
3179                    ret=sync_local_with_server(g_pSyncList[i]->ServerRootNode->Child,sync_local_with_server_init,i);
3180                }
3181
3182                wd_DEBUG("######## init sync folder end#######\n");
3183
3184                if(ret != 0 )
3185                    return ret;
3186                g_pSyncList[i]->init_completed = 1;
3187                g_pSyncList[i]->OldServerRootNode = g_pSyncList[i]->ServerRootNode;
3188            }
3189        }
3190    }
3191    if(ret == 0)
3192        write_log(S_SYNC,"","",i);
3193
3194    return ret;
3195}
3196
3197int sync_initial()
3198{
3199    int i,status,ret;
3200    for(i=0;i<asus_cfg.dir_number;i++)
3201    {
3202
3203
3204        if(exit_loop)
3205            break;
3206#if TOKENFILE
3207        if(disk_change)
3208        {
3209            //disk_change = 0;
3210            check_disk_change();
3211        }
3212
3213        if(g_pSyncList[i]->sync_disk_exist == 0)
3214        {
3215            write_log(S_ERROR,"Sync disk unplug!","",i);
3216            continue;
3217        }
3218#endif
3219        if(g_pSyncList[i]->init_completed)
3220            continue;
3221
3222        ret = 1;
3223        if(exit_loop == 0)
3224        {
3225#ifdef MULTI_PATH
3226            if(api_metadata_test_dir(asus_cfg.prule[i]->rooturl,dofile)!=0)
3227            {
3228                wd_DEBUG("\nserver sync path is not exist,need create\n");
3229                api_create_folder(asus_cfg.prule[i]->base_path,asus_cfg.prule[i]->rooturl);
3230                //exit(0);
3231            }
3232#endif
3233            free_server_tree(g_pSyncList[i]->ServerRootNode);
3234            g_pSyncList[i]->ServerRootNode = NULL;
3235
3236            g_pSyncList[i]->ServerRootNode = create_server_treeroot();
3237#ifdef MULTI_PATH
3238            status = browse_to_tree(asus_cfg.prule[i]->rooturl,g_pSyncList[i]->ServerRootNode);
3239#else
3240            status = browse_to_tree("/",g_pSyncList[i]->ServerRootNode);
3241#endif
3242//            for(i=0;i<asus_cfg.dir_number;i++)
3243//            {
3244//                SearchServerTree(g_pSyncList[i]->ServerRootNode);
3245//                //free_server_tree(g_pSyncList[i]->ServerRootNode);
3246//            }
3247            //exit(0);
3248            usleep(1000*200);
3249            if(status != 0)
3250                continue;
3251
3252            if(exit_loop == 0)
3253            {
3254
3255                if(test_if_dir_empty(asus_cfg.prule[i]->path))
3256                {
3257                    if(asus_cfg.prule[i]->rule != 2)
3258                    {
3259
3260                        wd_DEBUG("######## init sync empty folder,please wait......#######\n");
3261
3262                        if(g_pSyncList[i]->ServerRootNode->Child != NULL)
3263                        {
3264                            ret=initMyLocalFolder(g_pSyncList[i]->ServerRootNode->Child,i);
3265                            if(ret != 0 )
3266                                continue;
3267                            g_pSyncList[i]->init_completed=1;
3268                            g_pSyncList[i]->OldServerRootNode = g_pSyncList[i]->ServerRootNode;
3269                        }
3270
3271                        wd_DEBUG("######## init sync empty folder end#######\n");
3272
3273                    }
3274                    else
3275                    {
3276                        g_pSyncList[i]->init_completed=1;
3277                        g_pSyncList[i]->OldServerRootNode = g_pSyncList[i]->ServerRootNode;
3278                        /*
3279                         fix upload only rule local is empty,UI log is still show "initial"
3280                        */
3281                        ret = 0;
3282                    }
3283                }
3284                else
3285                {
3286
3287                    wd_DEBUG("######## init sync folder,please wait......#######\n");
3288
3289                    if(g_pSyncList[i]->ServerRootNode->Child != NULL)
3290                    {
3291                        ret=sync_local_with_server(g_pSyncList[i]->ServerRootNode->Child,sync_local_with_server_init,i);
3292                    }
3293
3294                    wd_DEBUG("######## init sync folder end#######\n");
3295
3296                    if(ret != 0 )
3297                        continue;
3298                    g_pSyncList[i]->init_completed = 1;
3299                    g_pSyncList[i]->OldServerRootNode = g_pSyncList[i]->ServerRootNode;
3300                }
3301            }
3302        }
3303        if(ret == 0)
3304            write_log(S_SYNC,"","",i);
3305
3306    }
3307
3308
3309    return ret;
3310}
3311int sync_local_with_server(Server_TreeNode *treenode,int(* sync_fun)(Server_TreeNode *,Browse*,Local*,int),int index)
3312{
3313    if(treenode->parenthref == NULL)
3314        return 0;
3315    Local *localnode;
3316    char *localpath;
3317    int ret=0;
3318#ifdef MULTI_PATH
3319    localpath=serverpath_to_localpath(treenode->parenthref,index);
3320#else
3321    if(strcmp(treenode->parenthref,"/") == 0)
3322    {
3323        localpath = (char *)malloc(sizeof(char)*(asus_cfg.prule[index]->base_path_len+asus_cfg.prule[index]->rooturl_len+2));
3324        memset(localpath,'\0',asus_cfg.prule[index]->base_path_len+asus_cfg.prule[index]->rooturl_len+2);
3325        sprintf(localpath,"%s%s",asus_cfg.prule[index]->base_path,asus_cfg.prule[index]->rooturl);
3326    }
3327    else
3328    {
3329        localpath=serverpath_to_localpath(treenode->parenthref,index);
3330    }
3331#endif
3332
3333    localnode=Find_Floor_Dir(localpath);
3334    free(localpath);
3335
3336    if(localnode != NULL)
3337    {
3338        ret=sync_fun(treenode,treenode->browse,localnode,index);
3339        if(ret != 0 && ret != SERVER_SPACE_NOT_ENOUGH
3340           && ret != LOCAL_FILE_LOST)
3341        {
3342            free_localfloor_node(localnode);
3343            return ret;
3344        }
3345        free_localfloor_node(localnode);
3346    }
3347    if(treenode->Child != NULL && !exit_loop)
3348    {
3349        ret =sync_local_with_server(treenode->Child,sync_fun,index);
3350        if(ret != 0 && ret != SERVER_SPACE_NOT_ENOUGH
3351           && ret != LOCAL_FILE_LOST)
3352        {
3353            return ret;
3354        }
3355    }
3356    if(treenode->NextBrother != NULL && !exit_loop)
3357    {
3358        ret = sync_local_with_server(treenode->NextBrother,sync_fun,index);
3359        if(ret != 0 && ret != SERVER_SPACE_NOT_ENOUGH
3360           && ret != LOCAL_FILE_LOST)
3361        {
3362            return ret;
3363        }
3364    }
3365    return ret;
3366}
3367int sync_local_with_server_init(Server_TreeNode *treenode,Browse *perform_br,Local *perform_lo,int index)
3368{
3369    wd_DEBUG("parentf = %s\n",treenode->parenthref);
3370    wd_DEBUG("perform_br->foldernumber = %d,perform_br->filenumber = %d,\n",perform_br->foldernumber,perform_br->filenumber);
3371    wd_DEBUG("perform_lo->foldernumber = %d,perform_lo->filenumber = %d,\n",perform_lo->foldernumber,perform_lo->filenumber);
3372    if(perform_br == NULL || perform_lo == NULL)
3373    {
3374        return 0;
3375    }
3376    int ret = 0;
3377
3378    CloudFile *foldertmp=NULL;
3379    CloudFile *filetmp=NULL;
3380    LocalFolder *localfoldertmp;
3381    LocalFile *localfiletmp;
3382    if(perform_br->foldernumber > 0)
3383        foldertmp = perform_br->folderlist->next;
3384    if(perform_br->filenumber > 0)
3385        filetmp = perform_br->filelist->next;
3386    localfoldertmp=perform_lo->folderlist->next;
3387    localfiletmp=perform_lo->filelist->next;
3388
3389    /****************handle files****************/
3390    if(perform_br->filenumber == 0 && perform_lo->filenumber !=0)
3391    {
3392        while(localfiletmp != NULL && !exit_loop)
3393        {
3394            if(asus_cfg.prule[index]->rule != 1)
3395            {
3396                if(wait_handle_socket(index))
3397                {
3398                    return HAVE_LOCAL_SOCKET;
3399                }
3400
3401                char *serverpath=localpath_to_serverpath(localfiletmp->path,index);
3402                ret=upload_file(localfiletmp->path,serverpath,1,index);
3403                if(ret == 0 || ret == SERVER_SPACE_NOT_ENOUGH || ret == LOCAL_FILE_LOST)
3404                {
3405                    if(ret == 0)
3406                    {
3407                        cJSON *json = dofile(Con(TMP_R,upload_chunk_commit.txt));
3408                        time_t mtime=cJSON_printf(json,"modified");
3409                        cJSON_Delete(json);
3410                        ChangeFile_modtime(localfiletmp->path,mtime);
3411                        free(serverpath);
3412                    }
3413                }
3414                else
3415                {
3416                    free(serverpath);
3417                    return ret;
3418                }
3419            }
3420            else
3421            {
3422                if(wait_handle_socket(index))
3423                {
3424                    return HAVE_LOCAL_SOCKET;
3425                }
3426                add_action_item("createfile",localfiletmp->path,g_pSyncList[index]->download_only_socket_head);
3427            }
3428            localfiletmp = localfiletmp->next;
3429        }
3430    }
3431    else if(perform_br->filenumber != 0 && perform_lo->filenumber ==0)
3432    {
3433        while(filetmp != NULL && !exit_loop)
3434        {
3435            if(asus_cfg.prule[index]->rule != 2)
3436            {
3437                if(is_local_space_enough(filetmp,index))
3438                {
3439                    if(wait_handle_socket(index))
3440                    {
3441                        return HAVE_LOCAL_SOCKET;
3442                    }
3443                    char *localpath= serverpath_to_localpath(filetmp->href,index);
3444                    add_action_item("createfile",localpath,g_pSyncList[index]->server_action_list);
3445                    ret=api_download(localpath,filetmp->href,index);
3446                    if(ret == 0)
3447                    {
3448                        ChangeFile_modtime(localpath,filetmp->mtime);
3449                        free(localpath);
3450                    }
3451                    else
3452                    {
3453                        free(localpath);
3454                        return ret;
3455                    }
3456
3457                }
3458                else
3459                {
3460                    write_log(S_ERROR,"local space is not enough!","",index);
3461                    add_action_item("download",filetmp->href,g_pSyncList[index]->unfinished_list);
3462                }
3463            }
3464            filetmp=filetmp->next;
3465        }
3466    }
3467    else if(perform_br->filenumber != 0 && perform_lo->filenumber !=0)
3468    {
3469
3470        while(localfiletmp != NULL && !exit_loop) //is based by localfiletmp
3471        {
3472            int cmp=1;
3473            char *serverpath=localpath_to_serverpath(localfiletmp->path,index);
3474            while(filetmp != NULL)
3475            {
3476                if((cmp=strcmp(serverpath,filetmp->href)) == 0)
3477                {
3478                    free(serverpath);
3479                    break;
3480                }
3481                else
3482                {
3483                    filetmp=filetmp->next;
3484                }
3485            }
3486            if(cmp != 0)
3487            {
3488                if(asus_cfg.prule[index]->rule != 1)
3489                {
3490                    if(wait_handle_socket(index))
3491                    {
3492                        buffer_free(serverpath);
3493                        return HAVE_LOCAL_SOCKET;
3494                    }
3495
3496                    ret=upload_file(localfiletmp->path,serverpath,1,index);
3497                    if(ret == 0 || ret == SERVER_SPACE_NOT_ENOUGH || ret == LOCAL_FILE_LOST)
3498                    {
3499                        if(ret == 0)
3500                        {
3501                            cJSON *json = dofile(Con(TMP_R,upload_chunk_commit.txt));
3502                            time_t mtime=cJSON_printf(json,"modified");
3503                            cJSON_Delete(json);
3504                            ChangeFile_modtime(localfiletmp->path,mtime);
3505                            free(serverpath);
3506                        }
3507                    }
3508                    else
3509                    {
3510                        free(serverpath);
3511                        return ret;
3512                    }
3513                }
3514                else
3515                {
3516                    buffer_free(serverpath);
3517                    if(wait_handle_socket(index))
3518                    {
3519                        return HAVE_LOCAL_SOCKET;
3520                    }
3521                    add_action_item("createfile",localfiletmp->path,g_pSyncList[index]->download_only_socket_head);
3522                }
3523            }
3524            else
3525            {
3526                if((ret = the_same_name_compare(localfiletmp,filetmp,index,1)) != 0)
3527                {
3528                    return ret;
3529                }
3530            }
3531            filetmp=perform_br->filelist->next;
3532            localfiletmp=localfiletmp->next;
3533        }
3534
3535        filetmp=perform_br->filelist->next;
3536        localfiletmp=perform_lo->filelist->next;
3537        while(filetmp != NULL && !exit_loop) //is based by filetmp
3538        {
3539            int cmp=1;
3540            char *localpath=serverpath_to_localpath(filetmp->href,index);
3541            while(localfiletmp != NULL)
3542            {
3543                if((cmp=strcmp(localpath,localfiletmp->path)) == 0)
3544                {
3545                    free(localpath);
3546                    break;
3547                }
3548                else
3549                {
3550                    localfiletmp=localfiletmp->next;
3551                }
3552            }
3553            if(cmp != 0)
3554            {
3555                if(asus_cfg.prule[index]->rule != 2)
3556                {
3557                    if(is_local_space_enough(filetmp,index))
3558                    {
3559                        if(wait_handle_socket(index))
3560                        {
3561                            buffer_free(localpath);
3562                            return HAVE_LOCAL_SOCKET;
3563                        }
3564
3565                        add_action_item("createfile",localpath,g_pSyncList[index]->server_action_list);
3566                        ret=api_download(localpath,filetmp->href,index);
3567                        if(ret == 0)
3568                        {
3569                            ChangeFile_modtime(localpath,filetmp->mtime);
3570                            free(localpath);
3571                        }
3572                        else
3573                        {
3574                            free(localpath);
3575                            return ret;
3576                        }
3577
3578                    }
3579                    else
3580                    {
3581                        buffer_free(localpath);
3582                        write_log(S_ERROR,"local space is not enough!","",index);
3583                        add_action_item("download",filetmp->href,g_pSyncList[index]->unfinished_list);
3584                    }
3585                }
3586            }
3587            localfiletmp=perform_lo->filelist->next;
3588            filetmp=filetmp->next;
3589        }
3590    }
3591    /*************handle folders**************/
3592    if(perform_br->foldernumber !=0 && perform_lo->foldernumber ==0)
3593    {
3594        if(asus_cfg.prule[index]->rule != 2)
3595        {
3596            while(foldertmp != NULL && !exit_loop)
3597            {
3598                if(wait_handle_socket(index))
3599                {
3600                    return HAVE_LOCAL_SOCKET;
3601                }
3602                char *localpath;
3603                localpath = serverpath_to_localpath(foldertmp->href,index);
3604                if(NULL == opendir(localpath))
3605                {
3606                    add_action_item("createfolder",localpath,g_pSyncList[index]->server_action_list);
3607                    int res;
3608                    res = api_metadata_test_dir(foldertmp->href,dofile);
3609                    if(res == 0)
3610                        mkdir(localpath,0777);
3611                    else if(res == -1)
3612                    {
3613                        free(localpath);
3614                        return res;
3615                    }
3616                    else
3617                    {
3618                        wd_DEBUG("this %s had been deleted\n",foldertmp->href);
3619                    }
3620                }
3621                free(localpath);
3622                foldertmp = foldertmp->next;
3623            }
3624        }
3625    }
3626    else if(perform_br->foldernumber ==0 && perform_lo->foldernumber !=0)
3627    {
3628        while(localfoldertmp != NULL && !exit_loop)
3629        {
3630            if(asus_cfg.prule[index]->rule != 1)
3631            {
3632                char *serverpath;
3633                serverpath = localpath_to_serverpath(localfoldertmp->path,index);
3634                ret=api_create_folder(localfoldertmp->path,serverpath);
3635                if(ret == 0)
3636                {
3637                    upload_serverlist(treenode,perform_br,localfoldertmp,index);
3638                    free(serverpath);
3639                }
3640                else
3641                {
3642                    free(serverpath);
3643                    return ret;
3644                }
3645
3646            }
3647            else
3648            {
3649                if(wait_handle_socket(index))
3650                {
3651                    return HAVE_LOCAL_SOCKET;
3652                }
3653                add_action_item("createfolder",localfoldertmp->path,g_pSyncList[index]->download_only_socket_head);
3654            }
3655            localfoldertmp = localfoldertmp->next;
3656        }
3657    }
3658    else if(perform_br->foldernumber !=0 && perform_lo->foldernumber !=0)
3659    {
3660        while(foldertmp != NULL && !exit_loop)
3661        {
3662            int cmp=1;
3663            char *localpath;
3664            localpath = serverpath_to_localpath(foldertmp->href,index);
3665            while(localfoldertmp != NULL)
3666            {
3667                if((cmp = strcmp(localpath,localfoldertmp->path)) == 0)
3668                {
3669                    free(localpath);
3670                    break;
3671                }
3672                localfoldertmp=localfoldertmp->next;
3673            }
3674            if(cmp != 0)
3675            {
3676                if(asus_cfg.prule[index]->rule != 2)
3677                {
3678                    if(wait_handle_socket(index))
3679                    {
3680                        buffer_free(localpath);
3681                        return HAVE_LOCAL_SOCKET;
3682                    }
3683                    if(NULL == opendir(localpath))
3684                    {
3685                        add_action_item("createfolder",localpath,g_pSyncList[index]->server_action_list);
3686                        int res;
3687                        res = api_metadata_test_dir(foldertmp->href,dofile);
3688                        if(res == 0)
3689                            mkdir(localpath,0777);
3690                        else if(res == -1)
3691                        {
3692                            buffer_free(localpath);
3693                            return res;
3694                        }
3695                        else
3696                        {
3697                            wd_DEBUG("this %s had been deleted\n",foldertmp->href);
3698                        }
3699                    }
3700                    free(localpath);
3701                }
3702                else
3703                    buffer_free(localpath);
3704            }
3705            foldertmp = foldertmp->next;
3706            localfoldertmp = perform_lo->folderlist->next;
3707        }
3708
3709
3710        foldertmp = perform_br->folderlist->next;
3711        localfoldertmp = perform_lo->folderlist->next;
3712        while(localfoldertmp != NULL && !exit_loop)
3713        {
3714            int cmp=1;
3715            char *serverpath;
3716            serverpath = localpath_to_serverpath(localfoldertmp->path,index);
3717            while(foldertmp != NULL)
3718            {
3719                if((cmp = strcmp(serverpath,foldertmp->href)) == 0)
3720                {
3721                    free(serverpath);
3722                    break;
3723                }
3724                foldertmp=foldertmp->next;
3725            }
3726            if(cmp != 0)
3727            {
3728                if(asus_cfg.prule[index]->rule != 1)
3729                {
3730                    if(wait_handle_socket(index))
3731                    {
3732                        buffer_free(serverpath);
3733                        return HAVE_LOCAL_SOCKET;
3734                    }
3735                    ret=api_create_folder(localfoldertmp->path,serverpath);
3736                    if(ret == 0)
3737                    {
3738                        upload_serverlist(treenode,perform_br,localfoldertmp,index);
3739                        free(serverpath);
3740                    }
3741                    else
3742                    {
3743                        free(serverpath);
3744                        return ret;
3745                    }
3746                }
3747                else
3748                {
3749                    buffer_free(serverpath);
3750                    if(wait_handle_socket(index))
3751                    {
3752                        return HAVE_LOCAL_SOCKET;
3753                    }
3754                    add_action_item("createfolder",localfoldertmp->path,g_pSyncList[index]->download_only_socket_head);
3755                }
3756            }
3757            foldertmp = perform_br->folderlist->next;
3758            localfoldertmp = localfoldertmp->next;
3759        }
3760    }
3761    return ret;
3762}
3763
3764int sync_local_with_server_perform(Server_TreeNode *treenode,Browse *perform_br,Local *perform_lo,int index)
3765{
3766    wd_DEBUG("parentf = %s\n",treenode->parenthref);
3767    wd_DEBUG("perform_br->foldernumber = %d,perform_br->filenumber = %d,\n",perform_br->foldernumber,perform_br->filenumber);
3768    wd_DEBUG("perform_lo->foldernumber = %d,perform_lo->filenumber = %d,\n",perform_lo->foldernumber,perform_lo->filenumber);
3769    if(perform_br == NULL || perform_lo == NULL)
3770    {
3771        return 0;
3772    }
3773    int ret = 0;
3774
3775    CloudFile *foldertmp=NULL;
3776    CloudFile *filetmp=NULL;
3777    LocalFolder *localfoldertmp;
3778    LocalFile *localfiletmp;
3779    if(perform_br->foldernumber > 0)
3780        foldertmp = perform_br->folderlist->next;
3781    if(perform_br->filenumber > 0)
3782        filetmp = perform_br->filelist->next;
3783    localfoldertmp=perform_lo->folderlist->next;
3784    localfiletmp=perform_lo->filelist->next;
3785
3786    /****************handle files****************/
3787    if(perform_br->filenumber == 0 && perform_lo->filenumber !=0)
3788    {
3789        while(localfiletmp != NULL && exit_loop == 0)
3790        {
3791            if(asus_cfg.prule[index]->rule == 1)
3792            {
3793                action_item *item;
3794                item = get_action_item("download_only",localfiletmp->path,
3795                                       g_pSyncList[index]->download_only_socket_head,index);
3796                if(item != NULL)
3797                {
3798                    localfiletmp = localfiletmp->next;
3799                    continue;
3800                }
3801            }
3802            if(wait_handle_socket(index))
3803            {
3804                return HAVE_LOCAL_SOCKET;
3805            }
3806            add_action_item("remove",localfiletmp->path,g_pSyncList[index]->server_action_list);
3807
3808            //[bug][fix]:local file size > cloud space,then the local file will be unlink
3809            action_item *pp;
3810            pp = get_action_item("upload",localfiletmp->path,
3811                                 g_pSyncList[index]->up_space_not_enough_list,index);
3812            if(pp == NULL)
3813            {
3814                unlink(localfiletmp->path);
3815            }
3816
3817            localfiletmp = localfiletmp->next;
3818        }
3819    }
3820    else if(perform_br->filenumber != 0 && perform_lo->filenumber ==0)
3821    {
3822        while(filetmp != NULL && !exit_loop)
3823        {
3824            if(wait_handle_socket(index))
3825            {
3826                return HAVE_LOCAL_SOCKET;
3827            }
3828            if(is_local_space_enough(filetmp,index))
3829            {
3830                action_item *item;
3831                item = get_action_item("download",filetmp->href,g_pSyncList[index]->unfinished_list,index);
3832
3833                char *localpath= serverpath_to_localpath(filetmp->href,index);
3834
3835                ret=api_download(localpath,filetmp->href,index);
3836                if(ret == 0)
3837                {
3838                    ChangeFile_modtime(localpath,filetmp->mtime);
3839                    if(item != NULL)
3840                    {
3841                        del_action_item("download",filetmp->href,g_pSyncList[index]->unfinished_list);
3842                    }
3843                    free(localpath);
3844                }
3845                else
3846                {
3847                    free(localpath);
3848                    return ret;
3849                }
3850
3851            }
3852            else
3853            {
3854                write_log(S_ERROR,"local space is not enough!","",index);
3855                add_action_item("download",filetmp->href,g_pSyncList[index]->unfinished_list);
3856            }
3857            filetmp=filetmp->next;
3858        }
3859    }
3860    else if(perform_br->filenumber != 0 && perform_lo->filenumber !=0)
3861    {
3862
3863        while(localfiletmp != NULL && !exit_loop) //is based by localfiletmp
3864        {
3865            int cmp=1;
3866            char *serverpath=localpath_to_serverpath(localfiletmp->path,index);
3867            while(filetmp != NULL)
3868            {
3869                if((cmp=strcmp(serverpath,filetmp->href)) == 0)
3870                {
3871                    free(serverpath);
3872                    break;
3873                }
3874                else
3875                {
3876                    filetmp=filetmp->next;
3877                }
3878            }
3879            if(cmp != 0)
3880            {
3881                buffer_free(serverpath);
3882                if(wait_handle_socket(index))
3883                {
3884                    return HAVE_LOCAL_SOCKET;
3885                }
3886                if(asus_cfg.prule[index]->rule == 1)
3887                {
3888                    action_item *item;
3889                    item = get_action_item("download_only",localfiletmp->path,
3890                                           g_pSyncList[index]->download_only_socket_head,index);
3891                    if(item != NULL)
3892                    {
3893                        filetmp = perform_br->filelist->next;
3894                        localfiletmp = localfiletmp->next;
3895                        continue;
3896                    }
3897                }
3898
3899                add_action_item("remove",localfiletmp->path,g_pSyncList[index]->server_action_list);
3900
3901                //[bug][fix]:local file size > cloud space,then the local file will be unlink
3902                action_item *pp;
3903                pp = get_action_item("upload",localfiletmp->path,
3904                                     g_pSyncList[index]->up_space_not_enough_list,index);
3905                if(pp == NULL)
3906                {
3907                    unlink(localfiletmp->path);
3908                }
3909
3910            }
3911            else
3912            {
3913                if((ret = the_same_name_compare(localfiletmp,filetmp,index,0)) != 0)
3914                {
3915                    return ret;
3916                }
3917            }
3918            filetmp=perform_br->filelist->next;
3919            localfiletmp=localfiletmp->next;
3920        }
3921
3922        filetmp=perform_br->filelist->next;
3923        localfiletmp=perform_lo->filelist->next;
3924        while(filetmp != NULL && !exit_loop) //is based by filetmp
3925        {
3926            int cmp=1;
3927            char *localpath=serverpath_to_localpath(filetmp->href,index);
3928            while(localfiletmp != NULL)
3929            {
3930                if((cmp=strcmp(localpath,localfiletmp->path)) == 0)
3931                {
3932                    free(localpath);
3933                    break;
3934                }
3935                else
3936                {
3937                    localfiletmp=localfiletmp->next;
3938                }
3939            }
3940            if(cmp != 0)
3941            {
3942                if(wait_handle_socket(index))
3943                {
3944                    buffer_free(localpath);
3945                    return HAVE_LOCAL_SOCKET;
3946                }
3947                if(is_local_space_enough(filetmp,index))
3948                {
3949                    action_item *item;
3950                    item = get_action_item("download",
3951                                           filetmp->href,g_pSyncList[index]->unfinished_list,index);
3952
3953                    add_action_item("createfile",localpath,g_pSyncList[index]->server_action_list);
3954                    ret=api_download(localpath,filetmp->href,index);
3955                    if(ret == 0)
3956                    {
3957                        ChangeFile_modtime(localpath,filetmp->mtime);
3958                        if(item != NULL)
3959                        {
3960                            del_action_item("download",filetmp->href,g_pSyncList[index]->unfinished_list);
3961                        }
3962                        free(localpath);
3963                    }
3964                    else
3965                    {
3966                        free(localpath);
3967                        return ret;
3968                    }
3969
3970                }
3971                else
3972                {
3973                    buffer_free(localpath);
3974                    write_log(S_ERROR,"local space is not enough!","",index);
3975                    add_action_item("download",filetmp->href,g_pSyncList[index]->unfinished_list);
3976                }
3977
3978            }
3979            localfiletmp=perform_lo->filelist->next;
3980            filetmp=filetmp->next;
3981        }
3982    }
3983    /*************handle folders**************/
3984    if(perform_br->foldernumber !=0 && perform_lo->foldernumber ==0)
3985    {
3986
3987        while(foldertmp != NULL && !exit_loop)
3988        {
3989            if(wait_handle_socket(index))
3990            {
3991                return HAVE_LOCAL_SOCKET;
3992            }
3993            char *localpath;
3994            localpath = serverpath_to_localpath(foldertmp->href,index);
3995            if(NULL == opendir(localpath))
3996            {
3997                int res;
3998                add_action_item("createfolder",localpath,g_pSyncList[index]->server_action_list);
3999                res = api_metadata_test_dir(foldertmp->href,dofile);
4000                if(res == 0)
4001                    mkdir(localpath,0777);
4002                else if(res == -1)
4003                {
4004                    free(localpath);
4005                    return res;
4006                }
4007                else
4008                {
4009                    wd_DEBUG("this %s had been deleted\n",foldertmp->href);
4010                }
4011            }
4012            free(localpath);
4013            foldertmp = foldertmp->next;
4014        }
4015
4016    }
4017    else if(perform_br->foldernumber ==0 && perform_lo->foldernumber !=0)
4018    {
4019        while(localfoldertmp != NULL && !exit_loop)
4020        {
4021            if(asus_cfg.prule[index]->rule == 1)
4022            {
4023                action_item *item;
4024                item = get_action_item("download_only",
4025                                       localfoldertmp->path,g_pSyncList[index]->download_only_socket_head,index);
4026                if(item != NULL)
4027                {
4028                    localfoldertmp = localfoldertmp->next;
4029                    continue;
4030                }
4031            }
4032            if(wait_handle_socket(index))
4033            {
4034                return HAVE_LOCAL_SOCKET;
4035            }
4036            del_all_items(localfoldertmp->path,index);
4037            localfoldertmp = localfoldertmp->next;
4038        }
4039    }
4040    else if(perform_br->foldernumber !=0 && perform_lo->foldernumber !=0)
4041    {
4042        while(foldertmp != NULL && !exit_loop)
4043        {
4044            int cmp=1;
4045            char *localpath;
4046            localpath = serverpath_to_localpath(foldertmp->href,index);
4047            while(localfoldertmp != NULL)
4048            {
4049                if((cmp = strcmp(localpath,localfoldertmp->path)) == 0)
4050                {
4051                    free(localpath);
4052                    break;
4053                }
4054                localfoldertmp=localfoldertmp->next;
4055            }
4056            if(cmp != 0)
4057            {
4058                if(wait_handle_socket(index))
4059                {
4060                    buffer_free(localpath);
4061                    return HAVE_LOCAL_SOCKET;
4062                }
4063                if(NULL == opendir(localpath))
4064                {
4065                    add_action_item("createfolder",localpath,g_pSyncList[index]->server_action_list);
4066                    int res;
4067                    res = api_metadata_test_dir(foldertmp->href,dofile);
4068                    if(res == 0)
4069                        mkdir(localpath,0777);
4070                    else if(res == -1)
4071                    {
4072                        free(localpath);
4073                        return res;
4074                    }
4075                    else
4076                    {
4077                        wd_DEBUG("this %s had been deleted\n",foldertmp->href);
4078                    }
4079                }
4080                free(localpath);
4081            }
4082            foldertmp = foldertmp->next;
4083            localfoldertmp = perform_lo->folderlist->next;
4084        }
4085
4086
4087        foldertmp = perform_br->folderlist->next;
4088        localfoldertmp = perform_lo->folderlist->next;
4089        while(localfoldertmp != NULL && !exit_loop)
4090        {
4091            int cmp=1;
4092            char *serverpath;
4093            serverpath = localpath_to_serverpath(localfoldertmp->path,index);
4094            while(foldertmp != NULL)
4095            {
4096                if((cmp = strcmp(serverpath,foldertmp->href)) == 0)
4097                {
4098                    free(serverpath);
4099                    break;
4100                }
4101                foldertmp=foldertmp->next;
4102            }
4103            if(cmp != 0)
4104            {
4105                buffer_free(serverpath);
4106                if(asus_cfg.prule[index]->rule == 1)
4107                {
4108                    action_item *item;
4109                    item = get_action_item("download_only",
4110                                           localfoldertmp->path,g_pSyncList[index]->download_only_socket_head,index);
4111                    if(item != NULL)
4112                    {
4113                        foldertmp = perform_br->folderlist->next;
4114                        localfoldertmp = localfoldertmp->next;
4115                        continue;
4116                    }
4117                }
4118                if(wait_handle_socket(index))
4119                {
4120                    return HAVE_LOCAL_SOCKET;
4121                }
4122                del_all_items(localfoldertmp->path,index);
4123            }
4124            foldertmp = perform_br->folderlist->next;
4125            localfoldertmp = localfoldertmp->next;
4126        }
4127    }
4128    return ret;
4129}
4130
4131void del_all_items(char *dir,int index)
4132{
4133    struct dirent* ent = NULL;
4134    DIR *pDir;
4135    pDir=opendir(dir);
4136
4137    if(pDir != NULL )
4138    {
4139        while (NULL != (ent=readdir(pDir)))
4140        {
4141            if(!strcmp(ent->d_name,".") || !strcmp(ent->d_name,".."))
4142                continue;
4143
4144            char *fullname;
4145            size_t len;
4146            len = strlen(dir)+strlen(ent->d_name)+2;
4147            fullname = my_str_malloc(len);
4148            sprintf(fullname,"%s/%s",dir,ent->d_name);
4149
4150            if(test_if_dir(fullname) == 1)
4151            {
4152                wait_handle_socket(index);
4153                del_all_items(fullname,index);
4154            }
4155            else
4156            {
4157                wait_handle_socket(index);
4158                add_action_item("remove",fullname,g_pSyncList[index]->server_action_list);
4159                remove(fullname);
4160            }
4161
4162            free(fullname);
4163
4164        }
4165        closedir(pDir);
4166
4167        add_action_item("remove",dir,g_pSyncList[index]->server_action_list);
4168        remove(dir);
4169    }
4170    else
4171        wd_DEBUG("open %s fail \n",dir);
4172}
4173
4174time_t api_getmtime(char *phref,cJSON *(*cmd_data)(char *filename))
4175{
4176    CURL *curl;
4177    CURLcode res;
4178    FILE *fp;
4179    char *myUrl;
4180    char *phref_tmp=oauth_url_escape(phref);
4181    myUrl=(char *)malloc(sizeof(char)*(strlen(phref_tmp)+128));
4182    memset(myUrl,0,strlen(phref_tmp)+128);
4183    sprintf(myUrl,"%s%s","https://api.dropbox.com/1/metadata/dropbox",phref_tmp);
4184    free(phref_tmp);
4185    char *header;
4186    FILE *hd;
4187    hd=fopen(Con(TMP_R,api_getmime.txt),"w+");
4188#ifdef OAuth1
4189    header=makeAuthorize(3);
4190#else
4191    header=makeAuthorize(1);
4192#endif
4193    struct curl_slist *headerlist=NULL;
4194    curl=curl_easy_init();
4195    headerlist=curl_slist_append(headerlist,header);
4196    if(curl){
4197        //curl_easy_setopt(curl,CURLOPT_URL,"https://api.dropbox.com/1/metadata/dropbox/oauth_plaintext_example/main.py?list=true&rev=120e60305d");
4198        //curl_easy_setopt(curl,CURLOPT_URL,"https://api.dropbox.com/1/metadata/dropbox/main");
4199        curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,0L);
4200        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
4201        curl_easy_setopt(curl,CURLOPT_URL,myUrl);
4202        CURL_DEBUG;
4203        curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headerlist);
4204        //curl_easy_setopt(curl,CURLOPT_POSTFIELDS,"");
4205        //curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,0);
4206        fp=fopen(Con(TMP_R,mtime.txt),"w");
4207        curl_easy_setopt(curl,CURLOPT_TIMEOUT,90);
4208        curl_easy_setopt(curl,CURLOPT_WRITEDATA,fp);
4209        curl_easy_setopt(curl,CURLOPT_WRITEHEADER,hd);
4210        res=curl_easy_perform(curl);
4211
4212        curl_easy_cleanup(curl);
4213        fclose(fp);
4214        curl_slist_free_all(headerlist);
4215        if(res!=0){
4216            fclose(hd);
4217            free(header);
4218            free(myUrl);
4219            wd_DEBUG("get %s mtime failed!id: [%d] \n",phref,res);
4220            return -2;
4221        }
4222        else
4223        {
4224            rewind(hd);
4225            char tmp[256]="\0";
4226            fgets(tmp,sizeof(tmp),hd);
4227            fclose(hd);
4228            if(strstr(tmp,"404")!=NULL)
4229            {
4230                return -1;
4231            }
4232        }
4233    }
4234    free(myUrl);
4235    free(header);
4236    cJSON *json;
4237    time_t mtime;
4238    json=cmd_data(Con(TMP_R,mtime.txt));
4239    mtime=cJSON_printf_mtime(json);
4240    cJSON_Delete(json);
4241    if(mtime!=-1)
4242        return mtime;
4243    else
4244        return -1;
4245}
4246/*0,local file newer
4247 *1,server file newer
4248 *2,local time == server time
4249 *-1,get server modtime failed
4250**/
4251int newer_file(char *localpath,int index,int is_init,int rule){
4252
4253    char *serverpath;
4254    serverpath = localpath_to_serverpath(localpath,index);
4255    //printf("serverpath = %s\n",serverpath);
4256    time_t old_mtime;
4257    if(is_init == 0 && rule == 1)
4258    {
4259        CloudFile *filetmp;
4260        filetmp=get_CloudFile_node(g_pSyncList[index]->VeryOldServerRootNode,serverpath,0x2);
4261        if(filetmp == NULL)
4262        {
4263            old_mtime=(time_t)-1;
4264        }
4265        else
4266        {
4267            old_mtime=filetmp->mtime;
4268        }
4269    }
4270
4271    time_t modtime1,modtime2;
4272    modtime1 = api_getmtime(serverpath,dofile);
4273    free(serverpath);
4274    if(modtime1 == -1 || modtime1 == -2)
4275    {
4276
4277        wd_DEBUG("newer_file Getmodtime failed!\n");
4278
4279        return -1;
4280    }
4281
4282    struct stat buf;
4283
4284    //printf("localpath = %s\n",localpath);
4285
4286    if( stat(localpath,&buf) == -1)
4287    {
4288        perror("stat:");
4289        return -1;
4290    }
4291    modtime2 = buf.st_mtime;
4292    wd_DEBUG("local>modtime2 = %lu,server>modtime1 = %lu\n",modtime2,modtime1);
4293
4294    if(is_init)
4295    {
4296        if(modtime2 > modtime1)
4297            return 0;
4298        else if(modtime2 == modtime1 || modtime2 +1 == modtime1) //FAT32 and umount HD than plugin HD ,it will be local time less then server time 1 sec;
4299        {
4300            if(modtime2 +1 == modtime1)
4301                ChangeFile_modtime(localpath,modtime1);
4302            return 2;
4303        }
4304        else
4305            return 1;
4306    }
4307    else
4308    {
4309        if(rule == 1) //download only
4310        {
4311            if(modtime2 > modtime1)
4312                return 0;
4313            else if(modtime2 == modtime1)
4314                return 2;
4315            else
4316            {
4317                if(modtime2 == old_mtime)
4318                    return 1;
4319                else
4320                    return 0;
4321            }
4322        }
4323        else
4324        {
4325            if(modtime2 > modtime1)
4326                return 0;
4327            else if(modtime2 == modtime1)
4328                return 2;
4329            else
4330                return 1;
4331        }
4332    }
4333
4334
4335}
4336char *change_local_same_name(char *fullname)
4337{
4338    int i = 1;
4339    char *temp_name = NULL;
4340    //char *temp_suffix = ".asus.td";
4341    int len = 0;
4342    char *path;
4343    char newfilename[256];
4344
4345    char *fullname_tmp = NULL;
4346    fullname_tmp = my_str_malloc(strlen(fullname)+1);
4347    sprintf(fullname_tmp,"%s",fullname);
4348
4349    char *filename = parse_name_from_path(fullname_tmp);
4350    len = strlen(filename);
4351
4352    wd_DEBUG("filename len is %d\n",len);
4353
4354    path = my_str_malloc((size_t)(strlen(fullname)-len+1));
4355
4356    wd_DEBUG("fullname = %s\n",fullname);
4357
4358    snprintf(path,strlen(fullname)-len+1,"%s",fullname);
4359
4360    wd_DEBUG("path = %s\n",path);
4361
4362    free(fullname_tmp);
4363
4364    while(1)
4365    {
4366        int n = i;
4367        int j = 0;
4368        while((n=(n/10)))
4369        {
4370            j++;
4371        }
4372        memset(newfilename,'\0',sizeof(newfilename));
4373        snprintf(newfilename,252-j,"%s",filename);
4374        sprintf(newfilename,"%s(%d)",newfilename,i);
4375
4376        wd_DEBUG("newfilename = %s\n",newfilename);
4377
4378        i++;
4379
4380        temp_name = my_str_malloc((size_t)(strlen(path)+strlen(newfilename)+1));
4381        sprintf(temp_name,"%s%s",path,newfilename);
4382
4383        if(access(temp_name,F_OK) != 0)
4384            break;
4385        else
4386            free(temp_name);
4387    }
4388
4389    free(path);
4390    free(filename);
4391    return temp_name;
4392}
4393/*
4394 1=>exit;
4395 0=>not exit;
4396 path=>serverpath;
4397 temp_name=>fullname;
4398 */
4399int is_server_exist(char *path,char *temp_name,int index)
4400{
4401    int status;
4402    FileList_one = (CloudFile *)malloc(sizeof(CloudFile));
4403    memset(FileList_one,0,sizeof(CloudFile));
4404
4405    FileList_one->href = NULL;
4406    FileList_one->name = NULL;
4407
4408    FileTail_one = FileList_one;
4409    FileTail_one->next = NULL;
4410    wd_DEBUG("is_server_exist path:%s\n",path);
4411    status=api_metadata_one(path,dofile);
4412    CloudFile *de_filecurrent;
4413    de_filecurrent=FileList_one->next;
4414    while(de_filecurrent != NULL)
4415    {
4416        if(de_filecurrent->href != NULL)
4417        {
4418            wd_DEBUG("de_filecurrent->href:%s\n",de_filecurrent->href);
4419            wd_DEBUG("temp_name           :%s\n",temp_name);
4420            if((status=strcmp(de_filecurrent->href,temp_name))==0)
4421            {
4422                free_CloudFile_item(FileList_one);
4423                return 1;
4424            }
4425
4426        }
4427        de_filecurrent = de_filecurrent->next;
4428    }
4429    free_CloudFile_item(FileList_one);
4430    return 0;
4431
4432}
4433
4434char *get_server_exist(char *temp_name,int index)
4435{
4436    char *path;
4437    char *p = strrchr(temp_name,'/');
4438    path = my_str_malloc(strlen(temp_name)-strlen(p)+1);
4439    snprintf(path,strlen(temp_name)-strlen(p)+1,"%s",temp_name);
4440
4441    int status;
4442    FileList_one = (CloudFile *)malloc(sizeof(CloudFile));
4443    memset(FileList_one,0,sizeof(CloudFile));
4444
4445    FileList_one->href = NULL;
4446    FileList_one->name = NULL;
4447
4448    FileTail_one = FileList_one;
4449    FileTail_one->next = NULL;
4450    wd_DEBUG("get_server_exist path:%s\n",path);
4451    status=api_metadata_one(path,dofile);
4452    if(status == -1)
4453    {
4454        free_CloudFile_item(FileList_one);
4455        free(path);
4456        return NULL;
4457    }
4458    char *temp_name_g = my_str_malloc(strlen(temp_name)+1);
4459    sprintf(temp_name_g,"%s",temp_name);
4460
4461    CloudFile *de_filecurrent;
4462    de_filecurrent=FileList_one->next;
4463    while(de_filecurrent != NULL)
4464    {
4465        if(de_filecurrent->href != NULL)
4466        {
4467            wd_DEBUG("de_filecurrent->href:%s\n",de_filecurrent->href);
4468            wd_DEBUG("temp_name           :%s\n",temp_name);
4469            char *tmp_href = my_str_malloc(strlen(de_filecurrent->href)+1);
4470            strcpy(tmp_href,de_filecurrent->href);
4471            if(strcmp(de_filecurrent->href,temp_name) != 0 && (status=strcmp(strlwr(tmp_href),strlwr(temp_name_g)))==0)
4472            {
4473                char *conflict_name = my_str_malloc(strlen(de_filecurrent->href)+1);
4474                strcpy(conflict_name,de_filecurrent->href);
4475                free_CloudFile_item(FileList_one);
4476                free(path);
4477                free(temp_name_g);
4478                free(tmp_href);
4479                return conflict_name;
4480            }
4481            else
4482                free(tmp_href);
4483
4484        }
4485        de_filecurrent = de_filecurrent->next;
4486    }
4487//    free_CloudFile_item(FileList_one);
4488//    return 0;
4489
4490}
4491
4492#if 0
4493char *change_server_same_name(char *fullname,int index){
4494
4495    int i = 1;
4496    int exist;
4497    char *filename = NULL;
4498    char *temp_name = NULL;
4499    //char *temp_suffix = ".asus.td";
4500    int len = 0;
4501    char *path;
4502    char newfilename[512];
4503    int exit = 1;
4504
4505    char *fullname_tmp = NULL;
4506    fullname_tmp = my_str_malloc(strlen(fullname)+1);
4507    sprintf(fullname_tmp,"%s",fullname);
4508
4509
4510    filename = parse_name_from_path(fullname_tmp);
4511    len = strlen(filename);
4512    //len = 6;
4513
4514    wd_DEBUG("filename len is %d\n",len);
4515
4516    path = my_str_malloc((size_t)(strlen(fullname)-len+1));
4517
4518    wd_DEBUG("fullname = %s\n",fullname);
4519
4520    snprintf(path,strlen(fullname)-len+1,"%s",fullname);
4521
4522    wd_DEBUG("path = %s\n",path);
4523
4524
4525    free(fullname_tmp);
4526
4527    while(exit)
4528    {
4529        int n = i;
4530        int j = 0;
4531        while((n=(n/10)))
4532        {
4533            j++;
4534        }
4535        memset(newfilename,'\0',sizeof(newfilename));
4536        snprintf(newfilename,252-j,"%s",filename);
4537        sprintf(newfilename,"%s(%d)",newfilename,i);
4538
4539        wd_DEBUG("newfilename = %s\n",newfilename);
4540
4541        i++;
4542
4543        temp_name = my_str_malloc((size_t)(strlen(path)+strlen(newfilename)+1));
4544        sprintf(temp_name,"%s%s",path,newfilename);
4545
4546        //char *serverpath;
4547        //serverpath = localpath_to_serverpath(temp_name);
4548
4549        //do{
4550
4551        wd_DEBUG("temp_name = %s\n",temp_name);
4552
4553
4554        exist = is_server_exist(path,temp_name,index);
4555        //}while(exist == -2);
4556
4557        if(exist)
4558        {
4559            free(temp_name);
4560        }
4561        else
4562        {
4563            exit = 0;
4564        }
4565
4566    }
4567
4568    free(path);
4569    free(filename);
4570    return temp_name;
4571
4572}
4573#endif
4574
4575char *change_server_same_name(char *fullname,int index)
4576{
4577    char *newname;
4578    char *tmp_name = malloc(strlen(fullname)+1);
4579    memset(tmp_name,0,strlen(fullname)+1);
4580    sprintf(tmp_name,"%s",fullname);
4581    int is_folder = test_if_dir(fullname);
4582    int exist;
4583    int len;
4584    char *filename;
4585    char *path;
4586
4587    filename = parse_name_from_path(fullname);
4588    len = strlen(filename);
4589
4590    path = my_str_malloc((size_t)(strlen(fullname)-len+1));
4591
4592    wd_DEBUG("fullname = %s\n",fullname);
4593
4594    snprintf(path,strlen(fullname)-len+1,"%s",fullname);
4595
4596    while(!exit_loop)
4597    {
4598        newname = get_confilicted_name(tmp_name,is_folder);
4599        //printf("confilicted_name=%s\n",confilicted_name);
4600        exist = is_server_exist(path,newname,index);
4601        if(exist == 1)
4602        {
4603            my_free(tmp_name);
4604            tmp_name = malloc(strlen(newname)+1);
4605            memset(tmp_name,0,strlen(newname)+1);
4606            sprintf(tmp_name,"%s",newname);
4607            my_free(newname);
4608            //have_same = 1;
4609        }
4610        else
4611            break;
4612    }
4613    my_free(path);
4614    my_free(filename);
4615    my_free(tmp_name);
4616    return newname;
4617}
4618
4619int the_same_name_compare(LocalFile *localfiletmp,CloudFile *filetmp,int index,int is_init)
4620{
4621
4622    wd_DEBUG("###########the same name compare################\n");
4623
4624    int ret=0;
4625    int newer_file_ret=0;
4626    if(asus_cfg.prule[index]->rule == 1)  //download only
4627    {
4628        newer_file_ret = newer_file(localfiletmp->path,index,is_init,1);
4629        if(newer_file_ret !=2 && newer_file_ret !=-1)
4630        {
4631            if(newer_file_ret == 0) //local file is change
4632            {
4633                //char *newname=change_local_same_name(localfiletmp->path);
4634                char *newname;
4635                char *tmp_name = malloc(strlen(localfiletmp->path)+1);
4636                memset(tmp_name,0,strlen(localfiletmp->path)+1);
4637                sprintf(tmp_name,"%s",localfiletmp->path);
4638
4639                while(!exit_loop)
4640                {
4641                    newname = get_confilicted_name(tmp_name,0);
4642                    //printf("confilicted_name=%s\n",confilicted_name);
4643                    if(access(newname,F_OK) == 0)
4644                    {
4645                        my_free(tmp_name);
4646                        tmp_name = malloc(strlen(newname)+1);
4647                        memset(tmp_name,0,strlen(newname)+1);
4648                        sprintf(tmp_name,"%s",newname);
4649                        my_free(newname);
4650                        //have_same = 1;
4651                    }
4652                    else
4653                        break;
4654                }
4655                my_free(tmp_name);
4656
4657                rename(localfiletmp->path,newname);
4658               char *err_msg = write_error_message("%s is download from server,%s is local file and rename from %s",localfiletmp->path,newname,localfiletmp->path);
4659                write_trans_excep_log(localfiletmp->path,3,err_msg);
4660                free(err_msg);
4661                //write_conflict_log(localfiletmp->path,newname,index);
4662                free(newname);
4663            }
4664
4665            action_item *item;
4666            item = get_action_item("download",filetmp->href,g_pSyncList[index]->unfinished_list,index);
4667
4668            if(is_local_space_enough(filetmp,index))
4669            {
4670                if(wait_handle_socket(index))
4671                {
4672                    return HAVE_LOCAL_SOCKET;
4673                }
4674                add_action_item("createfile",localfiletmp->path,g_pSyncList[index]->server_action_list);
4675                ret=api_download(localfiletmp->path,filetmp->href,index);
4676                if(ret == 0)
4677                {
4678                    time_t mtime=api_getmtime(filetmp->href,dofile);
4679                    if(mtime != -1 || mtime != -2)
4680                        ChangeFile_modtime(localfiletmp->path,mtime);
4681                    else
4682                    {
4683
4684                        wd_DEBUG("ChangeFile_modtime failed!\n");
4685
4686                    }
4687                    if(item != NULL)
4688                    {
4689                        del_action_item("download",filetmp->href,g_pSyncList[index]->unfinished_list);
4690                    }
4691                }
4692                else
4693                {
4694                    return ret;
4695                }
4696
4697            }
4698            else
4699            {
4700
4701                write_log(S_ERROR,"local space is not enough!","",index);
4702                if(item == NULL)
4703                {
4704                    add_action_item("download",filetmp->href,g_pSyncList[index]->unfinished_list);
4705                }
4706
4707
4708            }
4709        }
4710    }
4711    else if(asus_cfg.prule[index]->rule == 2)//upload only
4712    {
4713        newer_file_ret = newer_file(localfiletmp->path,index,is_init,0);
4714        if(newer_file_ret !=2 && newer_file_ret !=-1)
4715        {
4716            if(wait_handle_socket(index))
4717            {
4718                return HAVE_LOCAL_SOCKET;
4719            }
4720            /*
4721            char *newname;
4722            newname = change_server_same_name(filetmp->href,index);
4723            //Move(localfiletmp->path,newname,index);
4724            api_move(filetmp->href,newname,index);
4725            wd_DEBUG("newname = %s\n",newname);
4726            free(newname);
4727            */
4728            ret=upload_file(localfiletmp->path,filetmp->href,1,index);
4729            if(ret == 0 || ret == SERVER_SPACE_NOT_ENOUGH || ret == LOCAL_FILE_LOST)
4730            {
4731                if(ret == 0)
4732                {
4733                    cJSON *json = dofile(Con(TMP_R,upload_chunk_commit.txt));
4734                    time_t mtime=cJSON_printf(json,"modified");
4735                    cJSON_Delete(json);
4736                    ChangeFile_modtime(localfiletmp->path,mtime);
4737                }
4738            }
4739            else
4740                return ret;
4741
4742        }
4743    }
4744    else //sync
4745    {
4746        newer_file_ret = newer_file(localfiletmp->path,index,is_init,0);
4747
4748        if(newer_file_ret == 1)
4749        {
4750            if(is_init)
4751            {
4752                if(wait_handle_socket(index))
4753                {
4754                    return HAVE_LOCAL_SOCKET;
4755                }
4756                char *serverpath=localpath_to_serverpath(localfiletmp->path,index);
4757                /*third param flase,false=>if server file has exit ,will not be overwrite*/
4758                ret=upload_file(localfiletmp->path,serverpath,0,index);
4759                free(serverpath);
4760                if(ret == 0 || ret == SERVER_SPACE_NOT_ENOUGH || ret == LOCAL_FILE_LOST)
4761                {
4762                    if(ret == 0)
4763                    {
4764                        char *newlocalname = NULL;
4765                        cJSON *json = dofile(Con(TMP_R,upload_chunk_commit.txt));
4766                        time_t mtime=cJSON_printf(json,"modified");
4767                        cJSON_Delete(json);
4768
4769                        newlocalname=change_local_same_file(localfiletmp->path,index);
4770                        if(newlocalname)
4771                            ChangeFile_modtime(newlocalname,mtime);
4772                        free(newlocalname);
4773                    }
4774
4775                }
4776                else
4777                {
4778                    return ret;
4779                }
4780            }
4781            if(is_local_space_enough(filetmp,index))
4782            {
4783                action_item *item;
4784                item = get_action_item("download",filetmp->href,g_pSyncList[index]->unfinished_list,index);
4785                if(wait_handle_socket(index))
4786                {
4787                    return HAVE_LOCAL_SOCKET;
4788                }
4789                add_action_item("createfile",localfiletmp->path,g_pSyncList[index]->server_action_list);
4790                ret=api_download(localfiletmp->path,filetmp->href,index);
4791                if(ret == 0)
4792                {
4793                    time_t mtime=api_getmtime(filetmp->href,dofile);
4794                    if(mtime != -1 || mtime != -2)
4795                        ChangeFile_modtime(localfiletmp->path,mtime);
4796                    else
4797                    {
4798
4799                        wd_DEBUG("ChangeFile_modtime failed!\n");
4800
4801                    }
4802                    if(item != NULL)
4803                    {
4804                        del_action_item("download",filetmp->href,g_pSyncList[index]->unfinished_list);
4805                    }
4806                }
4807                else
4808                {
4809                    return ret;
4810                }
4811
4812            }
4813            else
4814            {
4815                write_log(S_ERROR,"local space is not enough!","",index);
4816                add_action_item("download",filetmp->href,g_pSyncList[index]->unfinished_list);
4817            }
4818        }
4819        else if(newer_file_ret == 0)
4820        {
4821            if(wait_handle_socket(index))
4822            {
4823                return HAVE_LOCAL_SOCKET;
4824            }
4825            ret=upload_file(localfiletmp->path,filetmp->href,1,index);
4826            if(ret == 0 || ret == SERVER_SPACE_NOT_ENOUGH || ret == LOCAL_FILE_LOST)
4827            {
4828                if(ret == 0)
4829                {
4830                    cJSON * json = dofile(Con(TMP_R,upload_chunk_commit.txt));
4831                    time_t mtime=cJSON_printf(json,"modified");
4832                    cJSON_Delete(json);
4833
4834                    ChangeFile_modtime(localfiletmp->path,mtime);
4835                }
4836            }
4837            else
4838                return ret;
4839        }
4840    }
4841    return 0;
4842}
4843int send_action(int type, char *content)
4844{
4845    if(exit_loop)
4846    {
4847        return 0;
4848    }
4849    int sockfd, numbytes;
4850    char buf[MAXDATASIZE];
4851    char str[1024];
4852    int port;
4853
4854    //if(type == 1)
4855    port = INOTIFY_PORT;
4856
4857    struct sockaddr_in their_addr; /* connector's address information */
4858
4859
4860    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
4861        perror("socket");
4862        //exit(1);
4863        return -1;
4864    }
4865
4866    bzero(&(their_addr), sizeof(their_addr)); /* zero the rest of the struct */
4867    their_addr.sin_family = AF_INET; /* host byte order */
4868    their_addr.sin_port = htons(port); /* short, network byte order */
4869    their_addr.sin_addr.s_addr = htonl(INADDR_ANY);
4870    //their_addr.sin_addr.s_addr = ((struct in_addr *)(he->h_addr))->s_addr;
4871    bzero(&(their_addr.sin_zero), sizeof(their_addr.sin_zero)); /* zero the rest of the struct */
4872    if (connect(sockfd, (struct sockaddr *)&their_addr,sizeof(struct
4873                                                              sockaddr)) == -1) {
4874        perror("connect");
4875        //exit(1);
4876        return -1;
4877    }
4878
4879    sprintf(str,"%d@%s",type,content);
4880
4881    //printf("send content is %s \n",str);
4882
4883    if (send(sockfd, str, strlen(str), 0) == -1) {
4884        perror("send");
4885        //exit(1);
4886        return -1;
4887    }
4888
4889    if ((numbytes=recv(sockfd, buf, MAXDATASIZE, 0)) == -1) {
4890        perror("recv");
4891        //exit(1);
4892        return -1;
4893    }
4894
4895    buf[numbytes] = '\0';
4896    close(sockfd);
4897
4898    wd_DEBUG("send_action finished!\n");
4899
4900    return 0;
4901}
4902void send_to_inotify(){
4903
4904    int i;
4905
4906    for(i=0;i<asus_cfg.dir_number;i++)
4907    {
4908
4909        wd_DEBUG("send_action base_path = %s\n",asus_cfg.prule[i]->path);
4910        //write_debug_log(asus_cfg.prule[i]->base_path);
4911
4912        //#ifndef NVRAM_
4913#if TOKENFILE
4914        if(g_pSyncList[i]->sync_disk_exist)
4915        {
4916            send_action(asus_cfg.type,asus_cfg.prule[i]->path);
4917            usleep(1000*10);
4918        }
4919#else
4920        send_action(asus_cfg.type,asus_cfg.prule[i]->path);
4921        usleep(1000*10);
4922#endif
4923        //#else
4924        //send_action(1,asus_cfg.prule[i]->base_path);
4925        //usleep(1000*10);
4926        //#endif
4927
4928    }
4929}
4930char *get_path_from_socket(char *cmd,int index)
4931{
4932
4933    if(!strncmp(cmd,"rmroot",6))
4934    {
4935        return NULL;
4936    }
4937
4938    char cmd_name[64]="\0";
4939    char *path;
4940    char *temp;
4941    char filename[256]="\0";
4942    char *fullname;
4943    char oldname[256]="\0",newname[256]="\0";
4944    char *oldpath;
4945    char action[64]="\0";
4946    char *cmp_name;
4947    char *mv_newpath;
4948    char *mv_oldpath;
4949    char *ch;
4950    int status;
4951
4952    ch = cmd;
4953    int i = 0;
4954    //while(*ch != '@')
4955    while(*ch != '\n')
4956    {
4957        i++;
4958        ch++;
4959    }
4960
4961    memcpy(cmd_name, cmd, i);
4962
4963    char *p = NULL;
4964    ch++;
4965    i++;
4966
4967    temp = my_str_malloc((size_t)(strlen(ch)+1));
4968
4969    strcpy(temp,ch);
4970    //p = strchr(temp,'@');
4971    p = strchr(temp,'\n');
4972
4973    path = my_str_malloc((size_t)(strlen(temp)- strlen(p)+1));
4974
4975
4976    if(p!=NULL)
4977        snprintf(path,strlen(temp)- strlen(p)+1,"%s",temp);
4978
4979    p++;
4980    if(strcmp(cmd_name, "rename") == 0)
4981    {
4982        char *p1 = NULL;
4983
4984        //p1 = strchr(p,'@');
4985        p1 = strchr(p,'\n');
4986
4987        if(p1 != NULL)
4988            strncpy(oldname,p,strlen(p)- strlen(p1));
4989
4990        p1++;
4991
4992        strcpy(newname,p1);
4993
4994        wd_DEBUG("cmd_name: [%s],path: [%s],oldname: [%s],newname: [%s]\n",cmd_name,path,oldname,newname);
4995
4996        if(newname[0] == '.' || (strstr(path,"/.")) != NULL)
4997        {
4998            free(temp);
4999            free(path);
5000            return NULL;
5001        }
5002    }
5003    else if(strcmp(cmd_name, "move") == 0)
5004    {
5005        char *p1 = NULL;
5006
5007        //p1 = strchr(p,'@');
5008        p1 = strchr(p,'\n');
5009
5010        oldpath = my_str_malloc((size_t)(strlen(p)- strlen(p1)+1));
5011
5012        if(p1 != NULL)
5013            snprintf(oldpath,strlen(p)- strlen(p1)+1,"%s",p);
5014
5015        p1++;
5016
5017        strcpy(oldname,p1);
5018
5019        wd_DEBUG("cmd_name: [%s],path: [%s],oldpath: [%s],oldname: [%s]\n",cmd_name,path,oldpath,oldname);
5020
5021
5022        if(oldname[0] == '.' || (strstr(path,"/.")) != NULL)
5023        {
5024            free(temp);
5025            free(path);
5026            free(oldpath);
5027            return NULL;
5028        }
5029    }
5030    else
5031    {
5032        strcpy(filename,p);
5033        fullname = my_str_malloc((size_t)(strlen(path)+strlen(filename)+2));
5034
5035        wd_DEBUG("cmd_name: [%s],path: [%s],filename: [%s]\n",cmd_name,path,filename);
5036
5037        if(filename[0] == '.' || (strstr(path,"/.")) != NULL)
5038        {
5039            free(temp);
5040            free(path);
5041            return NULL;
5042        }
5043    }
5044
5045    free(temp);
5046
5047    if( !strcmp(cmd_name,"rename") )
5048    {
5049        cmp_name = my_str_malloc((size_t)(strlen(path)+strlen(newname)+2));
5050        sprintf(cmp_name,"%s/%s",path,newname);
5051    }
5052    else
5053    {
5054        cmp_name = my_str_malloc((size_t)(strlen(path)+strlen(filename)+2));
5055        sprintf(cmp_name,"%s/%s",path,filename);
5056    }
5057
5058    if( strcmp(cmd_name, "createfile") == 0 )
5059    {
5060        strcpy(action,"createfile");
5061    }
5062    else if( strcmp(cmd_name, "remove") == 0  || strcmp(cmd_name, "delete") == 0)
5063    {
5064        strcpy(action,"remove");
5065    }
5066    else if( strcmp(cmd_name, "createfolder") == 0 )
5067    {
5068        strcpy(action,"createfolder");
5069    }
5070    else if( strcmp(cmd_name, "rename") == 0 )
5071    {
5072        strcpy(action,"rename");
5073    }
5074#if 1
5075    if(g_pSyncList[index]->server_action_list->next != NULL)
5076    {
5077        action_item *item;
5078
5079        item = get_action_item(action,cmp_name,g_pSyncList[index]->server_action_list,index);
5080
5081        if(item != NULL)
5082        {
5083
5084            wd_DEBUG("##### %s %s by Dropbox Server self ######\n",action,cmp_name);
5085
5086            //pthread_mutex_lock(&mutex);
5087            del_action_item(action,cmp_name,g_pSyncList[index]->server_action_list);
5088
5089            wd_DEBUG("#### del action item success!\n");
5090
5091            //pthread_mutex_unlock(&mutex);
5092            //local_sync = 0;
5093            free(path);
5094            if( strcmp(cmd_name, "rename") != 0 )
5095                free(fullname);
5096            free(cmp_name);
5097            return NULL;
5098        }
5099    }
5100#endif
5101    free(cmp_name);
5102    return path;
5103
5104}
5105void show(queue_entry_t pTemp)
5106{
5107    wd_DEBUG(">>>>>>show socketlist>>>>>>>>>>>>>\n");
5108    while(pTemp!=NULL)
5109    {
5110        wd_DEBUG(">>>>>>>>>>>>>>>>>>>>>>>>>\n");
5111        wd_DEBUG(">>>>%s\n",pTemp->cmd_name);
5112        wd_DEBUG(">>>>%s\n",pTemp->re_cmd);
5113        wd_DEBUG("\n");
5114        pTemp=pTemp->next_ptr;
5115    }
5116}
5117
5118char *search_newpath(char *href,int index)
5119{
5120    wd_DEBUG("################search_newpath###########\n");
5121    wd_DEBUG("href = %s\n",href);
5122    int flag_r = 0;
5123    queue_entry_t pTemp = g_pSyncList[index]->SocketActionList->head;
5124    while(pTemp != NULL)
5125    {
5126        if(strncmp(pTemp->cmd_name,"rename0",strlen("rename0")) == 0 ||
5127           strncmp(pTemp->cmd_name,"move0",strlen("move0")) == 0)
5128        {
5129            char cmd_name[64]="\0";
5130            char *path;
5131            char *temp;
5132            char oldname[256]="\0",newname[256]="\0";
5133            char *oldpath;
5134            char *mv_newpath;
5135            char *mv_oldpath;
5136            char *ch;
5137
5138            ch = pTemp->cmd_name;
5139            int i = 0;
5140            //while(*ch != '@')
5141            while(*ch != '\n')
5142            {
5143                i++;
5144                ch++;
5145            }
5146
5147            memcpy(cmd_name, pTemp->cmd_name, i);
5148
5149            char *p = NULL;
5150            ch++;
5151            i++;
5152
5153            temp = my_str_malloc((size_t)(strlen(ch)+1));
5154
5155            strcpy(temp,ch);
5156            //p = strchr(temp,'@');
5157            p = strchr(temp,'\n');
5158
5159            path = my_str_malloc((size_t)(strlen(temp)- strlen(p)+1));
5160
5161
5162            if(p!=NULL)
5163                snprintf(path,strlen(temp)- strlen(p)+1,"%s",temp);
5164
5165            p++;
5166            if(strcmp(cmd_name, "rename0") == 0)
5167            {
5168                char *p1 = NULL;
5169
5170                //p1 = strchr(p,'@');
5171                p1 = strchr(p,'\n');
5172
5173                if(p1 != NULL)
5174                    strncpy(oldname,p,strlen(p)- strlen(p1));
5175
5176                p1++;
5177
5178                strcpy(newname,p1);
5179
5180                //wd_DEBUG("cmd_name: [%s],path: [%s],oldname: [%s],newname: [%s]\n",cmd_name,path,oldname,newname);
5181
5182                if(newname[0] == '.' || (strstr(path,"/.")) != NULL)
5183                {
5184                    free(temp);
5185                    free(path);
5186                    pTemp=pTemp->next_ptr;
5187                    continue;
5188                }
5189            }
5190            else if(strcmp(cmd_name, "move0") == 0)
5191            {
5192                char *p1 = NULL;
5193
5194                //p1 = strchr(p,'@');
5195                p1 = strchr(p,'\n');
5196
5197                oldpath = my_str_malloc((size_t)(strlen(p)- strlen(p1)+1));
5198
5199                if(p1 != NULL)
5200                    snprintf(oldpath,strlen(p)- strlen(p1)+1,"%s",p);
5201
5202                p1++;
5203
5204                strcpy(oldname,p1);
5205
5206                //wd_DEBUG("cmd_name: [%s],path: [%s],oldpath: [%s],oldname: [%s]\n",cmd_name,path,oldpath,oldname);
5207
5208
5209                if(oldname[0] == '.' || (strstr(path,"/.")) != NULL)
5210                {
5211                    free(temp);
5212                    free(path);
5213                    pTemp=pTemp->next_ptr;
5214                    continue;
5215                }
5216            }
5217            wd_DEBUG("111\n");
5218            free(temp);
5219            wd_DEBUG("222\n");
5220            if(strcmp(cmd_name, "move0") == 0)
5221            {
5222                mv_newpath = my_str_malloc((size_t)(strlen(path)+strlen(oldname)+2));
5223                mv_oldpath = my_str_malloc((size_t)(strlen(oldpath)+strlen(oldname)+2));
5224                sprintf(mv_newpath,"%s/%s",path,oldname);
5225                sprintf(mv_oldpath,"%s/%s",oldpath,oldname);
5226                free(oldpath);
5227            }
5228            else
5229            {
5230                mv_newpath = my_str_malloc((size_t)(strlen(path)+strlen(newname)+2));
5231                mv_oldpath = my_str_malloc((size_t)(strlen(path)+strlen(oldname)+2));
5232                sprintf(mv_newpath,"%s/%s",path,newname);
5233                sprintf(mv_oldpath,"%s/%s",path,oldname);
5234            }
5235            wd_DEBUG("333\n");
5236            char *pTemp_t=(char *)malloc(sizeof(char)*(strlen(href)+1+1));
5237            char *oldpath_t=(char *)malloc(sizeof(char)*(strlen(mv_oldpath)+1+1));
5238            memset(pTemp_t,'\0',strlen(href)+1+1);
5239            memset(oldpath_t,'\0',strlen(mv_oldpath)+1+1);
5240            sprintf(pTemp_t,"%s/",href);
5241            sprintf(oldpath_t,"%s/",mv_oldpath);
5242
5243            wd_DEBUG("pTemp_t=%s ,oldpath_t=%s\n",pTemp_t ,oldpath_t);
5244            char *p_t = NULL;
5245            char *ret_p = NULL;
5246            if((p_t=strstr(pTemp_t,oldpath_t)) != NULL)
5247            {
5248                wd_DEBUG("666\n");
5249                p_t=p_t+strlen(oldpath_t);
5250                wd_DEBUG("p_t=%s\n",p_t);
5251                ret_p = (char *)malloc(sizeof(char) * (strlen(mv_newpath)+strlen(p_t) + 1 +1));
5252                memset(ret_p,'\0',strlen(mv_newpath)+strlen(p_t) + 1 +1);
5253                sprintf(ret_p,"%s/%s",mv_newpath,p_t);
5254                wd_DEBUG("ret_p = %s\n",ret_p);
5255                flag_r = 1;
5256            }
5257            wd_DEBUG("444\n");
5258            free(pTemp_t);
5259            free(oldpath_t);
5260
5261            free(path);
5262            free(mv_oldpath);
5263            free(mv_newpath);
5264            wd_DEBUG("555\n");
5265            if(1 == flag_r)
5266            {
5267                wd_DEBUG("ret_p = %s\n",ret_p);
5268                return ret_p;
5269            }
5270        }
5271        pTemp=pTemp->next_ptr;
5272    }
5273
5274    if(flag_r == 0)
5275    {
5276        return NULL;
5277    }
5278
5279}
5280
5281void set_copyfile_list(char *buf,char *oldpath,char *newpath)
5282{
5283    wd_DEBUG("************************set_copyfile_list***********************\n");
5284    int i;
5285    char *r_path;
5286    r_path = get_socket_base_path(buf);
5287    for(i=0;i<asus_cfg.dir_number;i++)
5288    {
5289        //wd_DEBUG("asus_cfg.prule[%d]->base_path:%s\n",i,asus_cfg.prule[i]->path);
5290        //wd_DEBUG("r_path                       :%s\n",r_path);
5291        if(!strcmp(r_path,asus_cfg.prule[i]->path))
5292            break;
5293    }
5294    free(r_path);
5295
5296    check_action_item("copyfile",oldpath,g_pSyncList[i]->copy_file_list,i,newpath);
5297
5298}
5299
5300char *get_socket_filename(char *cmd)
5301{
5302    char cmd_name[64]="\0";
5303    char *path;
5304    char *temp;
5305    char *ch;
5306    char *filename;
5307
5308    ch = cmd;
5309    int i = 0;
5310    //while(*ch != '@')
5311    while(*ch != '\n')
5312    {
5313        i++;
5314        ch++;
5315    }
5316
5317    memcpy(cmd_name, cmd, i);
5318
5319    char *p = NULL;
5320    ch++;
5321    i++;
5322
5323    temp = my_str_malloc((size_t)(strlen(ch)+1));
5324
5325    strcpy(temp,ch);
5326    //p = strchr(temp,'@');
5327    p = strchr(temp,'\n');
5328
5329    path = my_str_malloc((size_t)(strlen(temp)- strlen(p)+1));
5330
5331
5332    if(p!=NULL)
5333        snprintf(path,strlen(temp)- strlen(p)+1,"%s",temp);
5334
5335    p++;
5336    filename = (char *)malloc(sizeof(char)*(strlen(p)+2));
5337    memset(filename,'\0',strlen(p)+2);
5338    sprintf(filename,"%s",p);
5339    return filename;
5340}
5341
5342int get_socket_fullname(queue_entry_t pTemp,char *fullname)
5343{
5344    char *cmd = pTemp ->cmd_name;
5345    char cmd_name[64]="\0";
5346    char *path;
5347    char *temp;
5348    char oldname[256]="\0",newname[256]="\0";
5349    char *oldpath;
5350    char *mv_newpath;
5351    char *mv_oldpath;
5352    char *ch;
5353
5354    ch = cmd;
5355    int i = 0;
5356    //while(*ch != '@')
5357    while(*ch != '\n')
5358    {
5359        i++;
5360        ch++;
5361    }
5362
5363    memcpy(cmd_name, cmd, i);
5364
5365    char *p = NULL;
5366    ch++;
5367    i++;
5368
5369    temp = my_str_malloc((size_t)(strlen(ch)+1));
5370
5371    strcpy(temp,ch);
5372    //p = strchr(temp,'@');
5373    p = strchr(temp,'\n');
5374
5375    path = my_str_malloc((size_t)(strlen(temp)- strlen(p)+1));
5376
5377
5378    if(p!=NULL)
5379        snprintf(path,strlen(temp)- strlen(p)+1,"%s",temp);
5380
5381    p++;
5382    if(strncmp(cmd_name, "rename",6) == 0)
5383    {
5384        char *p1 = NULL;
5385
5386        //p1 = strchr(p,'@');
5387        p1 = strchr(p,'\n');
5388
5389        if(p1 != NULL)
5390            strncpy(oldname,p,strlen(p)- strlen(p1));
5391
5392        p1++;
5393
5394        strcpy(newname,p1);
5395
5396        //wd_DEBUG("cmd_name: [%s],path: [%s],oldname: [%s],newname: [%s]\n",cmd_name,path,oldname,newname);
5397
5398        if(newname[0] == '.' || (strstr(path,"/.")) != NULL)
5399        {
5400            free(temp);
5401            free(path);
5402            return 0;
5403        }
5404    }
5405    else if(strncmp(cmd_name, "move",4) == 0)
5406    {
5407        char *p1 = NULL;
5408
5409        //p1 = strchr(p,'@');
5410        p1 = strchr(p,'\n');
5411
5412        oldpath = my_str_malloc((size_t)(strlen(p)- strlen(p1)+1));
5413
5414        if(p1 != NULL)
5415            snprintf(oldpath,strlen(p)- strlen(p1)+1,"%s",p);
5416
5417        p1++;
5418
5419        strcpy(oldname,p1);
5420
5421        //wd_DEBUG("cmd_name: [%s],path: [%s],oldpath: [%s],oldname: [%s]\n",cmd_name,path,oldpath,oldname);
5422
5423
5424        if(oldname[0] == '.' || (strstr(path,"/.")) != NULL)
5425        {
5426            free(temp);
5427            free(path);
5428            free(oldpath);
5429            return 0;
5430        }
5431    }
5432
5433    free(temp);
5434
5435    if(strncmp(cmd_name, "move",4) == 0)
5436    {
5437        mv_newpath = my_str_malloc((size_t)(strlen(path)+strlen(oldname)+2));
5438        mv_oldpath = my_str_malloc((size_t)(strlen(oldpath)+strlen(oldname)+2));
5439        sprintf(mv_newpath,"%s/%s",path,oldname);
5440        sprintf(mv_oldpath,"%s/%s",oldpath,oldname);
5441        free(oldpath);
5442    }
5443    else
5444    {
5445        mv_newpath = my_str_malloc((size_t)(strlen(path)+strlen(newname)+2));
5446        mv_oldpath = my_str_malloc((size_t)(strlen(path)+strlen(oldname)+2));
5447        sprintf(mv_newpath,"%s/%s",path,newname);
5448        sprintf(mv_oldpath,"%s/%s",path,oldname);
5449    }
5450
5451    if(strcmp(fullname,mv_oldpath) == 0 ||strcmp(fullname,mv_newpath) == 0)
5452    {
5453        free(path);
5454        free(mv_oldpath);
5455        free(mv_newpath);
5456        return 1;
5457    }
5458    if(pTemp->re_cmd != NULL)
5459    {
5460        if(strncmp(cmd_name, "move",4) == 0)
5461        {
5462            char *p1 = my_str_malloc((size_t)(strlen(pTemp->re_cmd)+strlen(oldname)+2));
5463            sprintf(p1,"%s%s",pTemp->re_cmd,oldname);
5464            if(strcmp(fullname,p1) == 0)
5465            {
5466                free(path);
5467                free(mv_oldpath);
5468                free(mv_newpath);
5469                free(p1);
5470                return 1;
5471            }
5472            free(p1);
5473        }
5474        else
5475        {
5476            char *p1 = my_str_malloc((size_t)(strlen(pTemp->re_cmd)+strlen(oldname)+2));
5477            char *p2 = my_str_malloc((size_t)(strlen(pTemp->re_cmd)+strlen(newname)+2));
5478            sprintf(p1,"%s%s",pTemp->re_cmd,oldname);
5479            sprintf(p2,"%s%s",pTemp->re_cmd,newname);
5480            if(strcmp(fullname,p1) == 0 || strcmp(fullname,p2) == 0 )
5481            {
5482                free(path);
5483                free(mv_oldpath);
5484                free(mv_newpath);
5485                free(p1);
5486                free(p2);
5487                return 1;
5488            }
5489            free(p1);
5490            free(p2);
5491        }
5492    }
5493
5494
5495    free(path);
5496    free(mv_oldpath);
5497    free(mv_newpath);
5498    return 0;
5499
5500}
5501
5502int check_localpath_is_socket(int index,char *ParentHerf,char *Fname,char *fullname)
5503{
5504    wd_DEBUG("************************check_localpath_is_socket***********************\n");
5505    int i = index;
5506
5507    queue_entry_t pTemp = g_pSyncList[i]->SocketActionList->head;
5508    int reg = 0;// 0==>is not socket
5509    while(pTemp!=NULL)
5510    {
5511        if(strncmp(pTemp->cmd_name,"rename",6) == 0 ||strncmp(pTemp->cmd_name,"move",4) == 0)
5512        {
5513            reg=get_socket_fullname(pTemp,fullname);
5514            if(reg)
5515                return reg;
5516        }
5517        else
5518        {
5519
5520            char *local_p1 = (char *)malloc(sizeof(char)*(strlen(ParentHerf)+1+strlen(Fname)+1+1));
5521
5522            memset(local_p1,'\0',strlen(ParentHerf)+1+strlen(Fname)+1+1);
5523
5524            sprintf(local_p1,"\n%s\n%s",ParentHerf,Fname);
5525
5526            if(strstr(pTemp->cmd_name,local_p1) != NULL )
5527            {
5528                reg = 1;
5529                free(local_p1);
5530                return reg;
5531            }
5532            if(pTemp->re_cmd != NULL)
5533            {
5534                char *filename = get_socket_filename(pTemp->cmd_name);
5535                char *local_p2 = (char *)malloc(sizeof(char)*(strlen(pTemp->re_cmd)+strlen(filename)+2));
5536                memset(local_p2,'\0',strlen(pTemp->re_cmd)+strlen(filename)+2);
5537                sprintf(local_p2,"%s%s",pTemp->re_cmd,filename);
5538                free(filename);
5539
5540                if(strcmp(local_p2,fullname) == 0)
5541                {
5542                    reg = 1;
5543                    free(local_p1);
5544                    free(local_p2);
5545                    return reg;
5546                }
5547                free(local_p2);
5548            }
5549            free(local_p1);
5550        }
5551
5552        pTemp=pTemp->next_ptr;
5553    }
5554    return reg;
5555
5556    //show(g_pSyncList[i]->SocketActionList->head);
5557}
5558int check_socket_parser(char *cmd,int index,char *re_cmd,char *str_path,char *so_filename,char *sn_filename)
5559{
5560//    if(strstr(cmd,"conflict") != NULL)
5561//        return 0;
5562    if( !strncmp(cmd,"exit",4))
5563    {
5564        wd_DEBUG("exit socket\n");
5565        return 0;
5566    }
5567
5568    if(!strncmp(cmd,"rmroot",6))
5569    {
5570        g_pSyncList[index]->no_local_root = 1;
5571        return 0;
5572    }
5573
5574    char cmd_name[64]="\0";
5575    char *path;
5576    char *temp;
5577    char filename[256]="\0";
5578    char oldname[256]="\0",newname[256]="\0";
5579    char *oldpath;
5580    char *ch;
5581
5582    ch = cmd;
5583    int i = 0;
5584    //while(*ch != '@')
5585    while(*ch != '\n')
5586    {
5587        i++;
5588        ch++;
5589    }
5590
5591    memcpy(cmd_name, cmd, i);
5592
5593    char *p = NULL;
5594    ch++;
5595    i++;
5596
5597    temp = my_str_malloc((size_t)(strlen(ch)+1));
5598
5599    strcpy(temp,ch);
5600    //p = strchr(temp,'@');
5601    p = strchr(temp,'\n');
5602
5603    path = my_str_malloc((size_t)(strlen(temp)- strlen(p)+1));
5604
5605
5606    if(p!=NULL)
5607        snprintf(path,strlen(temp)- strlen(p)+1,"%s",temp);
5608
5609    p++;
5610    if(strncmp(cmd_name, "rename",strlen("rename")) == 0)
5611    {
5612        char *p1 = NULL;
5613
5614        //p1 = strchr(p,'@');
5615        p1 = strchr(p,'\n');
5616
5617        if(p1 != NULL)
5618            strncpy(oldname,p,strlen(p)- strlen(p1));
5619
5620        p1++;
5621
5622        strcpy(newname,p1);
5623
5624        wd_DEBUG("cmd_name: [%s],path: [%s],oldname: [%s],newname: [%s]\n",cmd_name,path,oldname,newname);
5625
5626        if(newname[0] == '.' || (strstr(path,"/.")) != NULL)
5627        {
5628            free(temp);
5629            free(path);
5630            return 0;
5631        }
5632    }
5633    else if(strncmp(cmd_name, "move",strlen("move")) == 0)
5634    {
5635        char *p1 = NULL;
5636
5637        //p1 = strchr(p,'@');
5638        p1 = strchr(p,'\n');
5639
5640        oldpath = my_str_malloc((size_t)(strlen(p)- strlen(p1)+1));
5641
5642        if(p1 != NULL)
5643            snprintf(oldpath,strlen(p)- strlen(p1)+1,"%s",p);
5644
5645        p1++;
5646
5647        strcpy(oldname,p1);
5648
5649        wd_DEBUG("cmd_name: [%s],path: [%s],oldpath: [%s],oldname: [%s]\n",cmd_name,path,oldpath,oldname);
5650
5651
5652        if(oldname[0] == '.' || (strstr(path,"/.")) != NULL)
5653        {
5654            free(temp);
5655            free(path);
5656            free(oldpath);
5657            return 0;
5658        }
5659    }
5660    else
5661    {
5662        strcpy(filename,p);
5663
5664        wd_DEBUG("cmd_name: [%s],path: [%s],filename: [%s]\n",cmd_name,path,filename);
5665
5666        if(filename[0] == '.' || (strstr(path,"/.")) != NULL)
5667        {
5668            free(temp);
5669            free(path);
5670            return 0;
5671        }
5672    }
5673
5674    free(temp);
5675
5676    if( strcmp(cmd_name, "createfile") == 0 || strcmp(cmd_name, "dragfile") == 0 )
5677    {}
5678    else if( strcmp(cmd_name, "modify") == 0 )
5679    {
5680        if(re_cmd)
5681        {
5682            if(strcmp(re_cmd,str_path) == 0 && strcmp(filename,so_filename)==0)
5683            {
5684                pthread_mutex_lock(&mutex_socket);
5685//                my_free(cmd);
5686//                cmd = my_str_malloc(512);
5687                memset(cmd,0,1024);
5688                sprintf(cmd,"%s%s%s%s%s",cmd_name,CMD_SPLIT,path,CMD_SPLIT,sn_filename);
5689                pthread_mutex_unlock(&mutex_socket);
5690            }
5691        }
5692        else
5693        {
5694            if(strcmp(path,str_path) == 0 && strcmp(filename,so_filename)==0)
5695            {
5696                pthread_mutex_lock(&mutex_socket);
5697//                my_free(cmd);
5698//                cmd = my_str_malloc(512);
5699                memset(cmd,0,1024);
5700                sprintf(cmd,"%s%s%s%s%s",cmd_name,CMD_SPLIT,path,CMD_SPLIT,sn_filename);
5701                pthread_mutex_unlock(&mutex_socket);
5702            }
5703        }
5704    }
5705    else if(strcmp(cmd_name, "delete") == 0  || strcmp(cmd_name, "remove") == 0)
5706    {
5707        if(strcmp(path,str_path) == 0 && strcmp(filename,so_filename)==0)
5708        {
5709            pthread_mutex_lock(&mutex_socket);
5710//            my_free(cmd);
5711//            cmd = my_str_malloc(512);
5712            memset(cmd,0,1024);
5713            sprintf(cmd,"%s%s%s%s%s",cmd_name,CMD_SPLIT,path,CMD_SPLIT,sn_filename);
5714            pthread_mutex_unlock(&mutex_socket);
5715        }
5716    }
5717    else if(strncmp(cmd_name, "move",strlen("move")) == 0 || strncmp(cmd_name, "rename",strlen("rename")) == 0)
5718    {
5719        if(strncmp(cmd_name, "rename",strlen("rename")) == 0)
5720        {
5721            if(re_cmd)
5722            {
5723                if(strcmp(re_cmd,str_path) == 0 && strcmp(oldname,so_filename)==0)
5724                {
5725                    pthread_mutex_lock(&mutex_socket);
5726//                    my_free(cmd);
5727//                    cmd = my_str_malloc(512);
5728                    memset(cmd,0,1024);
5729                    sprintf(cmd,"%s%s%s%s%s%s%s",cmd_name,CMD_SPLIT,path,CMD_SPLIT,sn_filename,CMD_SPLIT,newname);
5730                    pthread_mutex_unlock(&mutex_socket);
5731                }
5732            }
5733            else
5734            {
5735                if(strcmp(path,str_path) == 0 && strcmp(oldname,so_filename)==0)
5736                {
5737                    pthread_mutex_lock(&mutex_socket);
5738                    //my_free(cmd);
5739                    //cmd = my_str_malloc(512);
5740                    memset(cmd,0,1024);
5741                    sprintf(cmd,"%s%s%s%s%s%s%s",cmd_name,CMD_SPLIT,path,CMD_SPLIT,sn_filename,CMD_SPLIT,newname);
5742                    //printf("cmd=%s\n",cmd);
5743                    pthread_mutex_unlock(&mutex_socket);
5744                }
5745            }
5746        }
5747        else
5748        {
5749            if(re_cmd)
5750            {
5751                if(strcmp(re_cmd,str_path) == 0 && strcmp(oldname,so_filename)==0)
5752                {
5753                    pthread_mutex_lock(&mutex_socket);
5754//                    my_free(cmd);
5755//                    cmd = my_str_malloc(512);
5756                    memset(cmd,0,1024);
5757                    sprintf(cmd,"%s%s%s%s%s%s%s",cmd_name,CMD_SPLIT,path,CMD_SPLIT,oldpath,CMD_SPLIT,sn_filename);
5758                    pthread_mutex_unlock(&mutex_socket);
5759                }
5760            }
5761            else
5762            {
5763                if(strcmp(oldpath,str_path) == 0 && strcmp(oldname,so_filename)==0)
5764                {
5765                    pthread_mutex_lock(&mutex_socket);
5766//                    my_free(cmd);
5767//                    cmd = my_str_malloc(512);
5768                    memset(cmd,0,1024);
5769                    sprintf(cmd,"%s%s%s%s%s%s%s",cmd_name,CMD_SPLIT,path,CMD_SPLIT,oldpath,CMD_SPLIT,sn_filename);
5770                    pthread_mutex_unlock(&mutex_socket);
5771                }
5772            }
5773            my_free(oldpath);
5774        }
5775    }
5776    else if( strcmp(cmd_name,"dragfolder") == 0)
5777    {}
5778    else if(strcmp(cmd_name, "createfolder") == 0)
5779    {}
5780    free(path);
5781    return 0;
5782
5783}
5784void updata_socket_list(char *temp_name,char *new_name,int i)
5785{
5786    char *path;
5787    char *old_filename;
5788    char *p = strrchr(temp_name,'/');
5789    path = my_str_malloc(strlen(temp_name)-strlen(p)+1);
5790    snprintf(path,strlen(temp_name)-strlen(p)+1,"%s",temp_name);
5791    p++;
5792    old_filename = my_str_malloc(strlen(p)+1);
5793    sprintf(old_filename,"%s",p);
5794
5795    p = NULL;
5796    char *new_filename;
5797    p = strrchr(new_name,'/');
5798    p++;
5799    new_filename = my_str_malloc(strlen(p)+1);
5800    sprintf(new_filename,"%s",p);
5801
5802    wd_DEBUG("*****************updata_socket_list***************\n");
5803    queue_entry_t pTemp = g_pSyncList[i]->SocketActionList->head->next_ptr;//head is current socket,updata from next begin
5804    while(pTemp!=NULL)
5805    {
5806        check_socket_parser(pTemp->cmd_name,i,pTemp->re_cmd,path,old_filename,new_filename);
5807        pTemp = pTemp->next_ptr;
5808    }
5809    my_free(path);
5810    my_free(old_filename);
5811    my_free(new_filename);
5812
5813    show(g_pSyncList[i]->SocketActionList->head);
5814}
5815
5816void set_re_cmd(char *buf,char *oldpath,char *newpath)
5817{
5818    wd_DEBUG("************************set_re_cmd***********************\n");
5819    int i;
5820    char *r_path;
5821    r_path = get_socket_base_path(buf);
5822    for(i=0;i<asus_cfg.dir_number;i++)
5823    {
5824        //wd_DEBUG("asus_cfg.prule[%d]->base_path:%s\n",i,asus_cfg.prule[i]->path);
5825        //wd_DEBUG("r_path                       :%s\n",r_path);
5826        if(!strcmp(r_path,asus_cfg.prule[i]->path))
5827            break;
5828    }
5829    free(r_path);
5830
5831    queue_entry_t pTemp = g_pSyncList[i]->SocketActionList->head;
5832
5833    while(pTemp!=NULL)
5834    {
5835//        if(strncmp(pTemp->cmd_name,"rename0",strlen("rename0")) != 0 &&
5836//           strncmp(pTemp->cmd_name,"move0",strlen("move0")) != 0)
5837//        {
5838            char *socket_path=get_path_from_socket(pTemp->cmd_name,i);
5839            wd_DEBUG("path:%s\n",socket_path);
5840            wd_DEBUG("path:%s\n",oldpath);
5841            char *pTemp_t=(char *)malloc(sizeof(char)*(strlen(socket_path)+1+1));
5842            char *oldpath_t=(char *)malloc(sizeof(char)*(strlen(oldpath)+1+1));
5843            memset(pTemp_t,'\0',strlen(socket_path)+1+1);
5844            memset(oldpath_t,'\0',strlen(oldpath)+1+1);
5845            sprintf(pTemp_t,"%s/",socket_path);
5846            sprintf(oldpath_t,"%s/",oldpath);
5847            char *p_t=NULL;
5848            if(socket_path != NULL)
5849            {
5850                if(pTemp->re_cmd == NULL)
5851                {
5852                    //if((p_t=strstr(pTemp->cmd_name,oldpath)) != NULL)
5853                    if((p_t=strstr(pTemp_t,oldpath_t)) != NULL)
5854                    {
5855                        if(strlen(oldpath)<strlen(socket_path))
5856                        {
5857                            p_t=p_t+strlen(oldpath);
5858                            pTemp->re_cmd = (char *)malloc(sizeof(char) * (strlen(newpath)+strlen(p_t) + 1));
5859                            memset(pTemp->re_cmd,'\0',strlen(newpath)+strlen(p_t) + 1);
5860                            sprintf(pTemp->re_cmd,"%s%s",newpath,p_t);
5861                        }
5862                        else
5863                        {
5864                            pTemp->re_cmd = (char *)malloc(sizeof(char) * (strlen(newpath) + 1));
5865                            sprintf(pTemp->re_cmd,"%s/",newpath);
5866                        }
5867                    }
5868                }
5869                else
5870                {
5871                    //if(strstr(pTemp->re_cmd,oldpath) != NULL)
5872                    if((p_t=strstr(pTemp->re_cmd,oldpath_t)) != NULL)
5873                    {
5874                        if(strlen(oldpath_t)<strlen(pTemp->re_cmd))
5875                        {
5876                            p_t+=strlen(oldpath);
5877                            char *p_tt=(char *)malloc(sizeof(char)*(strlen(p_t)+1));
5878                            memset(p_tt,'\0',strlen(p_t)+1);
5879                            sprintf(p_tt,"%s",p_t);
5880                            free(pTemp->re_cmd);
5881                            pTemp->re_cmd = (char *)malloc(sizeof(char) * (strlen(newpath)+strlen(p_tt) + 1));
5882                            memset(pTemp->re_cmd,'\0',strlen(newpath)+strlen(p_tt) + 1);
5883                            sprintf(pTemp->re_cmd,"%s%s",newpath,p_tt);
5884                            free(p_tt);
5885                        }
5886                        else
5887                        {
5888                            free(pTemp->re_cmd);
5889                            pTemp->re_cmd = (char *)malloc(sizeof(char) * (strlen(newpath) + 1));
5890                            sprintf(pTemp->re_cmd,"%s/",newpath);
5891                        }
5892                    }
5893                }
5894                free(socket_path);
5895            }
5896            free(pTemp_t);
5897            free(oldpath_t);
5898//        }
5899
5900        pTemp=pTemp->next_ptr;
5901    }
5902
5903    show(g_pSyncList[i]->SocketActionList->head);
5904}
5905
5906int change_socklist_re_cmd(char *cmd)
5907{
5908    char cmd_name[64]="\0";
5909    char *path;
5910    char *temp;
5911    char oldname[256]="\0",newname[256]="\0";
5912    char *oldpath;
5913    char *mv_newpath;
5914    char *mv_oldpath;
5915    char *ch;
5916
5917    ch = cmd;
5918    int i = 0;
5919    //while(*ch != '@')
5920    while(*ch != '\n')
5921    {
5922        i++;
5923        ch++;
5924    }
5925
5926    memcpy(cmd_name, cmd, i);
5927
5928    char *p = NULL;
5929    ch++;
5930    i++;
5931
5932    temp = my_str_malloc((size_t)(strlen(ch)+1));
5933
5934    strcpy(temp,ch);
5935    //p = strchr(temp,'@');
5936    p = strchr(temp,'\n');
5937
5938    path = my_str_malloc((size_t)(strlen(temp)- strlen(p)+1));
5939
5940
5941    if(p!=NULL)
5942        snprintf(path,strlen(temp)- strlen(p)+1,"%s",temp);
5943
5944    p++;
5945    if(strcmp(cmd_name, "rename0") == 0)
5946    {
5947        char *p1 = NULL;
5948
5949        //p1 = strchr(p,'@');
5950        p1 = strchr(p,'\n');
5951
5952        if(p1 != NULL)
5953            strncpy(oldname,p,strlen(p)- strlen(p1));
5954
5955        p1++;
5956
5957        strcpy(newname,p1);
5958
5959        //wd_DEBUG("cmd_name: [%s],path: [%s],oldname: [%s],newname: [%s]\n",cmd_name,path,oldname,newname);
5960
5961        if(newname[0] == '.' || (strstr(path,"/.")) != NULL)
5962        {
5963            free(temp);
5964            free(path);
5965            return 0;
5966        }
5967    }
5968    else if(strcmp(cmd_name, "move0") == 0)
5969    {
5970        char *p1 = NULL;
5971
5972        //p1 = strchr(p,'@');
5973        p1 = strchr(p,'\n');
5974
5975        oldpath = my_str_malloc((size_t)(strlen(p)- strlen(p1)+1));
5976
5977        if(p1 != NULL)
5978            snprintf(oldpath,strlen(p)- strlen(p1)+1,"%s",p);
5979
5980        p1++;
5981
5982        strcpy(oldname,p1);
5983
5984        //wd_DEBUG("cmd_name: [%s],path: [%s],oldpath: [%s],oldname: [%s]\n",cmd_name,path,oldpath,oldname);
5985
5986
5987        if(oldname[0] == '.' || (strstr(path,"/.")) != NULL)
5988        {
5989            free(temp);
5990            free(path);
5991            free(oldpath);
5992            return 0;
5993        }
5994    }
5995
5996    free(temp);
5997
5998    if(strcmp(cmd_name, "move0") == 0)
5999    {
6000        mv_newpath = my_str_malloc((size_t)(strlen(path)+strlen(oldname)+2));
6001        mv_oldpath = my_str_malloc((size_t)(strlen(oldpath)+strlen(oldname)+2));
6002        sprintf(mv_newpath,"%s/%s",path,oldname);
6003        sprintf(mv_oldpath,"%s/%s",oldpath,oldname);
6004        free(oldpath);
6005    }
6006    else
6007    {
6008        mv_newpath = my_str_malloc((size_t)(strlen(path)+strlen(newname)+2));
6009        mv_oldpath = my_str_malloc((size_t)(strlen(path)+strlen(oldname)+2));
6010        sprintf(mv_newpath,"%s/%s",path,newname);
6011        sprintf(mv_oldpath,"%s/%s",path,oldname);
6012    }
6013
6014    pthread_mutex_lock(&mutex_socket);
6015    set_re_cmd(cmd,mv_oldpath,mv_newpath);
6016    set_copyfile_list(cmd,mv_oldpath,mv_newpath);
6017    pthread_mutex_unlock(&mutex_socket);
6018
6019    free(path);
6020    free(mv_oldpath);
6021    free(mv_newpath);
6022    return 0;
6023
6024}
6025
6026void *SyncLocal()
6027{
6028    //printf("it is go to SyncLocal\n");
6029
6030    int sockfd, new_fd; /* listen on sock_fd, new connection on new_fd*/
6031    int numbytes;
6032    char buf[MAXDATASIZE];
6033    int yes = 1;
6034    int ret;
6035
6036    fd_set read_fds;
6037    fd_set master;
6038    int fdmax;
6039    struct timeval timeout;
6040
6041    FD_ZERO(&read_fds);
6042    FD_ZERO(&master);
6043
6044    struct sockaddr_in my_addr; /* my address information */
6045    struct sockaddr_in their_addr; /* connector's address information */
6046    int sin_size;
6047
6048    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
6049        perror("socket");
6050        exit(1);
6051    }
6052
6053    if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1)
6054    {
6055        perror("Server-setsockopt() error lol!");
6056        exit(1);
6057    }
6058
6059    my_addr.sin_family = AF_INET; /* host byte order */
6060    my_addr.sin_port = htons(MYPORT); /* short, network byte order */
6061    my_addr.sin_addr.s_addr = INADDR_ANY; /* auto-fill with my IP */
6062    bzero(&(my_addr.sin_zero), sizeof(my_addr.sin_zero)); /* zero the rest of the struct */
6063
6064    if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct
6065                                                         sockaddr))== -1) {
6066        perror("bind");
6067        exit(1);
6068    }
6069    if (listen(sockfd, BACKLOG) == -1) {
6070        perror("listen");
6071        exit(1);
6072    }
6073    sin_size = sizeof(struct sockaddr_in);
6074
6075    FD_SET(sockfd,&master);
6076    fdmax = sockfd;
6077
6078    while(!exit_loop)
6079    { /* main accept() loop */
6080
6081        timeout.tv_sec = 0;
6082        timeout.tv_usec = 100;
6083
6084        read_fds = master;
6085
6086        ret = select(fdmax+1,&read_fds,NULL,NULL,&timeout);
6087
6088        switch (ret)
6089        {
6090        case 0:
6091            //printf("No data in ten seconds\n");
6092            continue;
6093            break;
6094        case -1:
6095            perror("select");
6096            continue;
6097            break;
6098        default:
6099            if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, \
6100                                 &sin_size)) == -1) {
6101                perror("accept");
6102                continue;
6103            }
6104            memset(buf, 0, sizeof(buf));
6105
6106            if ((numbytes=recv(new_fd, buf, MAXDATASIZE, 0)) == -1) {
6107                perror("recv");
6108                exit(1);
6109            }
6110
6111            if(buf[strlen(buf)] == '\n')
6112            {
6113                buf[strlen(buf)] = '\0';
6114            }
6115            wd_DEBUG("socket buf = %s\n",buf);
6116            close(new_fd);
6117
6118            //if(sync_down == 1)
6119            //{
6120#ifdef RENAME_F
6121            //rename0 or move0 is the folder not file
6122            if(strncmp(buf,"rename0",strlen("rename0")) == 0 || strncmp(buf,"move0",strlen("move0")) == 0)
6123            {
6124                change_socklist_re_cmd(buf);
6125            }
6126#endif
6127#if 1
6128            pthread_mutex_lock(&mutex_socket);
6129            add_socket_item(buf);
6130            pthread_mutex_unlock(&mutex_socket);
6131#endif
6132        }
6133
6134    }
6135    close(sockfd);
6136
6137    wd_DEBUG("stop dropbox local sync\n");
6138
6139    //stop_down = 1;
6140
6141}
6142int add_socket_item(char *buf){
6143
6144    int i;
6145    //local_sync = 1;
6146    char *r_path;
6147    r_path = get_socket_base_path(buf);
6148    for(i=0;i<asus_cfg.dir_number;i++)
6149    {
6150        //wd_DEBUG("asus_cfg.prule[%d]->base_path:%s\n",i,asus_cfg.prule[i]->path);
6151        //wd_DEBUG("r_path                       :%s\n",r_path);
6152        if(!strcmp(r_path,asus_cfg.prule[i]->path))
6153            break;
6154    }
6155
6156    wd_DEBUG("add_socket_item rule:%d\n",i);
6157    free(r_path);
6158    pthread_mutex_lock(&mutex_receve_socket);
6159    //receve_socket = 1;
6160    g_pSyncList[i]->receve_socket = 1;
6161    pthread_mutex_unlock(&mutex_receve_socket);
6162
6163#if MEM_POOL_ENABLE
6164    SocketActionTmp = mem_alloc(16);
6165#else
6166    SocketActionTmp = malloc (sizeof (struct queue_entry));
6167#endif
6168
6169    //SocketActionTmp = malloc (sizeof (struct queue_entry));
6170    memset(SocketActionTmp,0,sizeof(struct queue_entry));
6171    int len = strlen(buf)+1;
6172#if MEM_POOL_ENABLE
6173    SocketActionTmp->cmd_name = mem_alloc(len);
6174#else
6175    SocketActionTmp->cmd_name = (char *)calloc(len,sizeof(char));
6176#endif
6177    sprintf(SocketActionTmp->cmd_name,"%s",buf);
6178    SocketActionTmp->re_cmd = NULL;
6179    SocketActionTmp->is_first = 0;
6180    queue_enqueue(SocketActionTmp,g_pSyncList[i]->SocketActionList);
6181
6182    wd_DEBUG("SocketActionTmp->cmd_name = %s\n",SocketActionTmp->cmd_name);
6183    return 0;
6184}
6185char *get_socket_base_path(char *cmd){
6186
6187    //printf("get_socket_base_path cmd : %s\n",cmd);
6188
6189    char *temp = NULL;
6190    char *temp1 = NULL;
6191    char path[1024];
6192    char *root_path = NULL;
6193
6194    if(!strncmp(cmd,"rmroot",6))
6195    {
6196        temp = strchr(cmd,'/');
6197        root_path = my_str_malloc(512);
6198        sprintf(root_path,"%s",temp);
6199    }
6200    else
6201    {
6202        temp = strchr(cmd,'/');
6203        //temp1 = strchr(temp,'@');
6204        temp1 = strchr(temp,'\n');
6205        memset(path,0,sizeof(path));
6206        strncpy(path,temp,strlen(temp)-strlen(temp1));
6207
6208        //printf("get_socket_base_path path = %s\n",path);
6209
6210        root_path = my_str_malloc(512);
6211        if(strncmp(path,"/tmp",4) ==0 )
6212        {
6213            temp = my_nstrchr('/',path,5);
6214        }
6215        else
6216        {
6217            temp = my_nstrchr('/',path,4);
6218        }
6219        if(temp == NULL)
6220        {
6221            sprintf(root_path,"%s",path);
6222        }
6223        else
6224        {
6225            snprintf(root_path,strlen(path)-strlen(temp)+1,"%s",path);
6226        }
6227    }
6228    //printf("get_socket_base_path root_path = %s\n",root_path);
6229    return root_path;
6230}
6231void run()
6232{
6233
6234    int create_thid1 = 0;
6235    int create_thid2 = 0;
6236    int create_thid3 = 0;
6237    int need_server_thid = 0;
6238
6239
6240    create_sync_list();
6241    send_to_inotify();
6242
6243    if(exit_loop == 0)
6244    {
6245        if( pthread_create(&newthid2,NULL,(void *)SyncLocal,NULL) != 0)
6246        {
6247            wd_DEBUG("thread creation failder\n");
6248            exit(1);
6249        }
6250        create_thid2 = 1;
6251    }
6252    //pthread_join(newthid2,NULL);
6253#if 1
6254    if(exit_loop == 0)
6255    {
6256
6257        wd_DEBUG("create newthid3\n");
6258        //write_debug_log("create newthid3");
6259
6260        if( pthread_create(&newthid3,NULL,(void *)Socket_Parser,NULL) != 0)
6261        {
6262            wd_DEBUG("thread creation failder\n");
6263            exit(1);
6264        }
6265        create_thid3 = 1;
6266        usleep(1000*500);
6267
6268    }
6269
6270#if 1
6271//    if(auth_ok)
6272//    {
6273        sync_initial();
6274//    }
6275#endif
6276
6277    finished_initial=1;
6278//    need_server_thid = get_create_threads_state();
6279
6280//    if(need_server_thid && exit_loop == 0)
6281//    {
6282//        if( pthread_create(&newthid1,NULL,(void *)SyncServer,NULL) != 0)
6283//        {
6284//            wd_DEBUG("thread creation failder\n");
6285//            exit(1);
6286//        }
6287//        create_thid1 = 1;
6288//        usleep(1000*500);
6289//    }
6290//    else
6291//    {
6292//        server_sync = 0;
6293//    }
6294
6295    /*
6296     fix when socket_parse run sync_initial_again ,local send socket,the process will sleep
6297    */
6298
6299    if(exit_loop == 0)
6300    {
6301        if( pthread_create(&newthid1,NULL,(void *)SyncServer,NULL) != 0)
6302        {
6303            wd_DEBUG("thread creation failder\n");
6304            exit(1);
6305        }
6306        create_thid1 = 1;
6307        usleep(1000*500);
6308    }
6309
6310    if(create_thid1)
6311        pthread_join(newthid1,NULL);
6312    if(create_thid3)
6313        pthread_join(newthid3,NULL);
6314    if(create_thid2)
6315        pthread_join(newthid2,NULL);
6316
6317    usleep(1000);
6318    clean_up();
6319#if TOKENFILE
6320    if(stop_progress != 1)
6321    {
6322        wd_DEBUG("run again!\n");
6323
6324
6325        //#ifndef NVRAM_
6326        while(disk_change)
6327        {
6328            //write_debug_log("while disk_change");
6329            disk_change = 0;
6330            sync_disk_removed = check_sync_disk_removed();
6331
6332            if(sync_disk_removed == 2)
6333            {
6334                wd_DEBUG("sync path is change\n");
6335            }
6336            else if(sync_disk_removed == 1)
6337            {
6338                wd_DEBUG("sync disk is unmount\n");
6339            }
6340            else if(sync_disk_removed == 0)
6341            {
6342                wd_DEBUG("sync disk exists\n");
6343            }
6344        }
6345        //#endif
6346
6347        exit_loop = 0;
6348        //read_config();
6349        run();
6350    }
6351#endif
6352#endif
6353}
6354
6355void clean_up()
6356{
6357
6358    wd_DEBUG("enter clean up\n");
6359
6360    int i;
6361
6362
6363    for(i=0;i<asus_cfg.dir_number;i++)
6364    {
6365        queue_destroy(g_pSyncList[i]->SocketActionList);
6366
6367        //printf("the pointer g_pSyncList[i]->ServerRootNode = %p\n",g_pSyncList[i]->ServerRootNode);
6368        if(g_pSyncList[i]->ServerRootNode == g_pSyncList[i]->OldServerRootNode)
6369        {
6370
6371            wd_DEBUG("the same Pointer!\n");
6372
6373            if(g_pSyncList[i]->ServerRootNode != NULL)
6374                free_server_tree(g_pSyncList[i]->ServerRootNode);
6375        }
6376        else
6377        {
6378            if(g_pSyncList[i]->ServerRootNode != NULL)
6379                free_server_tree(g_pSyncList[i]->ServerRootNode);
6380
6381            wd_DEBUG("clean %d ServerRootNode success!\n",i);
6382
6383            if(g_pSyncList[i]->OldServerRootNode != NULL)
6384                free_server_tree(g_pSyncList[i]->OldServerRootNode);
6385
6386            wd_DEBUG("clean %d OldServerRootNode success!\n",i);
6387
6388        }
6389
6390        free_action_item(g_pSyncList[i]->server_action_list);
6391        free_action_item(g_pSyncList[i]->unfinished_list);
6392        free_action_item(g_pSyncList[i]->copy_file_list);
6393        free_action_item(g_pSyncList[i]->up_space_not_enough_list);
6394
6395        if(asus_cfg.prule[i]->rule == 1)
6396        {
6397            free_action_item(g_pSyncList[i]->download_only_socket_head);
6398        }
6399        free(g_pSyncList[i]);
6400        //printf("clean %d up_space_not_enough_list success!\n",i);
6401
6402    }
6403    free(g_pSyncList);
6404
6405#if MEM_POOL_ENABLE
6406    mem_pool_destroy();
6407#endif
6408
6409    wd_DEBUG("clean up end !!!\n");
6410
6411}
6412
6413void *SyncServer()
6414{
6415    struct timeval now;
6416    struct timespec outtime;
6417
6418    int status;
6419    int i;
6420    while( !exit_loop )
6421    {
6422
6423        wd_DEBUG("***************SyncServer start**************\n");
6424
6425        for(i=0;i<asus_cfg.dir_number;i++)
6426        {
6427            status=0;
6428
6429            //wd_DEBUG("the %d SyncServer\n",i);
6430
6431            while (local_sync == 1 && exit_loop == 0){
6432                //printf("local_sync = %d\n",local_sync);
6433                //sleep(2);
6434                usleep(1000*10);
6435                //server_sync = 0;
6436            }
6437            server_sync = 1;
6438
6439            if(exit_loop)
6440                break;
6441#if TOKENFILE
6442            if(disk_change)
6443            {
6444                //disk_change = 0;
6445                check_disk_change();
6446            }
6447            if(g_pSyncList[i]->sync_disk_exist == 0)
6448            {
6449                write_log(S_ERROR,"Sync disk unplug!","",i);
6450                continue;
6451            }
6452
6453#endif
6454            if(g_pSyncList[i]->no_local_root)
6455            {
6456                my_mkdir_r(asus_cfg.prule[i]->path);   //have mountpath
6457                send_action(asus_cfg.type,asus_cfg.prule[i]->path);
6458                usleep(1000*10);
6459                g_pSyncList[i]->no_local_root = 0;
6460                g_pSyncList[i]->init_completed = 0;
6461            }
6462
6463            status = do_unfinished(i);
6464
6465            if( !g_pSyncList[i]->init_completed )
6466                status = sync_initial();
6467
6468            if(status != 0)
6469                continue;
6470
6471            if(asus_cfg.prule[i]->rule == 2)
6472            {
6473                //write_log(S_SYNC,"","",i);
6474                continue;
6475            }
6476
6477            if(exit_loop == 0)
6478            {
6479                int get_serlist_fail_time = 0;
6480                do
6481                {
6482                    g_pSyncList[i]->ServerRootNode = create_server_treeroot();
6483#ifdef MULTI_PATH
6484                    status = browse_to_tree(asus_cfg.prule[i]->rooturl,g_pSyncList[i]->ServerRootNode);
6485#else
6486                    status = browse_to_tree("/",g_pSyncList[i]->ServerRootNode);
6487#endif
6488#ifdef __DEBUG__
6489                    SearchServerTree(g_pSyncList[i]->ServerRootNode);
6490#endif
6491                    /*
6492                for(i=0;i<asus_cfg.dir_number;i++)
6493                {
6494                    SearchServerTree(g_pSyncList[i]->ServerRootNode);
6495                    free_server_tree(g_pSyncList[i]->ServerRootNode);
6496                }
6497                */
6498                    if(status != 0)
6499                    {
6500                        wd_DEBUG("get ServerList ERROR! \n");
6501                        get_serlist_fail_time ++;
6502                        free_server_tree(g_pSyncList[i]->ServerRootNode);
6503                        g_pSyncList[i]->ServerRootNode = NULL;
6504                    }
6505
6506
6507                }while(status!=0 && get_serlist_fail_time < 5 && exit_loop == 0 && g_pSyncList[i]->receve_socket == 0);
6508                if (status != 0)
6509                {
6510
6511                    //wd_DEBUG("get ServerList ERROR! \n");
6512
6513                    /*auth again:
6514                        for the token not work!
6515                    */
6516#ifdef OAuth1
6517                    if(g_pSyncList[i]->receve_socket == 0)
6518                    {
6519                        if(exit_loop == 0)
6520                            do_auth();
6521                    }
6522#endif
6523                    /*for get serverlist fail,then mem will updata*/
6524                    //free_server_tree(g_pSyncList[i]->ServerRootNode);
6525                    //g_pSyncList[i]->ServerRootNode = NULL;
6526
6527                    /*first_sync:
6528                        after the initial finish,the serverlist is change so force to run server sync;
6529                        when the server sync failed,next time we must force to run server sync;
6530                    */
6531                    g_pSyncList[i]->first_sync = 1;
6532                    //sleep(2);
6533                    usleep(1000*20);
6534                    continue;
6535                    //break;
6536                }
6537
6538                if(g_pSyncList[i]->unfinished_list->next != NULL)
6539                {
6540                    continue;
6541                }
6542
6543                if(g_pSyncList[i]->first_sync)
6544                {
6545
6546                    wd_DEBUG("first sync!\n");
6547                    g_pSyncList[i]->VeryOldServerRootNode=g_pSyncList[i]->OldServerRootNode;
6548                    //g_pSyncList[i]->first_sync = 0;
6549                    //free_server_tree(g_pSyncList[i]->OldServerRootNode);
6550                    g_pSyncList[i]->OldServerRootNode = g_pSyncList[i]->ServerRootNode;
6551                    //getLocalList();
6552                    status=Server_sync(i);
6553                    free_server_tree(g_pSyncList[i]->VeryOldServerRootNode);
6554                    if(status == 0)
6555                        g_pSyncList[i]->first_sync = 0;
6556                    else
6557                        g_pSyncList[i]->first_sync = 1;
6558                }
6559                else
6560                {
6561                    if(asus_cfg.prule[i]->rule == 0)
6562                    {
6563                        status=compareServerList(i);
6564                    }
6565                    //serverList different or download only
6566                    if (status == 0 || asus_cfg.prule[i]->rule == 1)
6567                    {
6568
6569                        g_pSyncList[i]->VeryOldServerRootNode=g_pSyncList[i]->OldServerRootNode;
6570                        //g_pSyncList[i]->first_sync = 0;
6571                        //free_server_tree(g_pSyncList[i]->OldServerRootNode);
6572                        g_pSyncList[i]->OldServerRootNode = g_pSyncList[i]->ServerRootNode;
6573                        //getLocalList();
6574                        status=Server_sync(i);
6575                        free_server_tree(g_pSyncList[i]->VeryOldServerRootNode);
6576                        if(status == 0)
6577                            g_pSyncList[i]->first_sync = 0;
6578                        else
6579                            g_pSyncList[i]->first_sync = 1;
6580                    }
6581                    else
6582                    {//serverList same
6583
6584                        free_server_tree(g_pSyncList[i]->ServerRootNode);
6585                        g_pSyncList[i]->ServerRootNode = NULL;
6586                        status = 0;
6587                    }
6588                }
6589
6590                /*
6591                if(status == 0 || asus_cfg.prule[i]->rule == 1)
6592                {
6593                    status=Server_sync(i);
6594                }
6595                free_server_tree(g_pSyncList[i]->OldServerRootNode);
6596                g_pSyncList[i]->OldServerRootNode = g_pSyncList[i]->ServerRootNode;
6597                */
6598            }
6599//            if(!status)
6600                write_log(S_SYNC,"","",i);
6601//            else
6602//            {
6603//                write_log(S_ERROR,"Local synchronization is not entirely successful,failure information,please refer errlog","",i);
6604//            }
6605
6606        }
6607        server_sync = 0;      //server sync finished
6608        pthread_mutex_lock(&mutex);
6609        if(!exit_loop)
6610        {
6611            gettimeofday(&now, NULL);
6612            outtime.tv_sec = now.tv_sec + 10;
6613            outtime.tv_nsec = now.tv_usec * 1000;
6614            pthread_cond_timedwait(&cond, &mutex, &outtime);
6615        }
6616        pthread_mutex_unlock(&mutex);
6617    }
6618
6619
6620    wd_DEBUG("stop dropbox server sync\n");
6621
6622}
6623
6624int Server_sync(int index)
6625{
6626
6627    wd_DEBUG("compareLocalList start!\n");
6628
6629    int ret = 0;
6630
6631    if(g_pSyncList[index]->ServerRootNode->Child != NULL)
6632    {
6633
6634        wd_DEBUG("ServerRootNode->Child != NULL\n");
6635
6636        ret = sync_local_with_server(g_pSyncList[index]->ServerRootNode->Child,sync_local_with_server_perform,index);
6637    }
6638    else
6639    {
6640
6641        wd_DEBUG("ServerRootNode->Child == NULL\n");
6642
6643    }
6644
6645    return ret;
6646}
6647
6648/*
6649 *judge is server changed
6650 *0:server changed
6651 *1:server is not changed
6652*/
6653int isServerChanged(Server_TreeNode *newNode,Server_TreeNode *oldNode)
6654{
6655    //printf("isServerChanged start!\n");
6656    int res = 1;
6657    int serverchanged = 0;
6658    if(newNode->browse == NULL && oldNode->browse == NULL)
6659    {
6660
6661        //wd_DEBUG("########Server is not change\n");
6662
6663        return 1;
6664    }
6665    else if(newNode->browse == NULL && oldNode->browse != NULL)
6666    {
6667
6668        //wd_DEBUG("########Server changed1\n");
6669
6670        return 0;
6671    }
6672    else if(newNode->browse != NULL && oldNode->browse == NULL)
6673    {
6674
6675        //wd_DEBUG("########Server changed2\n");
6676
6677        return 0;
6678    }
6679    else
6680    {
6681        if(newNode->browse->filenumber != oldNode->browse->filenumber || newNode->browse->foldernumber != oldNode->browse->foldernumber)
6682        {
6683
6684            //wd_DEBUG("########Server changed3\n");
6685
6686            return 0;
6687        }
6688        else
6689        {
6690            int cmp;
6691            CloudFile *newfoldertmp = NULL;
6692            CloudFile *oldfoldertmp = NULL;
6693            CloudFile *newfiletmp = NULL;
6694            CloudFile *oldfiletmp = NULL;
6695            if(newNode->browse != NULL)
6696            {
6697                if(newNode->browse->foldernumber > 0)
6698                    newfoldertmp = newNode->browse->folderlist->next;
6699                if(newNode->browse->filenumber > 0)
6700                    newfiletmp = newNode->browse->filelist->next;
6701            }
6702            if(oldNode->browse != NULL)
6703            {
6704                if(oldNode->browse->foldernumber > 0)
6705                    oldfoldertmp = oldNode->browse->folderlist->next;
6706                if(oldNode->browse->filenumber > 0)
6707                    oldfiletmp = oldNode->browse->filelist->next;
6708            }
6709
6710            while (newfoldertmp != NULL || oldfoldertmp != NULL)
6711            {
6712                if ((cmp = strcmp(newfoldertmp->href,oldfoldertmp->href)) != 0){
6713
6714                    //wd_DEBUG("########Server changed4\n");
6715
6716                    return 0;
6717                }
6718                newfoldertmp = newfoldertmp->next;
6719                oldfoldertmp = oldfoldertmp->next;
6720            }
6721            while (newfiletmp != NULL || oldfiletmp != NULL)
6722            {
6723                if ((cmp = strcmp(newfiletmp->href,oldfiletmp->href)) != 0)
6724                {
6725
6726                    //wd_DEBUG("########Server changed5\n");
6727
6728                    return 0;
6729                }
6730                if (newfiletmp->mtime != oldfiletmp->mtime)
6731                {
6732                    //printf("newpath=%s,newtime=%lu\n",newfiletmp->href,newfiletmp->modtime);
6733                    //printf("oldpath=%s,oldtime=%lu\n",oldfiletmp->href,oldfiletmp->modtime);
6734
6735                    //wd_DEBUG("########Server changed6\n");
6736
6737                    return 0;
6738                }
6739                newfiletmp = newfiletmp->next;
6740                oldfiletmp = oldfiletmp->next;
6741            }
6742        }
6743
6744        if((newNode->Child == NULL && oldNode->Child != NULL) || (newNode->Child != NULL && oldNode->Child == NULL))
6745        {
6746
6747            //wd_DEBUG("########Server changed7\n");
6748
6749            return 0;
6750        }
6751        if((newNode->NextBrother == NULL && oldNode->NextBrother != NULL) || (newNode->NextBrother!= NULL && oldNode->NextBrother == NULL))
6752        {
6753
6754            //wd_DEBUG("########Server changed8\n");
6755
6756            return 0;
6757        }
6758
6759        if(newNode->Child != NULL && oldNode->Child != NULL && !exit_loop)
6760        {
6761            res = isServerChanged(newNode->Child,oldNode->Child);
6762            if(res == 0)
6763            {
6764                serverchanged = 1;
6765            }
6766        }
6767        if(newNode->NextBrother != NULL && oldNode->NextBrother != NULL && !exit_loop)
6768        {
6769            res = isServerChanged(newNode->NextBrother,oldNode->NextBrother);
6770            if(res == 0)
6771            {
6772                serverchanged = 1;
6773            }
6774        }
6775    }
6776    //wd_DEBUG("#########compareServerList over\n");
6777    if(serverchanged == 1)
6778    {
6779
6780        wd_DEBUG("########Server changed9\n");
6781
6782        return 0;
6783    }
6784    else
6785    {
6786        //printf("########Server is not change\n");
6787        return 1;
6788    }
6789}
6790
6791/*ret = 0,server changed
6792 *ret = 1,server is no changed
6793*/
6794int compareServerList(int index)
6795{
6796    int ret;
6797
6798    wd_DEBUG("#########compareServerList\n");
6799
6800    if(g_pSyncList[index]->ServerRootNode->Child != NULL && g_pSyncList[index]->OldServerRootNode->Child != NULL)
6801    {
6802        ret = isServerChanged(g_pSyncList[index]->ServerRootNode->Child,g_pSyncList[index]->OldServerRootNode->Child);
6803        return ret;
6804    }
6805    else if(g_pSyncList[index]->ServerRootNode->Child == NULL && g_pSyncList[index]->OldServerRootNode->Child == NULL)
6806    {
6807        ret = 1;
6808        return ret;
6809    }
6810    else
6811    {
6812        ret = 0;
6813        return ret;
6814    }
6815}
6816int get_create_threads_state()
6817{
6818    int i;
6819    for(i=0;i<asus_cfg.dir_number;i++)
6820    {
6821        if(asus_cfg.prule[i]->rule != 2)
6822        {
6823            return 1;
6824        }
6825    }
6826
6827    return 0;
6828}
6829int download_only_add_socket_item(char *cmd,int index)
6830{
6831
6832    wd_DEBUG("download_only_add_socket_item receive socket : %s\n",cmd);
6833
6834    if( strstr(cmd,"(conflict)") != NULL )
6835        return 0;
6836
6837    wd_DEBUG("socket command is %s \n",cmd);
6838
6839
6840    if( !strncmp(cmd,"exit",4))
6841    {
6842
6843        wd_DEBUG("exit socket\n");
6844
6845        return 0;
6846    }
6847
6848    if(!strncmp(cmd,"rmroot",6))
6849    {
6850        g_pSyncList[index]->no_local_root = 1;
6851        return 0;
6852    }
6853
6854
6855    char cmd_name[64];
6856    char *path = NULL;
6857    char *temp = NULL;
6858    char filename[256];
6859    char *fullname = NULL;
6860    char oldname[256],newname[256];
6861    char *oldpath = NULL;
6862    char action[64];
6863    //char *cmp_name = NULL;
6864    //char *mv_newpath;
6865    //char *mv_oldpath;
6866    char *ch = NULL;
6867    char *old_fullname = NULL;
6868    //int status;
6869
6870    memset(cmd_name,'\0',sizeof(cmd_name));
6871    memset(oldname,'\0',sizeof(oldname));
6872    memset(newname,'\0',sizeof(newname));
6873    memset(action,'\0',sizeof(action));
6874
6875    ch = cmd;
6876    int i = 0;
6877    //while(*ch != '@')
6878    while(*ch != '\n')
6879    {
6880        i++;
6881        ch++;
6882    }
6883
6884    memcpy(cmd_name, cmd, i);
6885
6886    char *p = NULL;
6887    ch++;
6888    i++;
6889
6890    temp = my_str_malloc((size_t)(strlen(ch)+1));
6891
6892    strcpy(temp,ch);
6893    //p = strchr(temp,'@');
6894    p = strchr(temp,'\n');
6895
6896    //printf("temp = %s\n",temp);
6897    //printf("p = %s\n",p);
6898    //printf("strlen(temp)- strlen(p) = %d\n",strlen(temp)- strlen(p));
6899
6900    path = my_str_malloc((size_t)(strlen(temp)- strlen(p)+1));
6901
6902    //printf("path = %s\n",path);
6903
6904    if(p!=NULL)
6905        snprintf(path,strlen(temp)- strlen(p)+1,"%s",temp);
6906
6907    //free(temp);
6908
6909    p++;
6910    if(strncmp(cmd_name, "rename",6) == 0)
6911    {
6912        char *p1 = NULL;
6913
6914        //p1 = strchr(p,'@');
6915        p1 = strchr(p,'\n');
6916
6917        if(p1 != NULL)
6918            strncpy(oldname,p,strlen(p)- strlen(p1));
6919
6920        p1++;
6921
6922        strcpy(newname,p1);
6923
6924        wd_DEBUG("cmd_name: [%s],path: [%s],oldname: [%s],newname: [%s]\n",cmd_name,path,oldname,newname);
6925
6926    }
6927    else if(strncmp(cmd_name, "move",4) == 0)
6928    {
6929        char *p1 = NULL;
6930
6931        p1 = strchr(p,'\n');
6932        //p1 = strchr(p,'@');
6933
6934        oldpath = my_str_malloc((size_t)(strlen(p)- strlen(p1)+1));
6935
6936        if(p1 != NULL)
6937            snprintf(oldpath,strlen(p)- strlen(p1)+1,"%s",p);
6938
6939        p1++;
6940
6941        strcpy(oldname,p1);
6942
6943        wd_DEBUG("cmd_name: [%s],path: [%s],oldpath: [%s],oldname: [%s]\n",cmd_name,path,oldpath,oldname);
6944
6945    }
6946    else
6947    {
6948        strcpy(filename,p);
6949        //fullname = my_str_malloc((size_t)(strlen(path)+strlen(filename)+2));
6950
6951        wd_DEBUG("cmd_name: [%s],path: [%s],filename: [%s]\n",cmd_name,path,filename);
6952
6953    }
6954
6955    free(temp);
6956
6957    if( !strncmp(cmd_name,"rename",strlen("rename")) )
6958    {
6959        fullname = my_str_malloc((size_t)(strlen(path)+strlen(newname)+2));
6960        old_fullname = my_str_malloc((size_t)(strlen(path)+strlen(oldname)+2));
6961        sprintf(fullname,"%s/%s",path,newname);
6962        sprintf(old_fullname,"%s/%s",path,oldname);
6963        free(path);
6964    }
6965    else if( !strncmp(cmd_name,"move",strlen("move")) )
6966    {
6967        fullname = my_str_malloc((size_t)(strlen(path)+strlen(oldname)+2));
6968        old_fullname = my_str_malloc((size_t)(strlen(oldpath)+strlen(oldname)+2));
6969        sprintf(fullname,"%s/%s",path,oldname);
6970        sprintf(old_fullname,"%s/%s",oldpath,oldname);
6971        free(oldpath);
6972        free(path);
6973    }
6974    else
6975    {
6976        fullname = my_str_malloc((size_t)(strlen(path)+strlen(filename)+2));
6977        sprintf(fullname,"%s/%s",path,filename);
6978        free(path);
6979    }
6980    if( !strncmp(cmd_name,"copyfile",strlen("copyfile")) )
6981    {
6982        add_action_item("copyfile",fullname,g_pSyncList[index]->copy_file_list);
6983        free(fullname);
6984        return 0;
6985    }
6986
6987
6988    if( strcmp(cmd_name, "createfile") == 0 )
6989    {
6990        strcpy(action,"createfile");
6991        action_item *item;
6992
6993        item = get_action_item("copyfile",fullname,g_pSyncList[index]->copy_file_list,index);
6994
6995        if(item != NULL)
6996        {
6997
6998            wd_DEBUG("##### delete copyfile %s ######\n",fullname);
6999
7000            //pthread_mutex_lock(&mutex);
7001            del_action_item("copyfile",fullname,g_pSyncList[index]->copy_file_list);
7002        }
7003    }
7004    else if( strcmp(cmd_name, "cancelcopy") == 0 )
7005    {
7006        action_item *item;
7007
7008        item = get_action_item("copyfile",fullname,g_pSyncList[index]->copy_file_list,index);
7009
7010        if(item != NULL)
7011        {
7012
7013            wd_DEBUG("##### delete copyfile %s ######\n",fullname);
7014
7015            //pthread_mutex_lock(&mutex);
7016            del_action_item("copyfile",fullname,g_pSyncList[index]->copy_file_list);
7017        }
7018        free(fullname);
7019        return 0;
7020    }
7021    else if( strcmp(cmd_name, "remove") == 0  || strcmp(cmd_name, "delete") == 0)
7022    {
7023        strcpy(action,"remove");
7024        del_download_only_action_item(action,fullname,g_pSyncList[index]->download_only_socket_head);
7025    }
7026    else if( strcmp(cmd_name, "createfolder") == 0 )
7027    {
7028        strcpy(action,"createfolder");
7029    }
7030    else if( strncmp(cmd_name, "rename",6) == 0 )
7031    {
7032        strcpy(action,"rename");
7033        del_download_only_action_item(action,old_fullname,g_pSyncList[index]->download_only_socket_head);
7034        free(old_fullname);
7035    }
7036    else if( strncmp(cmd_name, "move",4) == 0 )
7037    {
7038        strcpy(action,"move");
7039        del_download_only_action_item(action,old_fullname,g_pSyncList[index]->download_only_socket_head);
7040        //free(old_fullname);
7041    }
7042
7043    if(g_pSyncList[index]->server_action_list->next != NULL)
7044    {
7045        action_item *item;
7046
7047        item = get_action_item(action,fullname,g_pSyncList[index]->server_action_list,index);
7048
7049        if(item != NULL)
7050        {
7051
7052            wd_DEBUG("##### %s %s by dropbox Server self ######\n",action,fullname);
7053
7054            //pthread_mutex_lock(&mutex);
7055            del_action_item(action,fullname,g_pSyncList[index]->server_action_list);
7056
7057            //pthread_mutex_unlock(&mutex);
7058            //local_sync = 0;
7059            free(fullname);
7060            return 0;
7061        }
7062    }
7063
7064    if( strcmp(cmd_name, "copyfile") != 0 )
7065    {
7066        g_pSyncList[index]->have_local_socket = 1;
7067    }
7068
7069
7070    //}
7071    //printf("add download_only_socket_head fullname = %s\n",fullname);
7072    if(strncmp(cmd_name, "rename",6) == 0)
7073    {
7074        if(test_if_dir(fullname))
7075        {
7076            add_all_download_only_socket_list(cmd_name,fullname,index);
7077        }
7078        else
7079        {
7080            add_action_item(cmd_name,fullname,g_pSyncList[index]->download_only_socket_head);
7081        }
7082    }
7083    else if(strncmp(cmd_name, "move",4) == 0)
7084    {
7085        if(test_if_dir(fullname))
7086        {
7087            add_all_download_only_socket_list(cmd_name,fullname,index);
7088        }
7089        else
7090        {
7091            add_action_item(cmd_name,fullname,g_pSyncList[index]->download_only_socket_head);
7092        }
7093    }
7094    else if(strcmp(cmd_name, "createfolder") == 0 || strcmp(cmd_name, "dragfolder") == 0)
7095    {
7096        add_action_item(cmd_name,fullname,g_pSyncList[index]->download_only_socket_head);
7097        if(!strcmp(cmd_name, "dragfolder"))
7098            add_all_download_only_dragfolder_socket_list(fullname,index);
7099    }
7100    else if( strcmp(cmd_name, "createfile") == 0  || strcmp(cmd_name, "dragfile") == 0 || strcmp(cmd_name, "modify") == 0)
7101    {
7102        add_action_item(cmd_name,fullname,g_pSyncList[index]->download_only_socket_head);
7103    }
7104
7105    free(fullname);
7106    return 0;
7107
7108
7109}
7110void *Socket_Parser()
7111{
7112
7113    wd_DEBUG("*******Socket_Parser start********\n");
7114
7115    queue_entry_t socket_execute;
7116    int i;
7117    int status;
7118    int has_socket = 0;
7119    int fail_flag;
7120    struct timeval now;
7121    struct timespec outtime;
7122    while(!exit_loop)
7123    {
7124        for(i=0;i<asus_cfg.dir_number;i++)
7125        {
7126            while(server_sync == 1 && exit_loop ==0)
7127            {
7128                usleep(1000*10);
7129            }
7130            local_sync=1;
7131
7132            if(exit_loop)
7133                break;
7134#if TOKENFILE
7135            if(disk_change)
7136            {
7137                //disk_change = 0;
7138                check_disk_change();
7139            }
7140
7141            if(g_pSyncList[i]->sync_disk_exist == 0)
7142                continue;
7143#endif
7144            if(asus_cfg.prule[i]->rule == 1) //Download only
7145            {
7146                while(exit_loop == 0)
7147                {
7148                    while(g_pSyncList[i]->SocketActionList->head != NULL && exit_loop == 0 && server_sync == 0)
7149                    {
7150                        has_socket = 1;
7151                        socket_execute=g_pSyncList[i]->SocketActionList->head;
7152                        status = download_only_add_socket_item(socket_execute->cmd_name,i);
7153                        if(status == 0  || status == SERVER_SPACE_NOT_ENOUGH
7154                           || status == LOCAL_FILE_LOST)
7155                        {
7156                            pthread_mutex_lock(&mutex_socket);
7157                            socket_execute = queue_dequeue(g_pSyncList[i]->SocketActionList);
7158
7159#if MEM_POOL_ENABLE
7160                    mem_free(socket_execute->cmd_name);
7161                    mem_free(socket_execute->re_cmd);
7162                    mem_free(socket_execute);
7163#else
7164                    if(socket_execute->re_cmd)
7165                        free(socket_execute->re_cmd);
7166                    if(socket_execute->cmd_name)
7167                        free(socket_execute->cmd_name);
7168                    free(socket_execute);
7169#endif
7170                            //printf("del socket item ok\n");
7171                            pthread_mutex_unlock(&mutex_socket);
7172                        }
7173                        else
7174                        {
7175                            fail_flag = 1;
7176
7177                            wd_DEBUG("######## socket item fail########\n");
7178
7179                            break;
7180                        }
7181                        //sleep(2);
7182                        usleep(1000*20);
7183                    }
7184                    if(fail_flag)
7185                        break;
7186
7187                    if(g_pSyncList[i]->copy_file_list->next == NULL)
7188                    {
7189                        break;
7190                    }
7191                    else
7192                    {
7193                        usleep(1000*100);
7194                        //sleep(1);
7195                    }
7196                }
7197                if(g_pSyncList[i]->server_action_list->next != NULL && g_pSyncList[i]->SocketActionList->head == NULL)
7198                {
7199                    free_action_item(g_pSyncList[i]->server_action_list);
7200                    g_pSyncList[i]->server_action_list = create_action_item_head();
7201                }
7202                pthread_mutex_lock(&mutex_receve_socket);
7203                //receve_socket = 0;
7204                if(g_pSyncList[i]->SocketActionList->head == NULL)
7205                    g_pSyncList[i]->receve_socket = 0;
7206                pthread_mutex_unlock(&mutex_receve_socket);
7207            }
7208            else
7209            {
7210                if(asus_cfg.prule[i]->rule == 2)
7211                {
7212#if 0
7213                    /*
7214                     fix upload only rule rm sync dir , can not create new sync dir;
7215                    */
7216
7217                    if(g_pSyncList[i]->no_local_root)
7218                    {
7219                        my_mkdir_r(asus_cfg.prule[i]->path);   //have mountpath
7220                        send_action(asus_cfg.type,asus_cfg.prule[i]->path);
7221                        usleep(1000*10);
7222                        g_pSyncList[i]->no_local_root = 0;
7223                        //g_pSyncList[i]->init_completed = 0;
7224                    }
7225
7226                    /*
7227                     fix upload only initial failed,must run intial again();
7228                    */
7229                    if(finished_initial)
7230                    {
7231                        if( g_pSyncList[i]->init_completed != 1)
7232                        {
7233                            sync_initial_again(i);
7234                        }
7235                    }
7236
7237                    /*upload only rule is not server pthread,so unfinished list del is here*/
7238                    status = do_unfinished(i);
7239#endif
7240                }
7241                while(exit_loop == 0)
7242                {
7243                    while(g_pSyncList[i]->SocketActionList->head != NULL && server_sync ==0 && exit_loop ==0)
7244                    {
7245                        has_socket = 1;
7246                        socket_execute=g_pSyncList[i]->SocketActionList->head;
7247
7248                        wd_DEBUG("######## socket cmd : %s########\n",socket_execute->cmd_name);
7249
7250                        status=cmd_parser(socket_execute->cmd_name,i,socket_execute->re_cmd);
7251                        if(status == 0 || status == SERVER_SPACE_NOT_ENOUGH )
7252                        {
7253                            wd_DEBUG("del socket item ok?\n");
7254                            pthread_mutex_lock(&mutex_socket);
7255                            socket_execute = queue_dequeue(g_pSyncList[i]->SocketActionList);
7256#if MEM_POOL_ENABLE
7257                    mem_free(socket_execute->cmd_name);
7258                    mem_free(socket_execute->re_cmd);
7259                    mem_free(socket_execute);
7260#else
7261                    if(socket_execute->re_cmd)
7262                        free(socket_execute->re_cmd);
7263                    if(socket_execute->cmd_name)
7264                        free(socket_execute->cmd_name);
7265                    free(socket_execute);
7266#endif
7267                            wd_DEBUG("del socket item ok\n");
7268                            pthread_mutex_unlock(&mutex_socket);
7269                        }
7270                        else if(status == LOCAL_FILE_LOST )
7271                        {
7272                            wd_DEBUG("del socket item ok?\n");
7273                            pthread_mutex_lock(&mutex_socket);
7274                            socket_execute = queue_dequeue_t(g_pSyncList[i]->SocketActionList);
7275#if MEM_POOL_ENABLE
7276                    mem_free(socket_execute->cmd_name);
7277                    mem_free(socket_execute->re_cmd);
7278                    mem_free(socket_execute);
7279#else
7280                    if(socket_execute->re_cmd)
7281                        free(socket_execute->re_cmd);
7282                    if(socket_execute->cmd_name)
7283                        free(socket_execute->cmd_name);
7284                    free(socket_execute);
7285#endif
7286                            wd_DEBUG("del socket item ok\n");
7287                            pthread_mutex_unlock(&mutex_socket);
7288                        }
7289                        else
7290                        {
7291                            fail_flag = 1;
7292
7293                            //wd_DEBUG("######## socket item fail########\n");
7294
7295                            break;
7296                        }
7297                        //sleep(2);
7298                        usleep(1000*20);
7299                    }
7300                    if(fail_flag)
7301                        break;
7302
7303                    //wd_DEBUG("######## socket del finished########\n");
7304
7305                    if(g_pSyncList[i]->copy_file_list->next == NULL)
7306                    {
7307                        break;
7308                    }
7309                    else
7310                    {
7311                        //sleep(1);
7312                        usleep(1000*100);
7313                    }
7314                }
7315                if(g_pSyncList[i]->server_action_list->next != NULL && g_pSyncList[i]->SocketActionList->head == NULL)
7316                {
7317                    free_action_item(g_pSyncList[i]->server_action_list);
7318                    g_pSyncList[i]->server_action_list = create_action_item_head();
7319                }
7320                //wd_DEBUG("#### clear server_action_list success!\n");
7321                pthread_mutex_lock(&mutex_receve_socket);
7322                if(g_pSyncList[i]->SocketActionList->head == NULL)
7323                {
7324                    g_pSyncList[i]->receve_socket = 0;
7325                }
7326                pthread_mutex_unlock(&mutex_receve_socket);
7327            }
7328
7329        }
7330        local_sync = 0;
7331        pthread_mutex_lock(&mutex_socket);
7332        if(!exit_loop)
7333        {
7334            gettimeofday(&now, NULL);
7335            outtime.tv_sec = now.tv_sec + 2;
7336            outtime.tv_nsec = now.tv_usec * 1000;
7337            pthread_cond_timedwait(&cond_socket, &mutex_socket, &outtime);
7338        }
7339        pthread_mutex_unlock(&mutex_socket);
7340    }
7341}
7342int cmd_parser(char *cmd,int index,char *re_cmd)
7343{
7344//    if(strstr(cmd,"conflict") != NULL)
7345//        return 0;
7346    if( !strncmp(cmd,"exit",4))
7347    {
7348
7349        wd_DEBUG("exit socket\n");
7350
7351        return 0;
7352    }
7353
7354    if(!strncmp(cmd,"rmroot",6))
7355    {
7356        g_pSyncList[index]->no_local_root = 1;
7357        return 0;
7358    }
7359
7360    char cmd_name[64]="\0";
7361    char *path;
7362    char *temp;
7363    char filename[256]="\0";
7364    char *fullname;
7365    char *fullname_t = NULL;
7366    char oldname[256]="\0",newname[256]="\0";
7367    char *oldpath;
7368    char action[64]="\0";
7369    char *cmp_name;
7370    char *mv_newpath;
7371    char *mv_oldpath;
7372    char *ch;
7373    int status;
7374
7375    ch = cmd;
7376    int i = 0;
7377    //while(*ch != '@')
7378    while(*ch != '\n')
7379    {
7380        i++;
7381        ch++;
7382    }
7383
7384    memcpy(cmd_name, cmd, i);
7385
7386    char *p = NULL;
7387    ch++;
7388    i++;
7389
7390    temp = my_str_malloc((size_t)(strlen(ch)+1));
7391
7392    strcpy(temp,ch);
7393    //p = strchr(temp,'@');
7394    p = strchr(temp,'\n');
7395
7396    path = my_str_malloc((size_t)(strlen(temp)- strlen(p)+1));
7397
7398
7399    if(p!=NULL)
7400        snprintf(path,strlen(temp)- strlen(p)+1,"%s",temp);
7401
7402    p++;
7403    if(strncmp(cmd_name, "rename",strlen("rename")) == 0)
7404    {
7405        char *p1 = NULL;
7406
7407        //p1 = strchr(p,'@');
7408        p1 = strchr(p,'\n');
7409
7410        if(p1 != NULL)
7411            strncpy(oldname,p,strlen(p)- strlen(p1));
7412
7413        p1++;
7414
7415        strcpy(newname,p1);
7416
7417        wd_DEBUG("cmd_name: [%s],path: [%s],oldname: [%s],newname: [%s]\n",cmd_name,path,oldname,newname);
7418
7419        if(newname[0] == '.' || (strstr(path,"/.")) != NULL)
7420        {
7421            free(temp);
7422            free(path);
7423            return 0;
7424        }
7425    }
7426    else if(strncmp(cmd_name, "move",strlen("move")) == 0)
7427    {
7428        char *p1 = NULL;
7429
7430        //p1 = strchr(p,'@');
7431        p1 = strchr(p,'\n');
7432
7433        oldpath = my_str_malloc((size_t)(strlen(p)- strlen(p1)+1));
7434
7435        if(p1 != NULL)
7436            snprintf(oldpath,strlen(p)- strlen(p1)+1,"%s",p);
7437
7438        p1++;
7439
7440        strcpy(oldname,p1);
7441
7442        wd_DEBUG("cmd_name: [%s],path: [%s],oldpath: [%s],oldname: [%s]\n",cmd_name,path,oldpath,oldname);
7443
7444
7445        if(oldname[0] == '.' || (strstr(path,"/.")) != NULL)
7446        {
7447            free(temp);
7448            free(path);
7449            free(oldpath);
7450            return 0;
7451        }
7452    }
7453    else if(strcmp(cmd_name, "delete") == 0 || strcmp(cmd_name, "remove") == 0)
7454    {
7455        strcpy(filename,p);
7456        fullname = my_str_malloc((size_t)(strlen(path)+strlen(filename)+2));
7457
7458        wd_DEBUG("cmd_name: [%s],path: [%s],filename: [%s]\n",cmd_name,path,filename);
7459
7460        if(filename[0] == '.' || (strstr(path,"/.")) != NULL)
7461        {
7462            free(temp);
7463            free(path);
7464            return 0;
7465        }
7466    }
7467    else
7468    {
7469        strcpy(filename,p);
7470        fullname = my_str_malloc((size_t)(strlen(path)+strlen(filename)+2));
7471        if(re_cmd != NULL)
7472            fullname_t = my_str_malloc((size_t)(strlen(re_cmd)+strlen(filename)+2));
7473
7474        wd_DEBUG("cmd_name: [%s],path: [%s],filename: [%s]\n",cmd_name,path,filename);
7475
7476        if(filename[0] == '.' || (strstr(path,"/.")) != NULL)
7477        {
7478            free(temp);
7479            free(path);
7480            return 0;
7481        }
7482    }
7483
7484    free(temp);
7485
7486    if( !strncmp(cmd_name,"rename",strlen("rename")) )
7487    {
7488        cmp_name = my_str_malloc((size_t)(strlen(path)+strlen(newname)+2));
7489        sprintf(cmp_name,"%s/%s",path,newname);
7490    }
7491    else if( !strcmp(cmd_name,"delete") || !strcmp(cmd_name,"remove"))
7492    {
7493        cmp_name = my_str_malloc((size_t)(strlen(path)+strlen(filename)+2));
7494        sprintf(cmp_name,"%s/%s",path,filename);
7495    }
7496    else
7497    {
7498        if(re_cmd == NULL)
7499        {
7500            cmp_name = my_str_malloc((size_t)(strlen(path)+strlen(filename)+2));
7501            sprintf(cmp_name,"%s/%s",path,filename);
7502        }
7503        else
7504        {
7505            cmp_name = my_str_malloc((size_t)(strlen(re_cmd)+strlen(filename)+2));
7506            sprintf(cmp_name,"%s%s",re_cmd,filename);
7507        }
7508    }
7509
7510    if( strcmp(cmd_name, "createfile") == 0 )
7511    {
7512        strcpy(action,"createfile");
7513        action_item *item;
7514
7515        item = get_action_item("copyfile",cmp_name,g_pSyncList[index]->copy_file_list,index);
7516
7517        if(item != NULL)
7518        {
7519
7520            wd_DEBUG("##### delete copyfile %s ######\n",cmp_name);
7521
7522            del_action_item("copyfile",cmp_name,g_pSyncList[index]->copy_file_list);
7523        }
7524    }
7525    else if( strcmp(cmd_name, "cancelcopy") == 0 )
7526    {
7527        action_item *item;
7528
7529        item = get_action_item("copyfile",cmp_name,g_pSyncList[index]->copy_file_list,index);
7530
7531        if(item != NULL)
7532        {
7533
7534            wd_DEBUG("##### delete copyfile %s ######\n",cmp_name);
7535
7536            del_action_item("copyfile",cmp_name,g_pSyncList[index]->copy_file_list);
7537        }
7538        free(path);
7539        free(cmp_name);
7540        free(fullname);
7541        return 0;
7542    }
7543    else if( strcmp(cmd_name, "remove") == 0  || strcmp(cmd_name, "delete") == 0)
7544    {
7545        strcpy(action,"remove");
7546    }
7547    else if( strcmp(cmd_name, "createfolder") == 0 )
7548    {
7549        strcpy(action,"createfolder");
7550    }
7551    else if( strncmp(cmd_name, "rename",strlen("rename")) == 0 )
7552    {
7553        strcpy(action,"rename");
7554    }
7555#if 1
7556    if(g_pSyncList[index]->server_action_list->next != NULL)
7557    {
7558        action_item *item;
7559
7560        item = get_action_item(action,cmp_name,g_pSyncList[index]->server_action_list,index);
7561
7562        if(item != NULL)
7563        {
7564
7565            wd_DEBUG("##### %s %s by Dropbox Server self ######\n",action,cmp_name);
7566
7567            //pthread_mutex_lock(&mutex);
7568            del_action_item(action,cmp_name,g_pSyncList[index]->server_action_list);
7569
7570            wd_DEBUG("#### del action item success!\n");
7571
7572            //pthread_mutex_unlock(&mutex);
7573            //local_sync = 0;
7574            free(path);
7575            if( strncmp(cmd_name, "rename",strlen("rename")) != 0 )
7576                free(fullname);
7577            free(cmp_name);
7578            return 0;
7579        }
7580    }
7581#endif
7582    free(cmp_name);
7583
7584
7585    wd_DEBUG("###### %s is start ######\n",cmd_name);
7586    //write_system_log(cmd_name,"start");
7587
7588
7589    if( strcmp(cmd_name, "copyfile") != 0 )
7590    {
7591        g_pSyncList[index]->have_local_socket = 1;
7592    }
7593
7594    if( strcmp(cmd_name, "createfile") == 0 || strcmp(cmd_name, "dragfile") == 0 )
7595    {
7596
7597        sprintf(fullname,"%s/%s",path,filename);
7598        char *serverpath=localpath_to_serverpath(fullname,index);
7599        if(re_cmd != NULL)
7600        {
7601            sprintf(fullname_t,"%s%s",re_cmd,filename);
7602            status=upload_file(fullname_t,serverpath,0,index);
7603        }
7604        else
7605        {
7606            status=upload_file(fullname,serverpath,0,index);
7607        }
7608
7609        /*third param flase,false=>if server file has exit ,will not be overwrite*/
7610        if(status == 0)
7611        {
7612            char *newlocalname = NULL;
7613            cJSON *json = dofile(Con(TMP_R,upload_chunk_commit.txt));
7614            time_t mtime=cJSON_printf(json,"modified");
7615            cJSON_Delete(json);
7616            if(re_cmd == NULL)
7617                newlocalname=change_local_same_file(fullname,index);
7618            else
7619                newlocalname=change_local_same_file(fullname_t,index);
7620            if(newlocalname)
7621                ChangeFile_modtime(newlocalname,mtime);
7622            if(re_cmd)
7623                free(fullname_t);
7624            free(fullname);
7625            free(newlocalname);
7626            free(serverpath);
7627        }
7628        else
7629        {
7630
7631            wd_DEBUG("upload %s failed\n",fullname);
7632            //write_system_log("error","uploadfile fail");
7633            if(re_cmd)
7634                free(fullname_t);
7635            free(path);
7636            free(fullname);
7637            free(serverpath);
7638            return status;
7639        }
7640    }
7641    else if( strcmp(cmd_name, "copyfile") == 0 )
7642    {
7643        if(re_cmd == NULL)
7644        {
7645            sprintf(fullname,"%s/%s",path,filename);
7646            add_action_item("copyfile",fullname,g_pSyncList[index]->copy_file_list);
7647        }
7648        else
7649        {
7650            sprintf(fullname_t,"%s%s",re_cmd,filename);
7651            add_action_item("copyfile",fullname_t,g_pSyncList[index]->copy_file_list);
7652        }
7653        free(fullname);
7654        if(re_cmd)
7655            free(fullname_t);
7656    }
7657    else if( strcmp(cmd_name, "modify") == 0 )
7658    {
7659        time_t mtime_1,mtime_2;
7660
7661        sprintf(fullname,"%s/%s",path,filename);
7662        char *serverpath=localpath_to_serverpath(fullname,index);
7663        if(re_cmd != NULL)
7664            sprintf(fullname_t,"%s%s",re_cmd,filename);
7665
7666        CloudFile *filetmp;
7667        filetmp=get_CloudFile_node(g_pSyncList[index]->OldServerRootNode,serverpath,0x2);
7668        if(filetmp == NULL)
7669        {
7670            mtime_1=(time_t)-1;
7671        }
7672        else
7673        {
7674            mtime_1=filetmp->mtime;
7675        }
7676        mtime_2=api_getmtime(serverpath,dofile);
7677        if(mtime_2 == -1)
7678        {
7679            /*only upload */
7680            /*third param ture,ture=>if server file has exit ,will be overwrite*/
7681            if(re_cmd == NULL)
7682                status=upload_file(fullname,serverpath,1,index);
7683            else
7684                status=upload_file(fullname_t,serverpath,1,index);
7685            if(status == 0)
7686            {
7687                cJSON *json = dofile(Con(TMP_R,upload_chunk_commit.txt));
7688                time_t mtime=cJSON_printf(json,"modified");
7689                cJSON_Delete(json);
7690                if(re_cmd == NULL)
7691                    ChangeFile_modtime(fullname,mtime);
7692                else
7693                    ChangeFile_modtime(fullname_t,mtime);
7694                if(re_cmd)
7695                    free(fullname_t);
7696                free(fullname);
7697                free(serverpath);
7698            }
7699            else
7700            {
7701
7702                wd_DEBUG("upload %s failed\n",fullname);
7703                //write_system_log("error","uploadfile fail");
7704
7705                if(re_cmd)
7706                    free(fullname_t);
7707                free(path);
7708                free(fullname);
7709                free(serverpath);
7710                return status;
7711            }
7712        }
7713        else if(mtime_2 != -1 && mtime_2 != -2)
7714        {
7715            if(mtime_1 == mtime_2)
7716            {
7717                /*third param ture,ture=>if server file has exit ,will be overwrite*/
7718                if(re_cmd == NULL)
7719                    status=upload_file(fullname,serverpath,1,index);
7720                else
7721                    status=upload_file(fullname_t,serverpath,1,index);
7722                if(status == 0)
7723                {
7724                    cJSON *json = dofile(Con(TMP_R,upload_chunk_commit.txt));
7725                    time_t mtime=cJSON_printf(json,"modified");
7726                    cJSON_Delete(json);
7727                    if(re_cmd == NULL)
7728                        ChangeFile_modtime(fullname,mtime);
7729                    else
7730                        ChangeFile_modtime(fullname_t,mtime);
7731                    if(re_cmd)
7732                        free(fullname_t);
7733                    free(fullname);
7734                    free(serverpath);
7735                }
7736                else
7737                {
7738
7739                    wd_DEBUG("upload %s failed\n",fullname);
7740                    //write_system_log("error","uploadfile fail");
7741
7742                    if(re_cmd)
7743                        free(fullname_t);
7744                    free(path);
7745                    free(fullname);
7746                    free(serverpath);
7747                    return status;
7748                }
7749            }
7750            else
7751            {
7752                /*rename then upload*/
7753                /*third param false,false=>if server file has exit ,will not be overwrite*/
7754                if(re_cmd == NULL)
7755                    status=upload_file(fullname,serverpath,0,index);
7756                else
7757                    status=upload_file(fullname_t,serverpath,0,index);
7758                if(status == 0)
7759                {
7760                    char *newlocalname = NULL;
7761                    cJSON *json = dofile(Con(TMP_R,upload_chunk_commit.txt));
7762                    time_t mtime=cJSON_printf(json,"modified");
7763                    cJSON_Delete(json);
7764                    if(re_cmd == NULL)
7765                        newlocalname=change_local_same_file(fullname,index);
7766                    else
7767                        newlocalname=change_local_same_file(fullname_t,index);
7768                    if(newlocalname)
7769                        ChangeFile_modtime(newlocalname,mtime);
7770                    if(re_cmd)
7771                        free(fullname_t);
7772                    free(newlocalname);
7773                    free(fullname);
7774                    free(serverpath);
7775                }
7776                else
7777                {
7778
7779                    wd_DEBUG("upload %s failed\n",fullname);
7780
7781                    if(re_cmd)
7782                        free(fullname_t);
7783                    free(path);
7784                    free(fullname);
7785                    free(serverpath);
7786                    return status;
7787                }
7788            }
7789        }
7790        else
7791        {
7792            if(re_cmd)
7793                free(fullname_t);
7794            free(path);
7795            free(fullname);
7796            free(serverpath);
7797            return -1;
7798        }
7799#if 0
7800        if(mtime_1 == mtime_2 || mtime_2 == -1 ||asus_cfg.prule[index]->rule == 2)
7801        {
7802            /*third param ture,ture=>if server file has exit ,will be overwrite*/
7803            status=upload_file(fullname,serverpath,1,index);
7804            if(status == 0)
7805            {
7806                time_t mtime=cJSON_printf(dofile(Con(TMP_R,upload_chunk_commit.txt),"modified");
7807                ChangeFile_modtime(fullname,mtime);
7808                free(fullname);
7809                free(serverpath);
7810            }
7811            else
7812            {
7813
7814                wd_DEBUG("upload %s failed\n",fullname);
7815                //write_system_log("error","uploadfile fail");
7816
7817                free(path);
7818                free(fullname);
7819                free(serverpath);
7820                return status;
7821            }
7822        }
7823        else if(mtime_1 !=mtime_2 && mtime_2 != -1 && asus_cfg.prule[index]->rule ==0)
7824        {
7825            /*third param false,false=>if server file has exit ,will not be overwrite*/
7826            status=upload_file(fullname,serverpath,0,index);
7827            if(status == 0)
7828            {
7829                char *newlocalname;
7830                time_t mtime=cJSON_printf(dofile(Con(TMP_R,upload_chunk_commit.txt),"modified");
7831                newlocalname=change_local_same_file(fullname,index);
7832                if(newlocalname)
7833                    ChangeFile_modtime(newlocalname,mtime);
7834                free(newlocalname);
7835                free(fullname);
7836                free(serverpath);
7837            }
7838            else
7839            {
7840
7841                wd_DEBUG("upload %s failed\n",fullname);
7842                //write_system_log("error","uploadfile fail");
7843
7844                free(path);
7845                free(fullname);
7846                free(serverpath);
7847                return status;
7848            }
7849        }
7850        else if(mtime_2 == -2) //when the network is not conncet ,the curl resporen -2;
7851        {
7852            free(path);
7853            free(fullname);
7854            free(serverpath);
7855            return -1;
7856        }
7857#endif
7858    }
7859    else if(strcmp(cmd_name, "delete") == 0  || strcmp(cmd_name, "remove") == 0)
7860    {
7861        action_item *item;
7862        item = get_action_item_access("upload",fullname,g_pSyncList[index]->access_failed_list,index);
7863        if(item != NULL)
7864        {
7865            del_action_item("upload",item->path,g_pSyncList[index]->access_failed_list);
7866        }
7867
7868        sprintf(fullname,"%s/%s",path,filename);
7869        char *serverpath=localpath_to_serverpath(fullname,index);
7870
7871        char *serverpath_1=localpath_to_serverpath(path,index);
7872        if(is_server_exist(serverpath_1,serverpath,index) == 0)
7873        {
7874            my_free(serverpath_1);
7875            my_free(serverpath);
7876            free(fullname);
7877            free(path);
7878            return 0;
7879        }
7880
7881        status=api_delete(serverpath,index);
7882
7883        if(status != 0)
7884        {
7885
7886            wd_DEBUG("delete failed\n");
7887
7888            free(path);
7889            free(fullname);
7890            free(serverpath);
7891            //free(fullname);
7892            return status;
7893        }
7894        free(fullname);
7895        free(serverpath);
7896    }
7897    else if(strncmp(cmd_name, "move",strlen("move")) == 0 || strncmp(cmd_name, "rename",strlen("rename")) == 0)
7898    {
7899        if(strncmp(cmd_name, "move",strlen("move")) == 0)
7900        {
7901            mv_newpath = my_str_malloc((size_t)(strlen(path)+strlen(oldname)+2));
7902            mv_oldpath = my_str_malloc((size_t)(strlen(oldpath)+strlen(oldname)+2));
7903            sprintf(mv_newpath,"%s/%s",path,oldname);
7904            sprintf(mv_oldpath,"%s/%s",oldpath,oldname);
7905            free(oldpath);
7906            if(re_cmd)
7907            {
7908                fullname_t = (char *)malloc(sizeof(char)*(strlen(re_cmd)+strlen(oldname)+1));
7909                memset(fullname_t,'\0',strlen(re_cmd)+strlen(oldname)+1);
7910                sprintf(fullname_t,"%s%s",re_cmd,oldname);
7911            }
7912        }
7913        else
7914        {
7915            mv_newpath = my_str_malloc((size_t)(strlen(path)+strlen(newname)+2));
7916            mv_oldpath = my_str_malloc((size_t)(strlen(path)+strlen(oldname)+2));
7917            sprintf(mv_newpath,"%s/%s",path,newname);
7918            sprintf(mv_oldpath,"%s/%s",path,oldname);
7919            if(re_cmd)
7920            {
7921                fullname_t = (char *)malloc(sizeof(char)*(strlen(re_cmd)+strlen(newname)+1));
7922                memset(fullname_t,'\0',strlen(re_cmd)+strlen(newname)+1);
7923                sprintf(fullname_t,"%s%s",re_cmd,newname);
7924            }
7925        }
7926        if(strncmp(cmd_name, "rename",strlen("rename")) == 0)
7927        {
7928//            if(is_renamed)
7929//            {
7930                int exist=0;
7931                char *serverpath=localpath_to_serverpath(mv_newpath,index);
7932                char *serverpath_old=localpath_to_serverpath(mv_oldpath,index);
7933                /*if the newer name has exist in server,the server same name will be rename ,than rename the oldname to newer*/
7934                char *serverpath_1=localpath_to_serverpath(path,index);
7935                exist=is_server_exist(serverpath_1,serverpath,index);
7936                wd_DEBUG("exist = %d\n",exist);
7937                if(exist)
7938                {
7939                    char *newname;
7940                    newname=change_server_same_name(serverpath,index);
7941
7942                    status = api_move(serverpath,newname,index,0,NULL);
7943
7944
7945                    if(status == 0)
7946                    {
7947                        char *err_msg = write_error_message("server file %s is renamed to %s",serverpath,newname);
7948                        write_trans_excep_log(serverpath,3,err_msg);
7949                        free(err_msg);
7950                        //write_conflict_log(serverpath,newname,index);
7951                        status = api_move(serverpath_old,serverpath,index,1,fullname_t);
7952                    }
7953                    free(newname);
7954                }
7955                else
7956                {
7957                    status = api_move(serverpath_old,serverpath,index,1,fullname_t);
7958                }
7959                free(serverpath);
7960                free(serverpath_old);
7961                free(serverpath_1);
7962                if(re_cmd)
7963                    free(fullname_t);
7964                if(status != 0)
7965                {
7966
7967                    wd_DEBUG("move/rename failed\n");
7968                    //write_system_log("error","uploadfile fail");
7969                    free(mv_oldpath);
7970                    free(mv_newpath);
7971                    free(path);
7972                    return status;
7973                }
7974//            }
7975//            is_renamed = 0;
7976
7977//            if(test_if_dir(mv_newpath))
7978//            {
7979//                action_item *item;
7980//                item = get_action_item_access("upload",mv_oldpath,g_pSyncList[index]->access_failed_list,index);
7981//                if(item != NULL)
7982//                {
7983//                    char *name_access=parse_name_from_path(item->path);
7984//                    char *local_access;
7985//                    local_access=(char *)malloc(sizeof(char)*(strlen(name_access)+strlen(mv_newpath)+2));
7986//                    memset(local_access,0,sizeof(local_access));
7987//                    sprintf(local_access,"%s/%s",mv_newpath,name_access);
7988//                    char *server_access=localpath_to_serverpath(local_access,index);
7989//                    printf("local_access : %s\n,server_access : %s\n",local_access,server_access);
7990//                    status=upload_file(local_access,server_access,1,index);
7991//                    free(local_access);
7992//                    free(server_access);
7993//                    if(status == 0 || status == LOCAL_FILE_LOST || status == SERVER_SPACE_NOT_ENOUGH)
7994//                    {
7995//                        if(status == 0)
7996//                        {
7997//                            time_t mtime=cJSON_printf(dofile(Con(TMP_R,upload_chunk_commit.txt)),"modified");
7998//                            ChangeFile_modtime(local_access,mtime);
7999//                        }
8000//                        del_action_item("upload",item->path,g_pSyncList[index]->access_failed_list);
8001//                    }
8002//                    else
8003//                    {
8004//                        wd_DEBUG("upload %s failed\n",fullname);
8005//                        free(path);
8006//                        free(mv_oldpath);
8007//                        free(mv_newpath);
8008//                        return status;
8009    //                    char info[512];
8010    //                    sprintf(info,"createfile%s%s%s%s",CMD_SPLIT,mv_newpath,CMD_SPLIT,name_access);
8011    //                    pthread_mutex_lock(&mutex_socket);
8012    //                    add_socket_item(info);
8013    //                    pthread_mutex_unlock(&mutex_socket);
8014//                    }
8015//                }
8016//            }
8017//            if(access(filename,F_OK) != 0)
8018//            {
8019
8020//            }
8021
8022//            is_renamed = 1;
8023        }
8024        else  /*action : move*/
8025        {
8026            int exist = 0;
8027            int old_index;
8028            old_index=get_path_to_index(mv_oldpath);
8029            /*the move file is in other rules folder or root path*/
8030            /*index is 0 or 2
8031              0=>sync
8032              2=>upload
8033            */
8034            if(asus_cfg.prule[old_index]->rule == 1)
8035            {
8036                del_download_only_action_item("move",mv_oldpath,g_pSyncList[old_index]->download_only_socket_head);
8037            }
8038
8039            char *serverpath=localpath_to_serverpath(mv_newpath,index);
8040            char *serverpath_old=localpath_to_serverpath(mv_oldpath,index);
8041            char *serverpath_1=localpath_to_serverpath(path,index);
8042            exist=is_server_exist(serverpath_1,serverpath,index);
8043            if(exist)
8044            {
8045                char *newname;
8046                newname=change_server_same_name(serverpath,index);
8047
8048                status = api_move(serverpath,newname,index,0,NULL);
8049
8050                if(status == 0)
8051                {
8052                    char *err_msg = write_error_message("server file %s is renamed to %s",serverpath,newname);
8053                    write_trans_excep_log(serverpath,3,err_msg);
8054                    free(err_msg);
8055                    //write_conflict_log(serverpath,newname,index);
8056                    status = api_move(serverpath_old,serverpath,index,1,fullname_t);
8057                }
8058
8059                free(newname);
8060            }
8061            else
8062            {
8063                status = api_move(serverpath_old,serverpath,index,1,fullname_t);
8064            }
8065            free(serverpath);
8066            free(serverpath_old);
8067            free(serverpath_1);
8068            if(re_cmd)
8069                free(fullname_t);
8070            if(status != 0)
8071            {
8072
8073                wd_DEBUG("move/rename failed\n");
8074                //write_system_log("error","uploadfile fail");
8075
8076                free(path);
8077                free(mv_oldpath);
8078                free(mv_newpath);
8079                return status;
8080            }
8081        }
8082        free(mv_oldpath);
8083        free(mv_newpath);
8084
8085    }
8086    else if( strcmp(cmd_name,"dragfolder") == 0)
8087    {
8088        char info[512];
8089        memset(info,0,sizeof(info));
8090        if(re_cmd == NULL)
8091        {
8092            sprintf(fullname,"%s/%s",path,filename);
8093            sprintf(info,"createfolder%s%s%s%s",CMD_SPLIT,path,CMD_SPLIT,filename);
8094        }
8095        else
8096        {
8097            sprintf(fullname,"%s%s",re_cmd,filename);
8098            sprintf(info,"createfolder%s%s%s%s",CMD_SPLIT,re_cmd,CMD_SPLIT,filename);
8099        }
8100
8101
8102        pthread_mutex_lock(&mutex_socket);
8103        add_socket_item(info);
8104        pthread_mutex_unlock(&mutex_socket);
8105        deal_dragfolder_to_socketlist(fullname,index);
8106        if(re_cmd)
8107            free(fullname_t);
8108        free(fullname);
8109//        sprintf(fullname,"%s/%s",path,filename);
8110//        //printf("fullname is %s\n",fullname);
8111//        status=dragfolder(fullname,index);
8112//        free(fullname);
8113//        if(status != 0)
8114//        {
8115
8116//            wd_DEBUG("dragfolder failed status = %d\n",status);
8117
8118//            free(path);
8119//            return status;
8120//        }
8121    }
8122    else if(strcmp(cmd_name, "createfolder") == 0)
8123    {
8124        int exist;
8125
8126        sprintf(fullname,"%s/%s",path,filename);
8127        char *serverpath=localpath_to_serverpath(fullname,index);
8128        if(re_cmd != NULL)
8129            sprintf(fullname_t,"%s%s",re_cmd,filename);
8130
8131        if(re_cmd == NULL)
8132            status=api_create_folder(fullname,serverpath);
8133        else
8134            status=api_create_folder(fullname_t,serverpath);
8135        if(status==0)
8136        {
8137            exist=parse_create_folder(Con(TMP_R,create_folder.txt));
8138            if(exist)
8139            {
8140#if 0
8141                char *newname;
8142                newname=change_server_same_name(serverpath,index);
8143
8144                status = api_move(serverpath,newname,index,0,NULL);
8145
8146                free(newname);
8147                if(status ==0)
8148                {
8149                    if(re_cmd == NULL)
8150                        status=api_create_folder(fullname,serverpath);
8151                    else
8152                        status=api_create_folder(fullname_t,serverpath);
8153                }
8154#endif
8155            }
8156            if(re_cmd)
8157                free(fullname_t);
8158            free(serverpath);
8159            free(fullname);
8160        }
8161        else
8162        {
8163
8164            wd_DEBUG("createFolder failed status = %d\n",status);
8165
8166            free(path);
8167            return status;
8168        }
8169    }
8170    free(path);
8171    return 0;
8172
8173}
8174//int first_dragfolder = 0 ;
8175//int get_local_list(char *dir)
8176//{
8177//    Local *localnode;
8178//    localnode=Find_Floor_Dir(dir);
8179//    while(localnode->folderlist != NULL)
8180//        get_local_list(localnode->folderlist->path);
8181//}
8182//int dragfolder_test(char *dir,int index)
8183//{
8184//    if(first_dragfolder == 0)
8185//    {
8186//        get_local_list(dir);
8187//    }
8188//}
8189int deal_dragfolder_to_socketlist(char *dir,int index)
8190{
8191    wd_DEBUG("dir = %s\n",dir);
8192
8193    int status;
8194    struct dirent *ent = NULL;
8195    char info[512];
8196    memset(info,0,sizeof(info));
8197    DIR *pDir;
8198    pDir=opendir(dir);
8199    if(pDir != NULL)
8200    {
8201        while((ent=readdir(pDir)) != NULL)
8202        {
8203            if(ent->d_name[0] == '.')
8204                continue;
8205            if(!strcmp(ent->d_name,".") || !strcmp(ent->d_name,".."))
8206                continue;
8207            char *fullname;
8208            fullname = (char *)malloc(sizeof(char)*(strlen(dir)+strlen(ent->d_name)+2));
8209            memset(fullname,'\0',strlen(dir)+strlen(ent->d_name)+2);
8210
8211            sprintf(fullname,"%s/%s",dir,ent->d_name);
8212            if(test_if_dir(fullname) == 1)
8213            {
8214                sprintf(info,"createfolder%s%s%s%s",CMD_SPLIT,dir,CMD_SPLIT,ent->d_name);
8215                pthread_mutex_lock(&mutex_socket);
8216                add_socket_item(info);
8217                pthread_mutex_unlock(&mutex_socket);
8218                status = deal_dragfolder_to_socketlist(fullname,index);
8219            }
8220            else
8221            {
8222                sprintf(info,"createfile%s%s%s%s",CMD_SPLIT,dir,CMD_SPLIT,ent->d_name);
8223                pthread_mutex_lock(&mutex_socket);
8224                add_socket_item(info);
8225                pthread_mutex_unlock(&mutex_socket);
8226            }
8227            free(fullname);
8228        }
8229        closedir(pDir);
8230        return 0;
8231    }
8232}
8233int dragfolder_rename(char *dir,int index,time_t server_mtime)
8234{
8235    wd_DEBUG("change dir = %s mtime\n",dir);
8236
8237    int status;
8238    struct dirent *ent = NULL;
8239    DIR *pDir;
8240    pDir=opendir(dir);
8241    if(pDir != NULL)
8242    {
8243        while((ent=readdir(pDir)) != NULL)
8244        {
8245            if(ent->d_name[0] == '.')
8246                continue;
8247            if(!strcmp(ent->d_name,".") || !strcmp(ent->d_name,".."))
8248                continue;
8249            char *fullname;
8250            fullname = (char *)malloc(sizeof(char)*(strlen(dir)+strlen(ent->d_name)+2));
8251            memset(fullname,'\0',strlen(dir)+strlen(ent->d_name)+2);
8252
8253            sprintf(fullname,"%s/%s",dir,ent->d_name);
8254            if(test_if_dir(fullname) == 1)
8255            {
8256
8257                status = dragfolder_rename(fullname,index,server_mtime);
8258
8259            }
8260            else
8261            {
8262                status=ChangeFile_modtime(fullname,server_mtime);
8263            }
8264            free(fullname);
8265        }
8266        closedir(pDir);
8267        return 0;
8268    }
8269}
8270int dragfolder_old_dir(char *dir,int index,char *old_dir)
8271{
8272
8273    wd_DEBUG("dir = %s\n",dir);
8274
8275    int status;
8276    int exist;
8277    struct dirent *ent = NULL;
8278    DIR *pDir;
8279    pDir=opendir(dir);
8280    if(pDir != NULL)
8281    {
8282        //char *serverpath=localpath_to_serverpath(old_dir,index);
8283        status=api_create_folder(dir,old_dir);
8284        if(status != 0)
8285        {
8286
8287            wd_DEBUG("Create %s failed\n",old_dir);
8288
8289            //return -1;
8290            closedir(pDir);
8291            return status;
8292        }
8293        exist=parse_create_folder(Con(TMP_R,create_folder.txt));
8294        if(exist)
8295        {
8296            char *newname;
8297            newname=change_server_same_name(old_dir,index);
8298
8299            status = api_move(old_dir,newname,index,0,NULL);
8300
8301            free(newname);
8302            if(status ==0)
8303            {
8304                status=api_create_folder(dir,old_dir);
8305            }
8306            if(status != 0)
8307            {
8308                closedir(pDir);
8309                return status;
8310            }
8311        }
8312        //free(serverpath);
8313        while((ent=readdir(pDir)) != NULL)
8314        {
8315            if(ent->d_name[0] == '.')
8316                continue;
8317            if(!strcmp(ent->d_name,".") || !strcmp(ent->d_name,".."))
8318                continue;
8319            char *fullname;
8320            fullname = (char *)malloc(sizeof(char)*(strlen(dir)+strlen(ent->d_name)+2));
8321            memset(fullname,'\0',strlen(dir)+strlen(ent->d_name)+2);
8322            sprintf(fullname,"%s/%s",dir,ent->d_name);
8323
8324            char *fullname_r;
8325            fullname_r = (char *)malloc(sizeof(char)*(strlen(old_dir)+strlen(ent->d_name)+2));
8326            memset(fullname_r,'\0',strlen(old_dir)+strlen(ent->d_name)+2);
8327            sprintf(fullname_r,"%s/%s",old_dir,ent->d_name);
8328
8329            status = check_localpath_is_socket(index,dir,ent->d_name,fullname);
8330            if(status == 1)
8331            {
8332                wd_DEBUG("the %s is socket ,so do nothing\n",fullname);
8333                free(fullname);
8334                free(fullname_r);
8335                continue;
8336            }
8337
8338            if(test_if_dir(fullname) == 1)
8339            {
8340
8341                status = dragfolder_old_dir(fullname,index,fullname_r);
8342                if(status != 0)
8343                {
8344
8345                    wd_DEBUG("CreateFolder %s failed\n",fullname);
8346
8347                    free(fullname);
8348                    free(fullname_r);
8349                    closedir(pDir);
8350                    return status;
8351                }
8352            }
8353            else
8354            {
8355                char *serverpath_1=localpath_to_serverpath(fullname_r,index);
8356                status=upload_file(fullname,serverpath_1,1,index);
8357                if(status == 0)
8358                {
8359                    cJSON *json = dofile(Con(TMP_R,upload_chunk_commit.txt));
8360                    time_t mtime=cJSON_printf(json,"modified");
8361                    cJSON_Delete(json);
8362                    ChangeFile_modtime(fullname,mtime);
8363
8364                }
8365                else if(status == SERVER_SPACE_NOT_ENOUGH)
8366                {
8367
8368                    wd_DEBUG("upload %s failed,server space is not enough!\n",fullname);
8369
8370                }
8371                else if(status == LOCAL_FILE_LOST)
8372                {
8373
8374                    wd_DEBUG("upload %s failed,local file lost!\n",fullname);
8375
8376                }
8377                else
8378                {
8379
8380                    wd_DEBUG("upload %s failed\n",fullname);
8381
8382                    free(serverpath_1);
8383                    free(fullname);
8384                    free(fullname_r);
8385                    return status;
8386                }
8387            }
8388            free(fullname);
8389            free(fullname_r);
8390        }
8391        closedir(pDir);
8392        return 0;
8393    }
8394}
8395int dragfolder(char *dir,int index)
8396{
8397
8398    wd_DEBUG("dir = %s\n",dir);
8399
8400    int status;
8401    int exist;
8402    struct dirent *ent = NULL;
8403    DIR *pDir;
8404    pDir=opendir(dir);
8405    if(pDir != NULL)
8406    {
8407        char *serverpath=localpath_to_serverpath(dir,index);
8408        status=api_create_folder(dir,serverpath);
8409        if(status != 0)
8410        {
8411
8412            wd_DEBUG("Create %s failed\n",serverpath);
8413
8414            //return -1;
8415            closedir(pDir);
8416            return status;
8417        }
8418        exist=parse_create_folder(Con(TMP_R,create_folder.txt));
8419        if(exist)
8420        {
8421            char *newname;
8422            newname=change_server_same_name(serverpath,index);
8423
8424            status = api_move(serverpath,newname,index,0,NULL);
8425
8426            free(newname);
8427            if(status ==0)
8428            {
8429                status=api_create_folder(dir,serverpath);
8430            }
8431            if(status != 0)
8432            {
8433                closedir(pDir);
8434                return status;
8435            }
8436        }
8437        free(serverpath);
8438        while((ent=readdir(pDir)) != NULL)
8439        {
8440            if(ent->d_name[0] == '.')
8441                continue;
8442            if(!strcmp(ent->d_name,".") || !strcmp(ent->d_name,".."))
8443                continue;
8444            char *fullname;
8445            fullname = (char *)malloc(sizeof(char)*(strlen(dir)+strlen(ent->d_name)+2));
8446            memset(fullname,'\0',strlen(dir)+strlen(ent->d_name)+2);
8447
8448            sprintf(fullname,"%s/%s",dir,ent->d_name);
8449
8450            /*
8451             fix :below question
8452             a.rename local path A,and server is not exist;
8453             b.create a file 'a' in A/;
8454             final-->the server will exist 'a' and 'a(1)';
8455            */
8456            status = check_localpath_is_socket(index,dir,ent->d_name,fullname);
8457            if(status == 1)
8458            {
8459                wd_DEBUG("the %s is socket ,so do nothing\n",fullname);
8460                free(fullname);
8461                continue;
8462            }
8463            if(test_if_dir(fullname) == 1)
8464            {
8465
8466                status = dragfolder(fullname,index);
8467                if(status != 0)
8468                {
8469
8470                    wd_DEBUG("CreateFolder %s failed\n",fullname);
8471
8472                    free(fullname);
8473                    closedir(pDir);
8474                    return status;
8475                }
8476            }
8477            else
8478            {
8479                char *serverpath_1=localpath_to_serverpath(fullname,index);
8480                status=upload_file(fullname,serverpath_1,1,index);
8481                if(status == 0)
8482                {
8483                    cJSON *json = dofile(Con(TMP_R,upload_chunk_commit.txt));
8484                    time_t mtime=cJSON_printf(json,"modified");
8485                    cJSON_Delete(json);
8486                    ChangeFile_modtime(fullname,mtime);
8487
8488                }
8489                else if(status == SERVER_SPACE_NOT_ENOUGH)
8490                {
8491
8492                    wd_DEBUG("upload %s failed,server space is not enough!\n",fullname);
8493
8494                }
8495                else if(status == LOCAL_FILE_LOST)
8496                {
8497
8498                    wd_DEBUG("upload %s failed,local file lost!\n",fullname);
8499
8500                }
8501                else
8502                {
8503
8504                    wd_DEBUG("upload %s failed\n",fullname);
8505
8506                    free(serverpath_1);
8507                    free(fullname);
8508                    return status;
8509                }
8510            }
8511            free(fullname);
8512        }
8513        closedir(pDir);
8514        return 0;
8515    }
8516}
8517
8518int parse_create_folder(char *filename)
8519{
8520    FILE *fp;
8521    fp=fopen(filename,"r");
8522    if(fp == NULL)
8523    {
8524        wd_DEBUG("filename %s is not exit\n",filename);
8525        return 0;
8526    }
8527    char tmp[256]="\0";
8528    fgets(tmp,256,fp);
8529    fclose(fp);
8530#if 0
8531    if(strstr(tmp,"error") != NULL)
8532    {
8533        if(strstr(tmp,"already exists.") != NULL)
8534        {
8535            return 1;
8536        }
8537    }
8538#endif
8539    if(strstr(tmp,"403") != NULL)
8540    {
8541        return 1;
8542    }
8543    return 0;
8544
8545}
8546
8547int get_path_to_index(char *path)
8548{
8549    int i;
8550    char *root_path = NULL;
8551    char *temp = NULL;
8552    root_path = my_str_malloc(512);
8553
8554    temp = my_nstrchr('/',path,4);
8555    if(temp == NULL)
8556    {
8557        sprintf(root_path,"%s",path);
8558    }
8559    else
8560    {
8561        snprintf(root_path,strlen(path)-strlen(temp)+1,"%s",path);
8562    }
8563
8564    for(i=0;i<asus_cfg.dir_number;i++)
8565    {
8566        if(!strcmp(root_path,asus_cfg.prule[i]->base_path))
8567            break;
8568    }
8569
8570    wd_DEBUG("get_path_to_index root_path = %s\n",root_path);
8571
8572    free(root_path);
8573
8574    return i;
8575}
8576
8577void sig_handler (int signum)
8578{
8579    //Getmysyncfolder *gf;
8580    //printf("sig_handler !\n");
8581    //sleep(5);
8582
8583    wd_DEBUG("signal is %d\n",signum);
8584    switch (signum)
8585    {
8586#if TOKENFILE
8587    case SIGTERM:case SIGUSR2:
8588        {
8589            int mountflag = 0;
8590            if(signum == SIGUSR2)
8591            {
8592
8593                wd_DEBUG("signal is SIGUSR2\n");
8594
8595                FILE *fp;
8596                fp = fopen("/proc/mounts","r");
8597                char a[10240];
8598                memset(a,'\0',sizeof(a));
8599                fread(a,10240,1,fp);
8600                fclose(fp);
8601                if(strstr(a,"/dev/sd"))
8602                {
8603                    mountflag = 1;
8604                }
8605
8606            }
8607            if(signum == SIGTERM || mountflag == 0)
8608            {
8609                stop_progress = 1;
8610                exit_loop = 1;
8611
8612                /*updata /tmp/dropbox.conf*/
8613                /*
8614                system("sh /tmp/dropbox_get_nvram");
8615                sleep(2);
8616                if(create_webdav_conf_file(&asus_cfg_stop) == -1)
8617                {
8618                    wd_DEBUG("create_webdav_conf_file fail\n");
8619                    return;
8620                }
8621                */
8622
8623#ifndef NVRAM_
8624                char cmd_p[128] = {0};
8625                sprintf(cmd_p,"sh %s",DropBox_Get_Nvram);
8626                system(cmd_p);
8627                //system("sh /tmp/dropbox_get_nvram");
8628                sleep(2);
8629                if(create_webdav_conf_file(&asus_cfg_stop) == -1)
8630                {
8631                    wd_DEBUG("create_dropbox_conf_file fail\n");
8632                    return;
8633                }
8634
8635#else
8636                if(convert_nvram_to_file_mutidir(CONFIG_PATH,&asus_cfg_stop) == -1)
8637                {
8638                    wd_DEBUG("convert_nvram_to_file fail\n");
8639                    //nvram_set(NVRAM_USBINFO,"");
8640                    //nvram_commit();
8641                    write_to_nvram("","db_tokenfile");
8642                    return;
8643                }
8644#endif
8645                if(asus_cfg_stop.dir_number == 0)
8646                {
8647                    char *filename;
8648                    filename = my_str_malloc(strlen(asus_cfg.prule[0]->base_path)+20+1);
8649                    sprintf(filename,"%s/.dropbox_tokenfile",asus_cfg.prule[0]->base_path);
8650                    remove(filename);
8651                    free(filename);
8652
8653                    remove(g_pSyncList[0]->conflict_file);
8654                    //write_to_wd_tokenfile("");
8655
8656#ifdef NVRAM_
8657                    write_to_nvram("","db_tokenfile");
8658#else
8659                    write_to_wd_tokenfile("");
8660#endif
8661
8662                }
8663                else
8664                {
8665                    if(asus_cfg_stop.dir_number != asus_cfg.dir_number)
8666                    {
8667                        parse_config_mutidir(CONFIG_PATH,&asus_cfg_stop);
8668
8669                        rewrite_tokenfile_and_nv();
8670                    }
8671                }
8672                //pthread_mutex_unlock(&mutex);
8673                sighandler_finished = 1;
8674                pthread_cond_signal(&cond);
8675                pthread_cond_signal(&cond_socket);
8676                pthread_cond_signal(&cond_log);
8677            }
8678            else
8679            {
8680                disk_change = 1;
8681                sighandler_finished = 1;
8682            }
8683            break;
8684        }
8685#else
8686    case SIGTERM:
8687        {
8688            wd_DEBUG("signal is SIGTERM\n");
8689            stop_progress = 1;
8690            exit_loop = 1;
8691
8692            //sighandler_finished = 1;
8693            pthread_cond_signal(&cond);
8694            pthread_cond_signal(&cond_socket);
8695            pthread_cond_signal(&cond_log);
8696
8697            break;
8698        }
8699#endif
8700    case SIGPIPE:  // delete user
8701        wd_DEBUG("signal is SIGPIPE\n");
8702        signal(SIGPIPE, SIG_IGN);
8703        break;
8704
8705    default:
8706        break;
8707    }
8708}
8709
8710void* sigmgr_thread(){
8711    sigset_t   waitset;
8712    //siginfo_t  info;
8713    int        sig;
8714    int        rc;
8715    pthread_t  ppid = pthread_self();
8716
8717    pthread_detach(ppid);
8718
8719    sigemptyset(&waitset);
8720    sigaddset(&waitset,SIGUSR1);
8721    sigaddset(&waitset,SIGUSR2);
8722    sigaddset(&waitset,SIGTERM);
8723    sigaddset(&waitset,SIGPIPE);
8724
8725    while (1)  {
8726        rc = sigwait(&waitset, &sig);
8727        if (rc != -1) {
8728
8729            wd_DEBUG("sigwait() fetch the signal - %d\n", sig);
8730
8731            sig_handler(sig);
8732        } else {
8733            wd_DEBUG("sigwaitinfo() returned err: %d; %s\n", errno, strerror(errno));
8734        }
8735    }
8736}
8737void stop_process_clean_up(){
8738#if TOKENFILE
8739    unlink("/tmp/notify/usb/dropbox_client");
8740#endif
8741    pthread_cond_destroy(&cond);
8742    pthread_cond_destroy(&cond_socket);
8743    pthread_cond_destroy(&cond_log);
8744
8745    //free_disk_struc(&follow_disk_info_start);
8746    //free_disk_struc(&config_disk_info_start);
8747
8748    if(!access_token_expired)
8749        unlink(general_log);
8750}
8751char *change_local_same_file(char *oldname,int index)
8752{
8753    cJSON *json;
8754    char *newname;
8755    if (access(Con(TMP_R,upload_chunk_commit.txt),R_OK) ==0)
8756    {
8757        json=dofile(Con(TMP_R,upload_chunk_commit.txt));
8758        if(json)
8759        {
8760            char *localpath;
8761            newname=cJSON_parse_name(json);
8762            localpath=serverpath_to_localpath(newname,index);
8763            if(strcmp(newname,oldname)!=0)
8764            {
8765#ifndef TEST
8766                add_action_item("rename",localpath,g_pSyncList[index]->server_action_list);
8767                rename(oldname,localpath);
8768
8769                char *err_msg = write_error_message("server has exist %s file ,rename local %s to %s",oldname,oldname,localpath);
8770                write_trans_excep_log(oldname,3,err_msg);
8771                free(err_msg);
8772
8773                //write_conflict_log(oldname,newname,index);
8774                //free(localpath);
8775#endif
8776                cJSON_Delete(json);
8777                return localpath;
8778            }
8779            else
8780            {
8781                cJSON_Delete(json);
8782                return localpath;
8783            }
8784        }
8785        else
8786        {
8787            /*the file contents is error*/
8788            return NULL;
8789        }
8790    }
8791
8792
8793}
8794
8795void check_tokenfile()
8796{
8797#if TOKENFILE
8798        if(get_tokenfile_info()==-1)
8799        {
8800            wd_DEBUG("\nget_tokenfile_info failed\n");
8801            exit(-1);
8802        }
8803        check_config_path(1);
8804#endif
8805}
8806int check_link_internet()
8807{
8808    struct timeval now;
8809    struct timespec outtime;
8810    int link_flag = 0;
8811    int i;
8812#if defined NVRAM_
8813    while(!link_flag && !exit_loop)
8814    {
8815#ifndef USE_TCAPI
8816        char *link_internet = strdup(nvram_safe_get("link_internet"));
8817#else
8818        char tmp[MAXLEN_TCAPI_MSG] = {0};
8819        tcapi_get(WANDUCK, "link_internet", tmp);
8820        char *link_internet = my_str_malloc(strlen(tmp)+1);
8821        sprintf(link_internet,"%s",tmp);
8822#endif
8823        link_flag = atoi(link_internet);
8824        if(!link_flag)
8825        {
8826            for(i=0;i<asus_cfg.dir_number;i++)
8827            {
8828                write_log(S_ERROR,"Network Connection Failed","",i);
8829            }
8830
8831            pthread_mutex_lock(&mutex);
8832            if(!exit_loop)
8833            {
8834                gettimeofday(&now, NULL);
8835                outtime.tv_sec = now.tv_sec + 20;
8836                outtime.tv_nsec = now.tv_usec * 1000;
8837                pthread_cond_timedwait(&cond, &mutex, &outtime);
8838            }
8839            pthread_mutex_unlock(&mutex);
8840        }
8841            //sleep(20);
8842        free(link_internet);
8843    }
8844#else
8845
8846    do{
8847        char cmd_p[128] ={0};
8848        sprintf(cmd_p,"sh %s",DropBox_Get_Nvram_Link);
8849        system(cmd_p);
8850        sleep(2);
8851
8852        char nv[64] = {0};
8853        FILE *fp;
8854        fp = fopen(TMP_NVRAM_VL,"r");
8855        fgets(nv,sizeof(nv),fp);
8856        fclose(fp);
8857
8858        link_flag = atoi(nv);
8859        if(!link_flag)
8860        {
8861            for(i=0;i<asus_cfg.dir_number;i++)
8862            {
8863                write_log(S_ERROR,"Network Connection Failed","",i);
8864            }
8865            pthread_mutex_lock(&mutex);
8866            if(!exit_loop)
8867            {
8868                gettimeofday(&now, NULL);
8869                outtime.tv_sec = now.tv_sec + 20;
8870                outtime.tv_nsec = now.tv_usec * 1000;
8871                pthread_cond_timedwait(&cond, &mutex, &outtime);
8872            }
8873            pthread_mutex_unlock(&mutex);
8874        }
8875            //sleep(20);
8876        //free(nv);
8877
8878    }while(!link_flag && !exit_loop);
8879#endif
8880
8881    for(i=0;i<asus_cfg.dir_number;i++)
8882    {
8883        write_log(S_SYNC,"","",i);
8884    }
8885}
8886#ifdef OAuth1
8887int do_auth()
8888{
8889    int curl_res=0;
8890    int auth_ok=0;
8891    int error_time = 0;
8892    int have_error_log=0;
8893    int i;
8894    do
8895    {
8896        wd_DEBUG("##########begin auth############\n");
8897//        if(error_time > 5 && have_error_log != 1)
8898//        {
8899//            if(asus_cfg.dir_number > 0)
8900//                write_log(S_ERROR,"Network Connection Failed","",0);
8901//            have_error_log = 1;
8902//        }
8903
8904        if(error_time > 5)
8905        {
8906            check_link_internet();
8907            error_time = 0;
8908        }
8909        if(exit_loop)
8910            return auth_ok;
8911        curl_res = get_request_token();
8912
8913        if(curl_res == -1)
8914        {
8915            error_time++;
8916
8917            //usleep(5000*1000);
8918            //enter_sleep_time(5);
8919            continue;
8920        }
8921        curl_res = open_login_page_first();
8922        if(curl_res == -1)
8923        {
8924            error_time++;
8925
8926            //usleep(5000*1000);
8927            //enter_sleep_time(5);
8928            continue;
8929        }
8930        curl_res = login_first();
8931        if(curl_res == -1)
8932        {
8933            error_time++;
8934
8935            //usleep(5000*1000);
8936            //enter_sleep_time(5);
8937            continue;
8938        }
8939        curl_res = login_second();
8940        if(curl_res == -1)
8941        {
8942            error_time++;
8943
8944            //usleep(5000*1000);
8945            //enter_sleep_time(5);
8946            continue;
8947        }
8948        curl_res = login_second_submit();
8949        if(curl_res == -1)
8950        {
8951            error_time++;
8952
8953            //usleep(5000*1000);
8954            //enter_sleep_time(5);
8955            continue;
8956        }
8957
8958        curl_res=get_access_token();
8959        if(curl_res == -1 || curl_res > 0)
8960        {
8961            if(curl_res == -1)
8962            {
8963                for(i=0;i<asus_cfg.dir_number;i++)
8964                {
8965                    write_log(S_ERROR,"Authentication Failed","",i);
8966                }
8967
8968                return auth_ok;
8969            }
8970            else
8971                error_time++;
8972            //usleep(5000*1000);
8973            //enter_sleep_time(5);
8974            continue;
8975        }
8976        auth_ok=1;
8977        //}while(0);
8978    }while(auth_ok != 1 && exit_loop != 1);
8979    wd_DEBUG("##########auth over############\n");
8980
8981    return auth_ok;
8982}
8983#endif
8984int f_exists(const char *path)	// note: anything but a directory
8985{
8986        struct stat st;
8987        return (stat(path, &st) == 0) && (!S_ISDIR(st.st_mode));
8988}
8989void clean_sys_data()
8990{
8991    if(f_exists("/tmp/smartsync/.logs/dropbox"))
8992        unlink("/tmp/smartsync/.logs/dropbox");
8993    //my_mkdir("/tmp/smartsync_app");
8994    //system("touch /tmp/smartsync_app/dropbox_client_start");
8995}
8996
8997void db_disbale_access_token()
8998{
8999    my_free(auth->oauth_token);
9000    my_free(auth);
9001}
9002
9003int main(int args,char *argc[])
9004{
9005#ifndef TEST
9006    clean_sys_data();
9007    int auth_flag = 0;
9008    //setenv("MALLOC_TRACE","memlog",1);
9009    //mtrace();
9010    sigset_t bset,oset;
9011    pthread_t sig_thread;
9012    /*
9013    int res;
9014    res = curl_global_init(CURL_GLOBAL_DEFAULT);
9015*/
9016    curl_global_init(CURL_GLOBAL_ALL);
9017    sigemptyset(&bset);
9018    sigaddset(&bset,SIGUSR1);
9019    sigaddset(&bset,SIGUSR2);
9020    sigaddset(&bset,SIGTERM);
9021    sigaddset(&bset,SIGPIPE);
9022
9023    if( pthread_sigmask(SIG_BLOCK,&bset,&oset) == -1)
9024        wd_DEBUG("!! Set pthread mask failed\n");
9025
9026    if( pthread_create(&sig_thread,NULL,(void *)sigmgr_thread,NULL) != 0)
9027    {
9028        wd_DEBUG("thread creation failder\n");
9029        exit(-1);
9030    }
9031    init_globar_var();
9032
9033#if TOKENFILE
9034    write_notify_file(NOTIFY_PATH,SIGUSR2);
9035#ifndef NVRAM_
9036     my_mkdir("/opt/etc/.smartsync");
9037#ifndef WIN_32
9038    write_get_nvram_script_va("link_internet");
9039    write_get_nvram_script();
9040    char cmd_p[128] ={0};
9041    sprintf(cmd_p,"sh %s",DropBox_Get_Nvram);
9042    //system("sh /tmp/dropbox_get_nvram");
9043    system(cmd_p);
9044    sleep(2);
9045#endif
9046#else
9047    create_shell_file();
9048#endif
9049#endif
9050    //signal(SIGPIPE,sig_handler);
9051    //signal(SIGTERM,sig_handler);
9052
9053    //while(1)
9054    //sleep(2);
9055
9056
9057    auth=(Auth *)malloc(sizeof(Auth));
9058    memset(auth,0,sizeof(auth));
9059
9060
9061    read_config();
9062#ifdef OAuth1
9063    auth_flag = do_auth();
9064#else
9065    auth_flag = 1;
9066    auth->oauth_token = my_str_malloc(strlen(asus_cfg.pwd)+1);
9067    sprintf(auth->oauth_token,"%s",asus_cfg.pwd);
9068#endif
9069
9070    if(auth_flag)
9071    {
9072        check_tokenfile();
9073
9074        if(no_config == 0)
9075        {
9076            run();
9077        }
9078
9079        pthread_join(sig_thread,NULL);
9080        stop_process_clean_up();
9081    }
9082    db_disbale_access_token();
9083    curl_global_cleanup();
9084
9085    //detect_client();
9086////#ifdef NVRAM_
9087//    if(!detect_process("asuswebstorage")&&!detect_process("webdav_client")&&!detect_process("ftpclient"))
9088//    {
9089//        system("killall  -9 inotify &");
9090//        //DEBUG("webdav kill inotify\n");
9091//    }
9092//    else
9093//    {
9094//        //DEBUG("webdav did not kill inotify\n");
9095//    }
9096////#endif
9097#else
9098    /*
9099    //setenv("MALLOC_TRACE","memlog",1);
9100    //mtrace()
9101    info=(Info *)malloc(sizeof(Info));
9102    memset(info,0,sizeof(info));
9103    auth=(Auth *)malloc(sizeof(Auth));
9104    memset(auth,0,sizeof(auth));
9105    strcpy(info->usr,"m15062346679@163.com");
9106    strcpy(info->pwd,"123abc,./");
9107    */
9108    //printf("%s\n",get_confilicted_name_case("/tmp/mnt/ASD/new_inotify/cookie_login(case-conflict).txt",0));
9109    //printf("%s\n",get_confilicted_name_first("/tmp/mnt/ASD/new_inotify/cookie_login.txt",0));
9110    //is_server_enough("/111");
9111    //get_upload_id();
9112    /*
9113    get_request_token();
9114    open_login_page_first();
9115    login_first();
9116    login_second();
9117    get_access_token();
9118    */
9119    //cgi_init();
9120    //api_accout_info();
9121    //init_globar_var();
9122    //read_config();
9123    //create_sync_list();
9124    //api_metadata_test("/Photo");
9125    //api_metadata_test("/main");
9126    //api_move("/11.txt","/fb.txt",0,0,NULL);
9127    //api_download();
9128    //api_upload_put("/tmp/mnt/ASD/My410Sync/Music/ssss",oauth_url_escape("/My410Sync/Music/ssss"),0,0);
9129    //api_upload_post();//failing
9130    // ChangeFile_modtime("/tmp/mnt/ASD/lighttpd_0.0.0.1_mipsel.ipk",112);
9131    //api_upload_put_test("/tmp/mnt/ASD/aicloud_1.0.0.4_mipsel.ipk","/aicloud_1.0.0.4_mipsel.ipk",1);
9132    //is_server_enough("/tmp/mnt/ASD/GPL_aicloud.0.0.2.tar.gz");
9133    upload_file("/tmp/mnt/ASD/My410Sync/aicloud_1.0.0.10-0-gd8a47cb_mipsel.ipk",oauth_url_escape("/aicloud_1.0.0.10-0-gd8a47cb_mipsel.ipk"),0,0);
9134    //change_local_same_file("111",1);
9135    //printf("name=%s\n",oauth_url_escape("111%20aaa"));
9136    //api_getmtime("/111/51515151",dofile);
9137    //get_upload_id();
9138    //api_upload_chunk_commit("IuKV3xLGtsaW3zDc9ax3Og","aicloud_1.0.0.5_mipsel.ipk");
9139    //api_delete("/fb.txt",0);
9140    //api_create_folder("/tmp/mnt/ASD/music/","/music");
9141    //parse_create_folder("/tmp/dropbox/create_folder_header.txt");
9142
9143    /*
9144    int i;
9145    for(i=0;i<asus_cfg.dir_number;i++)
9146    {
9147        int status;
9148        g_pSyncList[i]->ServerRootNode = create_server_treeroot();
9149        status = browse_to_tree(asus_cfg.prule[i]->rooturl,g_pSyncList[i]->ServerRootNode);
9150
9151        SearchServerTree(g_pSyncList[i]->ServerRootNode);
9152        free_server_tree(g_pSyncList[i]->ServerRootNode);
9153    }
9154*/
9155#endif
9156    /*
9157    int status;
9158    ServerRootNode = create_server_treeroot();
9159    status = browse_to_tree(" ",ServerRootNode);
9160    SearchServerTree(ServerRootNode);
9161    free_server_tree(ServerRootNode);
9162    */
9163    /*
9164    CURL *curl;
9165    CURLcode res;
9166    FILE *fp;
9167    char *header;
9168    static const char buf[]="Expect:";
9169    header=makeAuthorize();
9170    struct curl_slist *headerlist=NULL;
9171    curl=curl_easy_init();
9172    headerlist=curl_slist_append(headerlist,header);
9173    if(curl){
9174            if(strstr(argc[1],"1")!=NULL)
9175                curl_easy_setopt(curl,CURLOPT_URL,"https://api.dropbox.com/1/oauth/request_token");
9176            else if((strstr(argc[1],"2")!=NULL))
9177                curl_easy_setopt(curl,CURLOPT_URL,"https://api.dropbox.com/1/oauth/access_token");
9178            else if((strstr(argc[1],"3")!=NULL))
9179                curl_easy_setopt(curl,CURLOPT_URL,"https://api.dropbox.com/1/account/info");
9180            curl_easy_setopt(curl,CURLOPT_VERBOSE,1);
9181            curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headerlist);
9182            //curl_easy_setopt(curl,CURLOPT_POSTFIELDS,"");
9183            //curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,0);
9184            if(strstr(argc[1],"1")!=NULL)
9185                fp=fopen("delete_1.txt","w");
9186            else if((strstr(argc[1],"2")!=NULL))
9187                fp=fopen("delete_2.txt","w");
9188            else if((strstr(argc[1],"3")!=NULL))
9189                fp=fopen("delete_3.txt","w");
9190            curl_easy_setopt(curl,CURLOPT_WRITEDATA,fp);
9191            res=curl_easy_perform(curl);
9192
9193            curl_easy_cleanup(curl);
9194            fclose(fp);
9195            if(res!=0){
9196                printf("delete [%d] failed!\n",res);
9197                return -1;
9198            }
9199    }
9200    free(header);
9201    */
9202}
9203#ifdef OAuth1
9204int get_request_token(){
9205
9206    CURL *curl;
9207    CURLcode res;
9208    FILE *fp;
9209    char *header;
9210    static const char buf[]="Expect:";
9211    header=makeAuthorize(1);
9212    struct curl_slist *headerlist=NULL;
9213    curl=curl_easy_init();
9214    headerlist=curl_slist_append(headerlist,header);
9215    if(curl){
9216        curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,0L);
9217        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
9218        curl_easy_setopt(curl,CURLOPT_URL,"https://api.dropbox.com/1/oauth/request_token");
9219        CURL_DEBUG;
9220        curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headerlist);
9221        //curl_easy_setopt(curl,CURLOPT_POSTFIELDS,"");
9222        //curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,0);
9223        fp=fopen(Con(TMP_R,data_1.txt),"w");
9224        curl_easy_setopt(curl,CURLOPT_WRITEDATA,fp);
9225        res=curl_easy_perform(curl);
9226
9227        curl_easy_cleanup(curl);
9228        fclose(fp);
9229        curl_slist_free_all(headerlist);
9230        if(res!=0){
9231            free(header);
9232            wd_DEBUG("get_request_token [%d] failed!\n",res);
9233            return -1;
9234        }
9235    }
9236    free(header);
9237
9238    if(parse(Con(TMP_R,data_1.txt),1) == -1)
9239        return -1;
9240    return 0;
9241}
9242
9243int cgi_init(char *query)
9244        //int cgi_init()
9245{
9246    //char query[]="oauth_token_secret=b1wa7jwkjc4u1ji&oauth_token=34zjc44boelj1zh&uid=150377145";
9247    int len, nel;
9248    char *q, *name, *value;
9249    /* Parse into individualassignments */
9250    q = query;
9251    len = strlen(query);
9252    nel = 1;
9253    while (strsep(&q, "&"))
9254        nel++;
9255    for (q = query; q< (query + len);) {
9256        value = name = q;
9257        /* Skip to next assignment */
9258        for (q += strlen(q); q < (query +len) && !*q; q++);
9259        /* Assign variable */
9260        name = strsep(&value,"=");
9261        if(strcmp(name,"oauth_token_secret")==0)
9262            strcpy(auth->oauth_token_secret,value);
9263        else if(strcmp(name,"oauth_token")==0)
9264            strcpy(auth->oauth_token,value);
9265        else if(strcmp(name,"uid")==0)
9266            auth->uid=atoi(value);
9267
9268    }
9269    wd_DEBUG("CGI[value] :%s %s %d\n", auth->oauth_token_secret,auth->oauth_token,auth->uid);
9270    return 0;
9271}
9272
9273int parse(char *filename,int flag)
9274{
9275
9276    char *p=NULL;
9277    char p1[56];
9278    char *p3=NULL;
9279    char *p4=NULL;
9280    FILE *fp=fopen(filename,"r");
9281    char tmp_data[256]="\0";
9282    fgets(tmp_data,sizeof(tmp_data),fp);
9283    wd_DEBUG("%s\n",tmp_data);
9284    if(strstr(tmp_data,"error")==NULL && tmp_data != NULL&&strlen(tmp_data) > 0)
9285    {
9286        switch(flag)
9287        {
9288        case 1:
9289            p=strchr(tmp_data,'&');
9290            memset(p1,'\0',sizeof(p1));
9291            strncpy(p1,tmp_data,strlen(tmp_data)-strlen(p));
9292            p3=strchr(p,'=');
9293            p3++;
9294            strcpy(auth->tmp_oauth_token,p3);
9295            p3=NULL;
9296            p4=strchr(p1,'=');
9297            p4++;
9298            snprintf(auth->tmp_oauth_token_secret,strlen(p4)+1,"%s",p4);
9299            //strncpy(auth->tmp_oauth_token_secret,p4,strlen(p4));
9300            wd_DEBUG("auth->tmp_oauth_token=%s\nauth->tmp_oauth_token_secret=%s\n",auth->tmp_oauth_token,auth->tmp_oauth_token_secret);
9301            break;
9302        case 2:
9303            cgi_init(tmp_data);
9304            break;
9305        default:
9306            break;
9307        }
9308        fclose(fp);
9309        return 0;
9310    }
9311    else
9312    {
9313        fclose(fp);
9314        return -1;
9315    }
9316
9317
9318}
9319#endif
9320char *makeAuthorize(int flag)
9321{
9322    char *header = NULL;
9323    char http_basic_authentication[] = "Authorization: Bearer ";
9324    char URI_Query_Parameter[] = "access_token=";
9325    int header_len ;
9326    switch(flag)
9327    {
9328    case 1:
9329        header_len = strlen(http_basic_authentication) + strlen(auth->oauth_token) +1;
9330        header = my_str_malloc(header_len);
9331        sprintf(header,"%s%s",http_basic_authentication,auth->oauth_token);
9332        break;
9333    case 2:
9334        header_len = strlen(URI_Query_Parameter) + strlen(auth->oauth_token) +1;
9335        header = my_str_malloc(header_len);
9336        sprintf(header,"%s%s",URI_Query_Parameter,auth->oauth_token);
9337        break;
9338    default:
9339        break;
9340    }
9341    //sprintf(header,"%s%s",http_basic_authentication,auth->oauth_token);
9342    //sprintf(header,"%s%s","access_token=","XDwYx52HJBYAAAAAAAABcY809z2fKmv_xai8IZXzYmZKcIADF9elZ55nmeUNR_m2");
9343    wd_DEBUG("makeAuthorize>%s\n",header);
9344    return header;
9345}
9346#ifdef OAuth1
9347char *makeAuthorize(int flag)
9348{
9349    char *header = NULL;
9350    header = (char *)malloc(sizeof(char*)*1024);
9351    char header_signature_method[64];
9352    char header_timestamp[64];
9353    char header_nonce[64];
9354    char *header_signature = NULL;
9355    char prekey[128];
9356    long long int sec;
9357
9358    char query_string[1024];
9359    char *incode_string = NULL;
9360    char *sha1_string = NULL;
9361
9362    //snprintf(header_signature_method,64,"%s","HMAC-SHA1");
9363    snprintf(header_signature_method,64,"%s","PLAINTEXT");
9364    if(flag==1)
9365        snprintf(prekey,128,"%s","5vq8jog8wgpx1p0&");
9366    else if(flag==2)
9367        //snprintf(prekey,128,"%s%s","5vq8jog8wgpx1p0&","YXG59mgidir11f6b");
9368        snprintf(prekey,128,"%s%s","5vq8jog8wgpx1p0&",auth->tmp_oauth_token_secret);
9369    else if(flag==3)
9370    {
9371#ifndef TEST
9372        snprintf(prekey,128,"%s&%s","5vq8jog8wgpx1p0",auth->oauth_token_secret);
9373#else
9374        snprintf(prekey,128,"%s","5vq8jog8wgpx1p0&efghhkqrt68qta2");
9375#endif
9376    }
9377    else if(flag==4)
9378    {
9379#ifndef TEST
9380        snprintf(prekey,128,"%s&%s","5vq8jog8wgpx1p0",auth->oauth_token_secret);
9381#else
9382        snprintf(prekey,128,"%s","5vq8jog8wgpx1p0&efghhkqrt68qta2");
9383#endif
9384    }
9385    //snprintf(prekey,128,"%s&%s","5vq8jog8wgpx1p0",auth->oauth_token_secret);
9386    //snprintf(prekey,128,"%s","5vq8jog8wgpx1p0&efghhkqrt68qta2");
9387    sec = time((time_t *)NULL);
9388    snprintf(header_timestamp,64,"%lld",sec);
9389    snprintf(header_nonce,64,"%lld",sec);
9390    /*
9391    //hmac_sha1
9392    snprintf( query_string,1024,"oauth_consumer_key=qah4ku73k3qmigj&oauth_nonce=%s&oauth_signature_method=HMAC-SHA1&oauth_timestamp=%s&oauth_version=1.0",header_nonce,header_timestamp);
9393    //snprintf( query_string,1024,"POST&https://api.dropbox.com/1/oauth/request_token&oauth_consumer_key",header_nonce,header_signature_method,header_timestamp);
9394    incode_string = oauth_url_escape(query_string);
9395    if(NULL == incode_string)
9396    {
9397        //handle_error(S_URL_ESCAPE_FAIL,"makeAuthorize");
9398        return NULL;
9399    }
9400    char *httpsUrl="https://api.dropbox.com/1/oauth/request_token";
9401    char *test_key = NULL;
9402    test_key=(char *)malloc(sizeof(char *)*(strlen(query_string)+4+4+strlen(httpsUrl)));
9403    memset(test_key,'\0',sizeof(test_key));
9404    sprintf(test_key,"POST&%s&%s",httpsUrl,incode_string);
9405    sha1_string = oauth_sign_hmac_sha1(test_key,prekey);
9406
9407    if(NULL == sha1_string)
9408    {
9409        //handle_error(S_SHA1_FAIL,"makeAuthorize");
9410        //my_free(incode_string);
9411        return NULL;
9412    }
9413
9414    header_signature = oauth_url_escape(sha1_string);
9415    if(NULL == header_signature)
9416    {
9417       // handle_error(S_URL_ESCAPE_FAIL,"makeAuthorize");
9418       // my_free(incode_string);
9419        //my_free(sha1_string);
9420        return NULL;
9421    }
9422*/
9423    header_signature=oauth_sign_plaintext(NULL,prekey);
9424    //snprintf(header,1024,"Authorization:signature_method=\"%s\",timestamp=\"%s\",nonce=%s,signature=\"%s\"",header_signature_method,header_timestamp,header_nonce,header_signature);
9425    if(flag==1)
9426        snprintf(header,1024,"Authorization:OAuth oauth_consumer_key=\"%s\",oauth_signature_method=\"%s\",oauth_signature=\"%s\",oauth_timestamp=\"%s\",oauth_nonce=\"%s\",oauth_version=\"1.0\""
9427                 ,"qah4ku73k3qmigj",header_signature_method,header_signature,header_timestamp,header_nonce);
9428    else if(flag==2)
9429//        snprintf(header,1024,"Authorization:OAuth oauth_consumer_key=\"%s\",oauth_token=\"%s\",oauth_signature_method=\"%s\",oauth_signature=\"%s\",oauth_timestamp=\"%s\",oauth_nonce=\"%s\",oauth_version=\"1.0\""
9430 //                ,"qah4ku73k3qmigj","AIZpfQv7qYwuDotM",header_signature_method,header_signature,header_timestamp,header_nonce);
9431    snprintf(header,1024,"Authorization:OAuth oauth_consumer_key=\"%s\",oauth_token=\"%s\",oauth_signature_method=\"%s\",oauth_signature=\"%s\",oauth_timestamp=\"%s\",oauth_nonce=\"%s\",oauth_version=\"1.0\""
9432             ,"qah4ku73k3qmigj",auth->tmp_oauth_token,header_signature_method,header_signature,header_timestamp,header_nonce);
9433    else if(flag==3)
9434    {
9435#ifndef TEST
9436        snprintf(header,1024,"Authorization:OAuth oauth_consumer_key=\"%s\",oauth_token=\"%s\",oauth_signature_method=\"%s\",oauth_signature=\"%s\",oauth_timestamp=\"%s\",oauth_nonce=\"%s\",oauth_version=\"1.0\""
9437                 ,"qah4ku73k3qmigj",auth->oauth_token,header_signature_method,header_signature,header_timestamp,header_nonce);
9438#else
9439        snprintf(header,1024,"Authorization:OAuth oauth_consumer_key=\"%s\",oauth_token=\"%s\",oauth_signature_method=\"%s\",oauth_signature=\"%s\",oauth_timestamp=\"%s\",oauth_nonce=\"%s\",oauth_version=\"1.0\""
9440                 ,"qah4ku73k3qmigj","8m9knhps2zgaon9",header_signature_method,header_signature,header_timestamp,header_nonce);
9441#endif
9442    }
9443    else if(flag==4)
9444    {
9445#ifndef TEST
9446        snprintf(header,1024,"oauth_consumer_key=%s&oauth_token=%s&oauth_signature_method=%s&oauth_signature=%s&oauth_timestamp=%s&oauth_nonce=%s&oauth_version=1.0"
9447                 ,"qah4ku73k3qmigj",auth->oauth_token,header_signature_method,header_signature,header_timestamp,header_nonce);
9448#else
9449        snprintf(header,1024,"oauth_consumer_key=%s&oauth_token=%s&oauth_signature_method=%s&oauth_signature=%s&oauth_timestamp=%s&oauth_nonce=%s&oauth_version=1.0"
9450                 ,"qah4ku73k3qmigj","8m9knhps2zgaon9",header_signature_method,header_signature,header_timestamp,header_nonce);
9451#endif
9452    }
9453    //snprintf(header,1024,"oauth_consumer_key=%s&oauth_token=%s&oauth_signature_method=%s&oauth_signature=%s&oauth_timestamp=%s&oauth_nonce=%s&oauth_version=1.0"
9454    //,"qah4ku73k3qmigj",auth->oauth_token,header_signature_method,header_signature,header_timestamp,header_nonce);
9455    //snprintf(header,1024,"oauth_consumer_key=%s&oauth_token=%s&oauth_signature_method=%s&oauth_signature=%s&oauth_timestamp=%s&oauth_nonce=%s&oauth_version=1.0"
9456    //,"qah4ku73k3qmigj","8m9knhps2zgaon9",header_signature_method,header_signature,header_timestamp,header_nonce);
9457
9458    // my_free(incode_string);
9459    //my_free(sha1_string);
9460    free(header_signature);
9461    //free(test_key);
9462    return header;
9463}
9464#endif
9465Browse *browseFolder(char *URL){
9466    //printf("browseFolder URL = %s\n",URL);
9467    int status;
9468    int i=0;
9469
9470    Browse *browse = getb(Browse);
9471    if( NULL == browse )
9472    {
9473        wd_DEBUG("create memery error\n");
9474        exit(-1);
9475    }
9476    memset(browse,0,sizeof(Browse));
9477
9478    TreeFolderList = (CloudFile *)malloc(sizeof(CloudFile));
9479    memset(TreeFolderList,0,sizeof(CloudFile));
9480    TreeFileList = (CloudFile *)malloc(sizeof(CloudFile));
9481    memset(TreeFileList,0,sizeof(CloudFile));
9482
9483    TreeFolderList->href = NULL;
9484    TreeFileList->href = NULL;
9485
9486    TreeFolderTail = TreeFolderList;
9487    TreeFileTail = TreeFileList;
9488    TreeFolderTail->next = NULL;
9489    TreeFileTail->next = NULL;
9490
9491    status = api_metadata(URL,dofile);
9492    if(status != 0)
9493    {
9494        free_CloudFile_item(TreeFolderList);
9495        free_CloudFile_item(TreeFileList);
9496        TreeFolderList = NULL;
9497        TreeFileList = NULL;
9498        free(browse);
9499        //printf("get Cloud Info ERROR! \n");
9500        return NULL;
9501    }
9502
9503    browse->filelist = TreeFileList;
9504    browse->folderlist = TreeFolderList;
9505
9506    CloudFile *de_foldercurrent,*de_filecurrent;
9507    de_foldercurrent = TreeFolderList->next;
9508    de_filecurrent = TreeFileList->next;
9509    while(de_foldercurrent != NULL){
9510        ++i;
9511        de_foldercurrent = de_foldercurrent->next;
9512    }
9513    browse->foldernumber = i;
9514    i = 0;
9515    while(de_filecurrent != NULL){
9516        ++i;
9517        de_filecurrent = de_filecurrent->next;
9518    }
9519    browse->filenumber = i;
9520    return browse;
9521}
9522
9523queue_t queue_create ()
9524{
9525    queue_t q;
9526    q = malloc (sizeof (struct queue_struct));
9527    if (q == NULL)
9528        exit (-1);
9529
9530    q->head = q->tail = NULL;
9531    return q;
9532}
9533void queue_enqueue (queue_entry_t d, queue_t q)
9534{
9535    d->next_ptr = NULL;
9536    if (q->tail)
9537    {
9538        q->tail->next_ptr = d;
9539        q->tail = d;
9540    }
9541    else
9542    {
9543        q->head = q->tail = d;
9544    }
9545}
9546
9547queue_entry_t  queue_dequeue_t (queue_t q)
9548{
9549    queue_entry_t first = q->head;
9550
9551    if (first)
9552    {
9553        if(first->re_cmd == NULL)
9554        {
9555            q->head = first->next_ptr;
9556            if (q->head == NULL)
9557            {
9558                q->tail = NULL;
9559            }
9560            first->next_ptr = NULL;
9561        }
9562        else
9563        {
9564            if(access(first->re_cmd,0) == 0)
9565            {
9566                q->head = first->next_ptr;
9567                if (q->head == NULL)
9568                {
9569                    q->tail = NULL;
9570                }
9571                first->next_ptr = NULL;
9572            }
9573            else
9574            {
9575                if(first->is_first == 0)
9576                {
9577                    first->is_first++;
9578                    return NULL;
9579                }
9580                else
9581                {
9582                    q->head = first->next_ptr;
9583                    if (q->head == NULL)
9584                    {
9585                        q->tail = NULL;
9586                    }
9587                    first->next_ptr = NULL;
9588                }
9589            }
9590        }
9591
9592    }
9593    return first;
9594}
9595queue_entry_t  queue_dequeue (queue_t q)
9596{
9597    queue_entry_t first = q->head;
9598
9599    if (first)
9600    {
9601        q->head = first->next_ptr;
9602        if (q->head == NULL)
9603        {
9604            q->tail = NULL;
9605        }
9606        first->next_ptr = NULL;
9607    }
9608    return first;
9609}
9610void queue_destroy (queue_t q)
9611{
9612    if (q != NULL)
9613    {
9614        while (q->head != NULL)
9615        {
9616            queue_entry_t next = q->head;
9617            q->head = next->next_ptr;
9618            next->next_ptr = NULL;
9619
9620#if MEM_POOL_ENABLE
9621            mem_free(next->cmd_name);
9622            mem_free(next->re_cmd);
9623            mem_free (next);
9624#else
9625            if(next->re_cmd)
9626                free(next->re_cmd);
9627            free(next->cmd_name);
9628            free (next);
9629#endif
9630        }
9631        q->head = q->tail = NULL;
9632        free (q);
9633    }
9634}
9635action_item *get_action_item_access(const char *action,const char *path,action_item *head,int index){
9636
9637    action_item *p;
9638    p = head->next;
9639
9640    while(p != NULL)
9641    {
9642        if(asus_cfg.prule[index]->rule == 1)
9643        {
9644
9645        }
9646        else
9647        {
9648            //char *path_old=strrchr(path,'/')
9649            if(!strcmp(p->action,action) && !strncmp(p->path,path,strlen(path)))
9650            {
9651                return p;
9652            }
9653        }
9654        p = p->next;
9655    }
9656    wd_DEBUG("can not find action item_1\n");
9657    return NULL;
9658}
9659action_item *check_action_item(const char *action,const char *oldpath,action_item *head,int index,const char *newpath)
9660{
9661    action_item *p;
9662    p = head->next;
9663
9664    while(p != NULL)
9665    {
9666        char *pTemp_t=(char *)malloc(sizeof(char)*(strlen(p->path)+1+1));
9667        char *oldpath_t=(char *)malloc(sizeof(char)*(strlen(oldpath)+1+1));
9668        memset(pTemp_t,'\0',strlen(p->path)+1+1);
9669        memset(oldpath_t,'\0',strlen(oldpath)+1+1);
9670        sprintf(pTemp_t,"%s/",p->path);
9671        sprintf(oldpath_t,"%s/",oldpath);
9672        char *p_t = NULL;
9673
9674        if(!strcmp(p->action,action) && (p_t=strstr(pTemp_t,oldpath_t)) != NULL)
9675        {
9676            if(strlen(oldpath_t)<strlen(pTemp_t))
9677            {
9678                p_t+=strlen(oldpath);
9679                char *p_tt=(char *)malloc(sizeof(char)*(strlen(p_t)+1));
9680                memset(p_tt,'\0',strlen(p_t)+1);
9681                sprintf(p_tt,"%s",p_t);
9682                free(p->path);
9683                p->path = (char *)malloc(sizeof(char) * (strlen(newpath)+strlen(p_tt) + 1));
9684                memset(p->path,'\0',strlen(newpath)+strlen(p_tt) + 1);
9685                sprintf(p->path,"%s%s",newpath,p_tt);
9686                free(p_tt);
9687            }
9688            else
9689            {
9690                free(p->path);
9691                p->path = (char *)malloc(sizeof(char) * (strlen(newpath) + 1));
9692                sprintf(p->path,"%s",newpath);
9693            }
9694            //wd_DEBUG("p->action:%s\n p->path:%s\n",p->action,p->path);
9695        }
9696
9697        free(pTemp_t);
9698        free(oldpath_t);
9699        p = p->next;
9700    }
9701    return NULL;
9702}
9703action_item *get_action_item(const char *action,const char *path,action_item *head,int index){
9704
9705    action_item *p;
9706    p = head->next;
9707
9708    while(p != NULL)
9709    {
9710        if(asus_cfg.prule[index]->rule == 1)
9711        {
9712            if(!strcmp(p->path,path))
9713            {
9714                return p;
9715            }
9716        }
9717        else
9718        {
9719            if(!strcmp(p->action,action) && !strcmp(p->path,path))
9720            {
9721                return p;
9722            }
9723        }
9724        p = p->next;
9725    }
9726    wd_DEBUG("can not find action item_2\n");
9727    return NULL;
9728}
9729int del_action_item(const char *action,const char *path,action_item *head){
9730
9731    action_item *p1,*p2;
9732    p1 = head->next;
9733    p2 = head;
9734
9735    while(p1 != NULL)
9736    {
9737        if( !strcmp(p1->action,action) && !strcmp(p1->path,path))
9738        {
9739            p2->next = p1->next;
9740            free(p1->action);
9741            free(p1->path);
9742            free(p1);
9743            return 0;
9744        }
9745        p2 = p1;
9746        p1 = p1->next;
9747    }
9748    wd_DEBUG("can not find action item_3\n");
9749    return 1;
9750}
9751int add_action_item(const char *action,const char *path,action_item *head){
9752
9753    wd_DEBUG("add_action_item,action = %s,path = %s\n",action,path);
9754
9755    action_item *p1,*p2;
9756
9757    p1 = head;
9758
9759    p2 = (action_item *)malloc(sizeof(action_item));
9760    memset(p2,'\0',sizeof(action_item));
9761    p2->action = (char *)malloc(sizeof(char)*(strlen(action)+1));
9762    p2->path = (char *)malloc(sizeof(char)*(strlen(path)+1));
9763    memset(p2->action,'\0',strlen(action)+1);
9764    memset(p2->path,'\0',strlen(path)+1);
9765
9766    sprintf(p2->action,"%s",action);
9767    sprintf(p2->path,"%s",path);
9768
9769    while(p1->next != NULL)
9770        p1 = p1->next;
9771
9772    p1->next = p2;
9773    p2->next = NULL;
9774
9775    wd_DEBUG("add action item OK!\n");
9776
9777    return 0;
9778}
9779void del_download_only_action_item(const char *action,const char *path,action_item *head)
9780{
9781    //printf("del_sync_item action=%s,path=%s\n",action,path);
9782    if(head == NULL)
9783    {
9784        return;
9785    }
9786    action_item *p1, *p2;
9787    char *cmp_name;
9788    char *p1_cmp_name;
9789    p1 = head->next;
9790    p2 = head;
9791
9792    cmp_name = my_str_malloc((size_t)(strlen(path)+2));
9793    sprintf(cmp_name,"%s/",path);    //add for delete folder and subfolder in download only socket list
9794
9795    while(p1 != NULL)
9796    {
9797        p1_cmp_name = my_str_malloc((size_t)(strlen(p1->path)+2));
9798        sprintf(p1_cmp_name,"%s/",p1->path);      //add for delete folder and subfolder in download only socket list
9799        //printf("del_download_only_sync_item  p1->name = %s\n",p1->name);
9800        //printf("del_download_only_sync_item  cmp_name = %s\n",cmp_name);
9801        if(strstr(p1_cmp_name,cmp_name) != NULL)
9802        {
9803            p2->next = p1->next;
9804            free(p1->action);
9805            free(p1->path);
9806            free(p1);
9807            //printf("del sync item ok\n");
9808            //break;
9809            p1 = p2->next;
9810        }
9811        else
9812        {
9813            p2 = p1;
9814            p1 = p1->next;
9815        }
9816        free(p1_cmp_name);
9817    }
9818
9819    free(cmp_name);
9820    //printf("del sync item fail\n");
9821}
9822void free_action_item(action_item *head){
9823
9824    action_item *point;
9825    point = head->next;
9826
9827    while(point != NULL)
9828    {
9829        head->next = point->next;
9830        free(point->action);
9831        free(point->path);
9832        free(point);
9833        point = head->next;
9834    }
9835    free(head);
9836}
9837action_item *create_action_item_head(){
9838
9839    action_item *head;
9840
9841    head = (action_item *)malloc(sizeof(action_item));
9842    if(head == NULL)
9843    {
9844        wd_DEBUG("create memory error!\n");
9845        exit(-1);
9846    }
9847    memset(head,'\0',sizeof(action_item));
9848    head->next = NULL;
9849
9850    return head;
9851}
9852int add_all_download_only_socket_list(char *cmd,const char *dir,int index)
9853{
9854    struct dirent* ent = NULL;
9855    char *fullname;
9856    int fail_flag = 0;
9857    //char error_message[256];
9858
9859    DIR *dp = opendir(dir);
9860
9861    if(dp == NULL)
9862    {
9863
9864        wd_DEBUG("opendir %s fail",dir);
9865
9866        //sprintf(error_message,"opendir %s fail",dir);
9867        //handle_error(S_OPENDIR_FAIL,error_message);
9868        fail_flag = 1;
9869        return -1;
9870    }
9871
9872    add_action_item(cmd,dir,g_pSyncList[index]->download_only_socket_head);
9873
9874    while (NULL != (ent=readdir(dp)))
9875    {
9876
9877        if(ent->d_name[0] == '.')
9878            continue;
9879        if(!strcmp(ent->d_name,".") || !strcmp(ent->d_name,".."))
9880            continue;
9881
9882        fullname = my_str_malloc((size_t)(strlen(dir)+strlen(ent->d_name)+2));
9883        //memset(error_message,0,sizeof(error_message));
9884        //memset(&createfolder,0,sizeof(Createfolder));
9885
9886        sprintf(fullname,"%s/%s",dir,ent->d_name);
9887
9888        if( test_if_dir(fullname) == 1)
9889        {
9890            add_all_download_only_socket_list("createfolder",fullname,index);
9891        }
9892        else
9893        {
9894            add_action_item("createfile",fullname,g_pSyncList[index]->download_only_socket_head);
9895        }
9896        free(fullname);
9897    }
9898
9899    closedir(dp);
9900
9901    return (fail_flag == 1) ? -1 : 0;
9902}
9903int add_all_download_only_dragfolder_socket_list(const char *dir,int index)
9904{
9905    struct dirent* ent = NULL;
9906    char *fullname;
9907    int fail_flag = 0;
9908    //char error_message[256];
9909
9910    DIR *dp = opendir(dir);
9911
9912    if(dp == NULL)
9913    {
9914
9915        wd_DEBUG("opendir %s fail",dir);
9916
9917        //sprintf(error_message,"opendir %s fail",dir);
9918        //handle_error(S_OPENDIR_FAIL,error_message);
9919        fail_flag = 1;
9920        return -1;
9921    }
9922
9923    while (NULL != (ent=readdir(dp)))
9924    {
9925
9926        if(ent->d_name[0] == '.')
9927            continue;
9928        if(!strcmp(ent->d_name,".") || !strcmp(ent->d_name,".."))
9929            continue;
9930
9931        fullname = my_str_malloc((size_t)(strlen(dir)+strlen(ent->d_name)+2));
9932        //memset(error_message,0,sizeof(error_message));
9933        //memset(&createfolder,0,sizeof(Createfolder));
9934
9935        sprintf(fullname,"%s/%s",dir,ent->d_name);
9936
9937        if( test_if_dir(fullname) == 1)
9938        {
9939            //add_action_item("createfolder",fullname,g_pSyncList[index]->dragfolder_action_list);
9940            add_action_item("createfolder",fullname,g_pSyncList[index]->download_only_socket_head);
9941            add_all_download_only_dragfolder_socket_list(fullname,index);
9942        }
9943        else
9944        {
9945            //add_action_item("createfile",fullname,g_pSyncList[index]->dragfolder_action_list);
9946            add_action_item("createfile",fullname,g_pSyncList[index]->download_only_socket_head);
9947        }
9948        free(fullname);
9949    }
9950
9951    closedir(dp);
9952
9953    return (fail_flag == 1) ? -1 : 0;
9954}
9955int test_if_download_temp_file(char *filename)
9956{
9957    char file_suffix[9];
9958    char *temp_suffix = ".asus.td";
9959    memset(file_suffix,0,sizeof(file_suffix));
9960    char *p = filename;
9961
9962    if(strstr(filename,temp_suffix))
9963    {
9964        strcpy(file_suffix,p+(strlen(filename)-strlen(temp_suffix)));
9965
9966        //printf(" %s file_suffix is %s\n",filename,file_suffix);
9967
9968        if(!strcmp(file_suffix,temp_suffix))
9969            return 1;
9970    }
9971
9972    return 0;
9973
9974}
9975int do_unfinished(int index){
9976    if(exit_loop)
9977    {
9978        return 0;
9979    }
9980
9981    wd_DEBUG("*************do_unfinished*****************\n");
9982
9983    action_item *p,*p1;
9984    p = g_pSyncList[index]->unfinished_list->next;
9985    int ret;
9986
9987    while(p != NULL)
9988    {
9989        //printf("unfinished_list\n");
9990        //printf("p->path = %s\n",p->path);
9991        //printf("p->action = %s\n",p->action);
9992        if(!strcmp(p->action,"download"))
9993        {
9994            CloudFile *filetmp = NULL;
9995            filetmp = get_CloudFile_node(g_pSyncList[index]->ServerRootNode,p->path,0x2);
9996            //printf("filetmp->href = %s\n",filetmp->href);
9997            if(filetmp == NULL)   //if filetmp == NULL,it means server has deleted filetmp
9998            {
9999
10000                wd_DEBUG("filetmp is NULL\n");
10001
10002                p1 = p->next;
10003                del_action_item("download",p->path,g_pSyncList[index]->unfinished_list);
10004                p = p1;
10005                continue;
10006            }
10007            char *localpath;
10008            localpath = serverpath_to_localpath(filetmp->href,index);
10009
10010            wd_DEBUG("localpath = %s\n",localpath);
10011
10012            if(is_local_space_enough(filetmp,index))
10013            {
10014                add_action_item("createfile",localpath,g_pSyncList[index]->server_action_list);
10015                ret = api_download(localpath,filetmp->href,index);
10016                if (ret == 0)
10017                {
10018                    ChangeFile_modtime(localpath,filetmp->mtime);
10019                    p1 = p->next;
10020                    del_action_item("download",filetmp->href,g_pSyncList[index]->unfinished_list);
10021                    p = p1;
10022                }
10023                else
10024                {
10025
10026                    wd_DEBUG("download %s failed",filetmp->href);
10027
10028                    p = p->next;
10029                    //return ret;
10030                }
10031            }
10032            else
10033            {
10034                write_log(S_ERROR,"local space is not enough!","",index);
10035                p = p->next;
10036            }
10037            free(localpath);
10038        }
10039        /*
10040        else if(!strcmp(p->action,"upload"))
10041        {
10042            p1 = p->next;
10043            char *serverpath;
10044            serverpath = localpath_to_serverpath(p->path,index);
10045            char *path_temp;
10046            path_temp = my_str_malloc(strlen(p->path)+1);
10047            sprintf(path_temp,"%s",p->path);
10048            ret = upload_file(p->path,serverpath,1,index);
10049#ifdef DEBUG
10050            printf("********* uploadret = %d\n",ret);
10051#endif
10052            if(ret == 0)
10053            {
10054                //char *serverpath;
10055                //serverpath = localpath_to_serverpath(p->path,index);
10056                //printf("serverpath = %s\n",serverpath);
10057                time_t mtime=cJSON_printf(dofile("/tmp/upload_chunk_commit.txt"),"modified");
10058                ChangeFile_modtime(p->path,mtime);
10059                //free(serverpath);
10060                //p1 = p->next;
10061                del_action_item("upload",p->path,g_pSyncList[index]->unfinished_list);
10062                del_action_item("upload",p->path,g_pSyncList[index]->up_space_not_enough_list);
10063                p = p1;
10064            }
10065            else if(ret == LOCAL_FILE_LOST)
10066            {
10067                //p1 = p->next;
10068                del_action_item("upload",p->path,g_pSyncList[index]->unfinished_list);
10069                p = p1;
10070            }
10071            else
10072            {
10073#ifdef DEBUG
10074                printf("upload %s failed",p->path);
10075#endif
10076                p = p->next;
10077            }
10078            free(serverpath);
10079            free(path_temp);
10080        }
10081        */
10082        else
10083        {
10084            p = p->next;
10085        }
10086    }
10087
10088    p = g_pSyncList[index]->up_space_not_enough_list->next;
10089    while(p != NULL)
10090    {
10091        p1 = p->next;
10092
10093        wd_DEBUG("up_space_not_enough_list\n");
10094
10095        char *serverpath;
10096        serverpath = localpath_to_serverpath(p->path,index);
10097        char *path_temp;
10098        path_temp = my_str_malloc(strlen(p->path)+1);
10099        sprintf(path_temp,"%s",p->path);
10100        ret = upload_file(p->path,serverpath,1,index);
10101
10102        wd_DEBUG("########### uploadret = %d\n",ret);
10103
10104        if(ret == 0)
10105        {
10106            //char *serverpath;
10107            //serverpath = localpath_to_serverpath(p->path,index);
10108            cJSON *json = dofile(Con(TMP_R,upload_chunk_commit.txt));
10109            time_t mtime=cJSON_printf(json,"modified");
10110            cJSON_Delete(json);
10111            ChangeFile_modtime(p->path,mtime);
10112            //free(serverpath);
10113            //p1 = p->next;
10114            del_action_item("upload",p->path,g_pSyncList[index]->unfinished_list);
10115            del_action_item("upload",p->path,g_pSyncList[index]->up_space_not_enough_list);
10116            p = p1;
10117        }
10118        else if(ret == LOCAL_FILE_LOST)
10119        {
10120            //p1 = p->next;
10121            del_action_item("upload",p->path,g_pSyncList[index]->up_space_not_enough_list);
10122            p = p1;
10123        }
10124        else
10125        {
10126
10127            wd_DEBUG("upload %s failed",p->path);
10128
10129            p = p->next;
10130        }
10131        free(serverpath);
10132        free(path_temp);
10133    }
10134    wd_DEBUG("*************do_unfinished ok*****************\n");
10135    return 0;
10136}
10137int write_log(int status, char *message, char *filename,int index)
10138{
10139    if(exit_loop)
10140    {
10141        return 0;
10142    }
10143    //printf("write log status = %d\n",status);
10144    pthread_mutex_lock(&mutex_log);
10145    Log_struc log_s;
10146    FILE *fp;
10147    int mount_path_length;
10148    int ret;
10149    struct timeval now;
10150    struct timespec outtime;
10151
10152
10153    if(status == S_SYNC && exit_loop ==0)
10154    {
10155        ret = api_accout_info();
10156        if(ret==0)
10157        {
10158            cJSON *json=dofile(Con(TMP_R,data_3.txt));
10159            cJSON_printf(json,"quota_info");
10160            if(json)
10161                cJSON_Delete(json);
10162        }
10163
10164    }
10165    long long int totalspace = server_quota;
10166
10167
10168    //mount_path_length = strlen(mount_path);
10169    mount_path_length = asus_cfg.prule[index]->base_path_len;
10170
10171    memset(&log_s,0,LOG_SIZE);
10172
10173    log_s.status = status;
10174
10175    fp = fopen(general_log,"w");
10176
10177    if(fp == NULL)
10178    {
10179
10180        wd_DEBUG("open %s error\n",general_log);
10181
10182        pthread_mutex_unlock(&mutex_log);
10183        return -1;
10184    }
10185
10186    if(log_s.status == S_ERROR)
10187    {
10188
10189        wd_DEBUG("******** status is ERROR *******\n");
10190
10191        strcpy(log_s.error,message);
10192        fprintf(fp,"STATUS:%d\nERR_MSG:%s\nTOTAL_SPACE:%lld\nUSED_SPACE:%lld\nRULENUM:%d\n",
10193                log_s.status,log_s.error,totalspace,server_normal+server_shared,index);
10194    }
10195    else if(log_s.status == S_DOWNLOAD)
10196    {
10197
10198        wd_DEBUG("******** status is DOWNLOAD *******\n");
10199
10200        strcpy(log_s.path,filename);
10201        fprintf(fp,"STATUS:%d\nMOUNT_PATH:%s\nFILENAME:%s\nTOTAL_SPACE:%lld\nUSED_SPACE:%lld\nRULENUM:%d\n",
10202                log_s.status,asus_cfg.prule[index]->base_path,log_s.path+mount_path_length,totalspace,server_normal+server_shared,index);
10203    }
10204    else if(log_s.status == S_UPLOAD)
10205    {
10206
10207        wd_DEBUG("******** status is UPLOAD *******\n");
10208
10209        strcpy(log_s.path,filename);
10210        fprintf(fp,"STATUS:%d\nMOUNT_PATH:%s\nFILENAME:%s\nTOTAL_SPACE:%lld\nUSED_SPACE:%lld\nRULENUM:%d\n",
10211                log_s.status,asus_cfg.prule[index]->base_path,log_s.path+mount_path_length,totalspace,server_normal+server_shared,index);
10212    }
10213    else
10214    {
10215        //printf("write log status2 = %d\n",status);
10216
10217        if (log_s.status == S_INITIAL)
10218            wd_DEBUG("******** other status is INIT *******\n");
10219        else
10220            wd_DEBUG("******** other status is SYNC *******\n");
10221
10222        fprintf(fp,"STATUS:%d\nTOTAL_SPACE:%lld\nUSED_SPACE:%lld\nRULENUM:%d\n",
10223                log_s.status,totalspace,server_normal+server_shared,index);
10224        //fprintf(fp,"%d\n",log_s.status);
10225    }
10226
10227    fclose(fp);
10228
10229    if(!exit_loop)
10230    {
10231        gettimeofday(&now, NULL);
10232        outtime.tv_sec = now.tv_sec + 3;
10233        outtime.tv_nsec = now.tv_usec * 1000;
10234        pthread_cond_timedwait(&cond_socket, &mutex_log, &outtime);
10235    }
10236
10237    pthread_mutex_unlock(&mutex_log);
10238    return 0;
10239}
10240/*SIG*/
10241#if TOKENFILE
10242int write_notify_file(char *path,int signal_num)
10243{
10244    FILE *fp;
10245    char fullname[64];
10246    memset(fullname,0,sizeof(fullname));
10247
10248    //my_mkdir_r(path);
10249    my_mkdir("/tmp/notify");
10250    my_mkdir("/tmp/notify/usb");
10251    sprintf(fullname,"%s/dropbox_client",path);
10252    fp = fopen(fullname,"w");
10253    if(NULL == fp)
10254    {
10255        wd_DEBUG("open notify %s file fail\n",fullname);
10256        return -1;
10257    }
10258    fprintf(fp,"%d",signal_num);
10259    fclose(fp);
10260    return 0;
10261}
10262int get_tokenfile_info()
10263{
10264    wd_DEBUG("2222\n");
10265    int i;
10266    int j = 0;
10267    struct mounts_info_tag *info = NULL;
10268    char *tokenfile;
10269    FILE *fp;
10270    char buffer[1024];
10271    char *p;
10272
10273    /*if(initial_tokenfile_info_data(&tokenfile_info_start) == NULL)
10274    {
10275        return -1;
10276    }*/
10277    wd_DEBUG("12222\n");
10278    tokenfile_info = tokenfile_info_start;
10279    wd_DEBUG("42222\n");
10280    info = (struct mounts_info_tag *)malloc(sizeof(struct mounts_info_tag));
10281    if(info == NULL)
10282    {
10283        wd_DEBUG("obtain memory space fail\n");
10284        return -1;
10285    }
10286    wd_DEBUG("32222\n");
10287    memset(info,0,sizeof(struct mounts_info_tag));
10288    memset(buffer,0,1024);
10289
10290    if(get_mounts_info(info) == -1)
10291    {
10292        wd_DEBUG("get mounts info fail\n");
10293        return -1;
10294    }
10295    wd_DEBUG("111\n");
10296    for(i=0;i<info->num;i++)
10297    {
10298        //printf("info->paths[%d] = %s\n",i,info->paths[i]);
10299        tokenfile = my_str_malloc(strlen(info->paths[i])+20+1);
10300        sprintf(tokenfile,"%s/.dropbox_tokenfile",info->paths[i]);
10301        //printf("tokenfile = %s\n",tokenfile);
10302        if(!access(tokenfile,F_OK))
10303        {
10304            wd_DEBUG("tokenfile is exist!\n");
10305            if((fp = fopen(tokenfile,"r"))==NULL)
10306            {
10307                fprintf(stderr,"read tokenfile error\n");
10308                exit(-1);
10309            }
10310            while(fgets(buffer,1024,fp)!=NULL)
10311            {
10312                if( buffer[ strlen(buffer)-1 ] == '\n' )
10313                    buffer[ strlen(buffer)-1 ] = '\0';
10314                p = buffer;
10315                if(j == 0)
10316                {
10317                    if(initial_tokenfile_info_data(&tokenfile_info_tmp) == NULL)
10318                    {
10319                        fclose(fp);
10320                        return -1;
10321                    }
10322                    tokenfile_info_tmp->url = my_str_malloc(strlen(p)+1);
10323                    sprintf(tokenfile_info_tmp->url,"%s",p);
10324                    tokenfile_info_tmp->mountpath = my_str_malloc(strlen(info->paths[i])+1);
10325                    sprintf(tokenfile_info_tmp->mountpath,"%s",info->paths[i]);
10326                    j++;
10327                }
10328                else
10329                {
10330                    tokenfile_info_tmp->folder = my_str_malloc(strlen(p)+1);
10331                    sprintf(tokenfile_info_tmp->folder,"%s",p);
10332                    tokenfile_info->next = tokenfile_info_tmp;
10333                    tokenfile_info = tokenfile_info_tmp;
10334                    j = 0;
10335                }
10336            }
10337            fclose(fp);
10338        }
10339        free(tokenfile);
10340    }
10341
10342
10343    for(i=0;i<info->num;++i)
10344    {
10345        free(info->paths[i]);
10346    }
10347    if(info->paths != NULL)
10348        free(info->paths);
10349    free(info);
10350
10351    return 0;
10352}
10353int get_mounts_info(struct mounts_info_tag *info)
10354{
10355    wd_DEBUG("get_mounts_info\n");
10356    int len = 0;
10357    FILE *fp;
10358    int i = 0;
10359    int num = 0;
10360    //char *mount_path;
10361    char **tmp_mount_list=NULL;
10362    char **tmp_mount=NULL;
10363
10364    char buf[len+1];
10365    memset(buf,'\0',sizeof(buf));
10366    char a[1024];
10367    //char *temp;
10368    char *p,*q;
10369    fp = fopen("/proc/mounts","r");
10370    if(fp)
10371    {
10372        while(!feof(fp))
10373        {
10374            memset(a,'\0',sizeof(a));
10375            fscanf(fp,"%[^\n]%*c",a);
10376            if((strlen(a) != 0)&&((p=strstr(a,"/dev/sd")) != NULL))
10377            {
10378                //if((q=strstr(p,"/mnt")) != NULL)
10379                if((q=strstr(p,"/tmp")) != NULL)
10380                {
10381                    if((p=strstr(q," ")) != NULL)
10382                    {
10383
10384                        len = strlen(q) - strlen(p)+1;
10385
10386
10387                        tmp_mount = (char **)malloc(sizeof(char *)*(num+1));
10388                        if(tmp_mount == NULL)
10389                        {
10390                            fclose(fp);
10391                            return -1;
10392                        }
10393
10394                        tmp_mount[num] = my_str_malloc(len+1);
10395                        if(tmp_mount[num] == NULL)
10396                        {
10397                            free(tmp_mount);
10398                            fclose(fp);
10399                            return -1;
10400                        }
10401                        snprintf(tmp_mount[num],len,"%s",q);
10402
10403                        if(num != 0)
10404                        {
10405                            for(i = 0; i < num; ++i)
10406                                tmp_mount[i] = tmp_mount_list[i];
10407
10408                            free(tmp_mount_list);
10409                            tmp_mount_list = tmp_mount;
10410                        }
10411                        else
10412                            tmp_mount_list = tmp_mount;
10413
10414                        ++num;
10415
10416                        //info->paths =
10417                    }
10418                }
10419            }
10420        }
10421    }
10422    fclose(fp);
10423
10424    info->paths = tmp_mount_list;
10425    info->num = num;
10426    return 0;
10427}
10428struct tokenfile_info_tag *initial_tokenfile_info_data(struct tokenfile_info_tag **token)
10429{
10430    struct tokenfile_info_tag *follow_token;
10431
10432    if(token == NULL)
10433        return *token;
10434
10435    *token = (struct tokenfile_info_tag *)malloc(sizeof(struct tokenfile_info_tag));
10436    if(*token == NULL)
10437        return NULL;
10438
10439    follow_token = *token;
10440
10441    follow_token->url = NULL;
10442    follow_token->folder = NULL;
10443    follow_token->mountpath = NULL;
10444    follow_token->next = NULL;
10445
10446    return follow_token;
10447}
10448int check_config_path(int is_read_config)
10449{
10450    wd_DEBUG("check_config_path start\n");
10451    int i;
10452    int flag;
10453    char *nv;
10454    char *nvp;
10455    char *new_nv;
10456    int nv_len;
10457    int is_path_change = 0;
10458
10459#ifdef NVRAM_
10460#ifndef USE_TCAPI
10461    nv = strdup(nvram_safe_get("db_tokenfile"));
10462#else
10463    char tmp[MAXLEN_TCAPI_MSG] = {0};
10464    tcapi_get(AICLOUD, "db_tokenfile", tmp);
10465    nv = my_str_malloc(strlen(tmp)+1);
10466    sprintf(nv,"%s",tmp);
10467#endif
10468#else
10469    FILE *fp;
10470    fp = fopen(TOKENFILE_RECORD,"r");
10471    if(fp==NULL)
10472    {
10473        nv = my_str_malloc(2);
10474        sprintf(nv,"");
10475    }
10476    else
10477    {
10478        fseek( fp , 0 , SEEK_END );
10479        int file_size;
10480        file_size = ftell( fp );
10481        fseek(fp , 0 , SEEK_SET);
10482        //nv =  (char *)malloc( file_size * sizeof( char ) );
10483        nv = my_str_malloc(file_size+2);
10484        //fread(nv , file_size , sizeof(char) , fp);
10485        fscanf(fp,"%[^\n]%*c",nv);
10486        fclose(fp);
10487    }
10488
10489
10490#endif
10491    nv_len = strlen(nv);
10492
10493    //write_debug_log("check_config_path");
10494    wd_DEBUG("nv_len = %d\n",nv_len);
10495    wd_DEBUG("nv = %s\n",nv);
10496
10497    for(i=0;i<asus_cfg.dir_number;i++)
10498    {
10499        flag = 0;
10500        /*tokenfile exist*/
10501        tokenfile_info_tmp = tokenfile_info_start->next;
10502        while(tokenfile_info_tmp != NULL)
10503        {
10504            if( !strcmp(tokenfile_info_tmp->url,asus_cfg.user) &&
10505                !strcmp(tokenfile_info_tmp->folder,asus_cfg.prule[i]->rooturl))
10506            {
10507                if(strcmp(tokenfile_info_tmp->mountpath,asus_cfg.prule[i]->base_path))
10508                {
10509                    memset(asus_cfg.prule[i]->base_path,0,sizeof(asus_cfg.prule[i]->base_path));
10510                    sprintf(asus_cfg.prule[i]->base_path,"%s",tokenfile_info_tmp->mountpath);
10511                    memset(asus_cfg.prule[i]->path,0,sizeof(asus_cfg.prule[i]->path));
10512                    sprintf(asus_cfg.prule[i]->path,"%s%s",tokenfile_info_tmp->mountpath,tokenfile_info_tmp->folder);
10513                    asus_cfg.prule[i]->base_path_len = strlen(asus_cfg.prule[i]->base_path);
10514                    is_path_change = 1;
10515                }
10516                if(!is_read_config)
10517                {
10518                    if(g_pSyncList[i]->sync_disk_exist == 0)
10519                        is_path_change = 1;   //plug the disk and the mout_path not change
10520                }
10521                flag = 1;
10522                break;
10523            }
10524            tokenfile_info_tmp = tokenfile_info_tmp->next;
10525        }
10526        wd_DEBUG("asus_cfg.prule[%d]->path = %s\n",i,asus_cfg.prule[i]->path);
10527        if(!flag)
10528        {
10529            nvp = my_str_malloc(strlen(asus_cfg.user)+strlen(asus_cfg.prule[i]->rooturl)+2);
10530            sprintf(nvp,"%s>%s",asus_cfg.user,asus_cfg.prule[i]->rooturl);
10531
10532            //write_debug_log(nv);
10533            //write_debug_log(nvp);
10534            wd_DEBUG("nvp = %s\n",nvp);
10535
10536            if(!is_read_config)
10537            {
10538                if(g_pSyncList[i]->sync_disk_exist == 1)
10539                    is_path_change = 2;   //remove the disk and the mout_path not change
10540            }
10541
10542            //printf("write nvram and tokenfile if before\n");
10543
10544            /* "name>folder" is not in tokenfile_record */
10545            if(strstr(nv,nvp) == NULL)
10546            {
10547                //printf("write nvram and tokenfile if behind");
10548
10549                if(initial_tokenfile_info_data(&tokenfile_info_tmp) == NULL)
10550                {
10551                    return -1;
10552                }
10553                tokenfile_info_tmp->url = my_str_malloc(strlen(asus_cfg.user)+1);
10554                sprintf(tokenfile_info_tmp->url,"%s",asus_cfg.user);
10555
10556                tokenfile_info_tmp->mountpath = my_str_malloc(strlen(asus_cfg.prule[i]->base_path)+1);
10557                sprintf(tokenfile_info_tmp->mountpath,"%s",asus_cfg.prule[i]->base_path);
10558
10559                tokenfile_info_tmp->folder = my_str_malloc(strlen(asus_cfg.prule[i]->rooturl)+1);
10560                sprintf(tokenfile_info_tmp->folder,"%s",asus_cfg.prule[i]->rooturl);
10561
10562                tokenfile_info->next = tokenfile_info_tmp;
10563                tokenfile_info = tokenfile_info_tmp;
10564
10565                write_to_tokenfile(asus_cfg.prule[i]->base_path);
10566
10567                if(nv_len)
10568                {
10569                    new_nv = my_str_malloc(strlen(nv)+strlen(nvp)+2);
10570                    sprintf(new_nv,"%s<%s",nv,nvp);
10571
10572                }
10573                else
10574                {
10575                    new_nv = my_str_malloc(strlen(nvp)+1);
10576                    sprintf(new_nv,"%s",nvp);
10577                }
10578                wd_DEBUG("new_nv = %s\n",new_nv);
10579                //write_to_wd_tokenfile(new_nv);
10580
10581#ifdef NVRAM_
10582                write_to_nvram(new_nv,"db_tokenfile");
10583#else
10584                write_to_wd_tokenfile(new_nv);
10585#endif
10586
10587                free(new_nv);
10588            }
10589            free(nvp);
10590        }
10591    }
10592    free(nv);
10593    return is_path_change;
10594}
10595int write_to_tokenfile(char *mpath)
10596{
10597    //write_debug_log("write_to_tokenfile");
10598    wd_DEBUG("write_to_tokenfile start\n");
10599    FILE *fp;
10600    //int flag=0;
10601
10602    char *filename;
10603    filename = my_str_malloc(strlen(mpath)+20+1);
10604    sprintf(filename,"%s/.dropbox_tokenfile",mpath);
10605    wd_DEBUG("filename = %s\n",filename);
10606
10607    int i = 0;
10608    if( ( fp = fopen(filename,"w") ) == NULL )
10609    {
10610        wd_DEBUG("open tokenfile failed!\n");
10611        return -1;
10612    }
10613
10614    tokenfile_info_tmp = tokenfile_info_start->next;
10615    while(tokenfile_info_tmp != NULL)
10616    {
10617        wd_DEBUG("tokenfile_info_tmp->mountpath = %s\n",tokenfile_info_tmp->mountpath);
10618        if(!strcmp(tokenfile_info_tmp->mountpath,mpath))
10619        {
10620            //write_debug_log(tokenfile_info_tmp->folder);
10621            wd_DEBUG("tokenfile_info_tmp->url = %s\n",tokenfile_info_tmp->url);
10622            if(i == 0)
10623            {
10624                fprintf(fp,"%s\n%s",tokenfile_info_tmp->url,tokenfile_info_tmp->folder);
10625                i=1;
10626            }
10627            else
10628            {
10629                fprintf(fp,"\n%s\n%s",tokenfile_info_tmp->url,tokenfile_info_tmp->folder);
10630            }
10631            //flag = 1;
10632        }
10633
10634        tokenfile_info_tmp = tokenfile_info_tmp->next;
10635    }
10636
10637    fclose(fp);
10638    if(!i)
10639        remove(filename);
10640    free(filename);
10641
10642    wd_DEBUG("write_to_tokenfile end\n");
10643    return 0;
10644}
10645#ifdef NVRAM_
10646int write_to_nvram(char *contents,char *nv_name)
10647{
10648    char *command;
10649    command = my_str_malloc(strlen(contents)+strlen(SHELL_FILE)+strlen(nv_name)+8);
10650    sprintf(command,"sh %s \"%s\" %s",SHELL_FILE,contents,nv_name);
10651
10652    wd_DEBUG("command : [%s]\n",command);
10653
10654    system(command);
10655    free(command);
10656
10657    return 0;
10658}
10659#else
10660int write_to_wd_tokenfile(char *contents)
10661{
10662    if(contents == NULL || contents == "")
10663    {
10664        unlink(TOKENFILE_RECORD);
10665        return 0;
10666    }
10667    FILE *fp;
10668    if( ( fp = fopen(TOKENFILE_RECORD,"w") ) == NULL )
10669    {
10670        wd_DEBUG("open wd_tokenfile failed!\n");
10671        return -1;
10672    }
10673    fprintf(fp,"%s",contents);
10674    fclose(fp);
10675    //printf("write_to_wd_tokenfile end\n");
10676    return 0;
10677}
10678#endif
10679#ifdef NVRAM_
10680int convert_nvram_to_file_mutidir(char *file,struct asus_config *config)
10681{
10682
10683    wd_DEBUG("enter convert_nvram_to_file_mutidir function\n");
10684
10685    FILE *fp;
10686    char *nv, *nvp, *b;
10687    //struct asus_config config;
10688    int i;
10689    //int status;
10690    char *p;
10691    char *buffer;
10692    char *buf;
10693
10694    fp=fopen(file, "w");
10695
10696    if (fp==NULL) return -1;
10697#ifndef USE_TCAPI
10698    nv = nvp = strdup(nvram_safe_get("cloud_sync"));
10699#else
10700    char tmp[MAXLEN_TCAPI_MSG] = {0};
10701    tcapi_get(AICLOUD, "cloud_sync", tmp);
10702    nvp = nv = my_str_malloc(strlen(tmp)+1);
10703    sprintf(nv,"%s",tmp);
10704#endif
10705
10706    //printf("otain nvram end\n");
10707
10708    if(nv)
10709    {
10710        while ((b = strsep(&nvp, "<")) != NULL)
10711        {
10712            i = 0;
10713            buf = buffer = strdup(b);
10714
10715            wd_DEBUG("buffer = %s\n",buffer);
10716
10717            while((p = strsep(&buffer,">")) != NULL)
10718            {
10719
10720                wd_DEBUG("p = %s\n",p);
10721
10722                if (*p == 0)
10723                {
10724                    fprintf(fp,"\n");
10725                    i++;
10726                    continue;
10727                }
10728                if(i == 0)
10729                {
10730                    if(atoi(p) != 3)
10731                        break;
10732                    fprintf(fp,"%s",p);
10733                }
10734                else
10735                {
10736                    fprintf(fp,"\n%s",p);
10737                }
10738//                if(i == 5)
10739//                    config->dir_number = atoi(p);
10740                if(i == 4)
10741                    config->dir_number = atoi(p);
10742                i++;
10743            }
10744            free(buf);
10745        }
10746        free(nv);
10747    }
10748
10749    else
10750        wd_DEBUG("get nvram fail\n");
10751
10752    fclose(fp);
10753
10754    wd_DEBUG("end convert_nvram_to_file_mutidir function\n");
10755
10756    return 0;
10757}
10758#else
10759int create_webdav_conf_file(struct asus_config *config){
10760
10761
10762    wd_DEBUG("enter create_dropbox_conf_file function\n");
10763
10764    FILE *fp;
10765    char *nv, *nvp, *b;
10766    int i;
10767    char *p;
10768    char *buffer;
10769    char *buf;
10770
10771    fp = fopen(TMPCONFIG,"r");
10772    if (fp==NULL)
10773    {
10774        nvp = my_str_malloc(2);
10775        sprintf(nvp,"");
10776    }
10777    else
10778    {
10779        fseek( fp , 0 , SEEK_END );
10780        int file_size;
10781        file_size = ftell( fp );
10782        fseek(fp , 0 , SEEK_SET);
10783        nvp =  (char *)malloc( file_size * sizeof( char ) );
10784        fread(nvp , file_size , sizeof(char) , fp);
10785        fclose(fp);
10786    }
10787
10788    nv = nvp;
10789
10790    replace_char_in_str(nvp,'\0','\n');
10791
10792    wd_DEBUG("**********nv = %s\n",nv);
10793
10794
10795    fp=fopen(CONFIG_PATH, "w");
10796
10797    if (fp==NULL) return -1;
10798
10799    //nv = nvp = strdup(nvram_safe_get("cloud_sync"));
10800
10801    //printf("otain nvram end\n");
10802    config->dir_number = 0;
10803    if(nv)
10804    {
10805        while ((b = strsep(&nvp, "<")) != NULL)
10806        {
10807            i = 0;
10808            buf = buffer = strdup(b);
10809
10810            wd_DEBUG("buffer = %s\n",buffer);
10811
10812            while((p = strsep(&buffer,">")) != NULL)
10813            {
10814
10815                wd_DEBUG("p = %s\n",p);
10816
10817                if (*p == 0)
10818                {
10819                    fprintf(fp,"\n");
10820                    i++;
10821                    continue;
10822                }
10823                if(i == 0)
10824                {
10825                    if(atoi(p) != 3)
10826                        break;
10827                    fprintf(fp,"%s",p);
10828                }
10829                else
10830                {
10831                    fprintf(fp,"\n%s",p);
10832                }
10833//                if(i == 5)
10834//                    config->dir_number = atoi(p);
10835                if(i == 4)
10836                    config->dir_number = atoi(p);
10837                i++;
10838            }
10839            //fprintf(fp,"\n");
10840            free(buf);
10841
10842        }
10843
10844        free(nv);
10845
10846    }
10847    else
10848        wd_DEBUG("get nvram fail\n");
10849
10850    fclose(fp);
10851    return 0;
10852
10853}
10854#endif
10855int rewrite_tokenfile_and_nv(){
10856
10857    int i,j;
10858    int exist;
10859    //write_debug_log("rewrite_tokenfile_and_nv start");
10860    wd_DEBUG("rewrite_tokenfile_and_nv start\n");
10861    if(asus_cfg.dir_number > asus_cfg_stop.dir_number)
10862    {
10863        for(i=0;i<asus_cfg.dir_number;i++)
10864        {
10865            exist = 0;
10866            for(j=0;j<asus_cfg_stop.dir_number;j++)
10867            {
10868                if(!strcmp(asus_cfg_stop.prule[j]->rooturl,asus_cfg.prule[i]->rooturl))
10869                {
10870                    exist = 1;
10871                    break;
10872                }
10873            }
10874            if(!exist)
10875            {
10876                //write_debug_log("del form nv");
10877                wd_DEBUG("del form nv\n");
10878                char *new_nv;
10879                delete_tokenfile_info(asus_cfg.user,asus_cfg.prule[i]->rooturl);
10880                new_nv = delete_nvram_contents(asus_cfg.user,asus_cfg.prule[i]->rooturl);
10881                wd_DEBUG("new_nv = %s\n",new_nv);
10882
10883                remove(g_pSyncList[i]->conflict_file);
10884
10885                write_to_tokenfile(asus_cfg.prule[i]->base_path);
10886
10887#ifdef NVRAM_
10888                write_to_nvram(new_nv,"db_tokenfile");
10889#else
10890                write_to_wd_tokenfile(new_nv);
10891#endif
10892
10893                //write_to_wd_tokenfile(new_nv);
10894                free(new_nv);
10895            }
10896        }
10897    }
10898    else
10899    {
10900        for(i=0;i<asus_cfg_stop.dir_number;i++)
10901        {
10902            exist = 0;
10903            for(j=0;j<asus_cfg.dir_number;j++)
10904            {
10905                if(!strcmp(asus_cfg_stop.prule[i]->rooturl,asus_cfg.prule[j]->rooturl))
10906                {
10907                    exist = 1;
10908                    break;
10909                }
10910            }
10911            if(!exist)
10912            {
10913                //write_debug_log("add to nv");
10914                wd_DEBUG("add to nv\n");
10915                char *new_nv;
10916                add_tokenfile_info(asus_cfg_stop.user,asus_cfg_stop.prule[i]->rooturl,asus_cfg_stop.prule[i]->base_path);
10917                new_nv = add_nvram_contents(asus_cfg_stop.user,asus_cfg_stop.prule[i]->rooturl);
10918                wd_DEBUG("new_nv = %s\n",new_nv);
10919                wd_DEBUG("base_path = %s\n",asus_cfg_stop.prule[i]->base_path);
10920                write_to_tokenfile(asus_cfg_stop.prule[i]->base_path);
10921
10922#ifdef NVRAM_
10923                write_to_nvram(new_nv,"db_tokenfile");
10924#else
10925                write_to_wd_tokenfile(new_nv);
10926#endif
10927
10928                //write_to_wd_tokenfile(new_nv);
10929                free(new_nv);
10930            }
10931        }
10932    }
10933    return 0;
10934}
10935#ifndef NVRAM_
10936int write_get_nvram_script(){
10937
10938    FILE *fp;
10939    char contents[512];
10940    memset(contents,0,512);
10941    strcpy(contents,"#! /bin/sh\nNV=`nvram get cloud_sync`\nif [ ! -f \"/tmp/smartsync/dropbox/config/dropbox_tmpconfig\" ]; then\n   touch /tmp/smartsync/dropbox/config/dropbox_tmpconfig\nfi\necho \"$NV\" >/tmp/smartsync/dropbox/config/dropbox_tmpconfig");
10942
10943    if(( fp = fopen(DropBox_Get_Nvram,"w"))==NULL)
10944    {
10945        fprintf(stderr,"create dropbox_get_nvram file error\n");
10946        return -1;
10947    }
10948
10949    fprintf(fp,"%s",contents);
10950    fclose(fp);
10951
10952    return 0;
10953}
10954int write_get_nvram_script_va(char *str)
10955{
10956    FILE *fp;
10957    char contents[512];
10958    memset(contents,0,512);
10959    //strcpy(contents,"#! /bin/sh\nNV=`nvram get cloud_sync`\nif [ ! -f \"/tmp/smartsync/dropbox/config/dropbox_tmpconfig\" ]; then\n   touch /tmp/smartsync/dropbox/config/dropbox_tmpconfig\nfi\necho \"$NV\" >/tmp/smartsync/dropbox/config/dropbox_tmpconfig");
10960    sprintf(contents,"#! /bin/sh\nNV=`nvram get %s`\nif [ ! -f \"%s\" ]; then\n   touch %s\nfi\necho \"$NV\" >%s",str,TMP_NVRAM_VL,TMP_NVRAM_VL,TMP_NVRAM_VL);
10961
10962    if(( fp = fopen(DropBox_Get_Nvram_Link,"w"))==NULL)
10963    {
10964        fprintf(stderr,"create dropbox_get_nvram file error\n");
10965        return -1;
10966    }
10967
10968    fprintf(fp,"%s",contents);
10969    fclose(fp);
10970
10971    return 0;
10972}
10973#endif
10974int delete_tokenfile_info(char *url,char *folder){
10975
10976    struct tokenfile_info_tag *tmp;
10977
10978    tmp = tokenfile_info_start;
10979    tokenfile_info_tmp = tokenfile_info_start->next;
10980
10981    while(tokenfile_info_tmp != NULL)
10982    {
10983        if( !strcmp(tokenfile_info_tmp->url,url) &&
10984            !strcmp(tokenfile_info_tmp->folder,folder))
10985        {
10986            tmp->next = tokenfile_info_tmp->next;
10987            free(tokenfile_info_tmp->folder);
10988            free(tokenfile_info_tmp->url);
10989            free(tokenfile_info_tmp->mountpath);
10990            free(tokenfile_info_tmp);
10991            tokenfile_info_tmp = NULL;
10992            break;
10993        }
10994        tmp = tokenfile_info_tmp;
10995        tokenfile_info_tmp = tokenfile_info_tmp->next;
10996    }
10997
10998    //write_debug_log("delete_tokenfile_info stop");
10999    return 0;
11000}
11001char *delete_nvram_contents(char *url,char *folder){
11002    //write_debug_log("delete_nvram_contents start");
11003
11004    char *nv;
11005    char *nvp;
11006    char *p,*b;
11007
11008    char *new_nv;
11009    int n;
11010    int i=0;
11011
11012
11013
11014#ifdef NVRAM_
11015#ifndef USE_TCAPI
11016    p = nv = strdup(nvram_safe_get("db_tokenfile"));
11017#else
11018    char tmp[MAXLEN_TCAPI_MSG] = {0};
11019    tcapi_get(AICLOUD, "db_tokenfile", tmp);
11020    p = nv = my_str_malloc(strlen(tmp)+1);
11021    sprintf(nv,"%s",tmp);
11022#endif
11023#else
11024    FILE *fp;
11025    fp = fopen(TOKENFILE_RECORD,"r");
11026    if (fp==NULL)
11027    {
11028        nv = my_str_malloc(2);
11029        sprintf(nv,"");
11030    }
11031    else
11032    {
11033        fseek( fp , 0 , SEEK_END );
11034        int file_size;
11035        file_size = ftell( fp );
11036        fseek(fp , 0 , SEEK_SET);
11037
11038        nv = my_str_malloc(file_size+2);
11039
11040        fscanf(fp,"%[^\n]%*c",nv);
11041        p = nv;
11042        fclose(fp);
11043    }
11044
11045#endif
11046
11047    nvp = my_str_malloc(strlen(url)+strlen(folder)+2);
11048    sprintf(nvp,"%s>%s",url,folder);
11049
11050
11051
11052    if(strstr(nv,nvp) == NULL)
11053    {
11054        free(nvp);
11055        return nv;
11056    }
11057
11058
11059
11060    if(!strcmp(nv,nvp))
11061    {
11062        free(nvp);
11063        memset(nv,0,sizeof(nv));
11064        sprintf(nv,"");
11065        return nv;
11066    }
11067
11068
11069    if(nv)
11070    {
11071        while((b = strsep(&p, "<")) != NULL)
11072        {
11073            //write_debug_log(b);
11074            if(strcmp(b,nvp))
11075            {
11076                n = strlen(b);
11077                if(i == 0)
11078                {
11079                    new_nv = my_str_malloc(n+1);
11080                    sprintf(new_nv,"%s",b);
11081                    ++i;
11082                }
11083                else
11084                {
11085                    new_nv = realloc(new_nv, strlen(new_nv)+n+2);
11086                    sprintf(new_nv,"%s<%s",new_nv,b);
11087                }
11088            }
11089        }
11090
11091        free(nv);
11092    }
11093    free(nvp);
11094
11095    return new_nv;
11096}
11097int add_tokenfile_info(char *url,char *folder,char *mpath){
11098
11099    if(initial_tokenfile_info_data(&tokenfile_info_tmp) == NULL)
11100    {
11101        return -1;
11102    }
11103
11104    tokenfile_info_tmp->url = my_str_malloc(strlen(url)+1);
11105    sprintf(tokenfile_info_tmp->url,"%s",url);
11106
11107    tokenfile_info_tmp->mountpath = my_str_malloc(strlen(mpath)+1);
11108    sprintf(tokenfile_info_tmp->mountpath,"%s",mpath);
11109
11110    tokenfile_info_tmp->folder = my_str_malloc(strlen(folder)+1);
11111    sprintf(tokenfile_info_tmp->folder,"%s",folder);
11112
11113    tokenfile_info->next = tokenfile_info_tmp;
11114    tokenfile_info = tokenfile_info_tmp;
11115
11116    return 0;
11117}
11118char *add_nvram_contents(char *url,char *folder){
11119
11120    char *nv;
11121    int nv_len;
11122    char *new_nv;
11123    char *nvp;
11124
11125    nvp = my_str_malloc(strlen(url)+strlen(folder)+2);
11126    sprintf(nvp,"%s>%s",url,folder);
11127
11128    wd_DEBUG("add_nvram_contents     nvp = %s\n",nvp);
11129
11130
11131#ifdef NVRAM_
11132#ifndef USE_TCAPI
11133    nv = strdup(nvram_safe_get("db_tokenfile"));
11134#else
11135    char tmp[MAXLEN_TCAPI_MSG] = {0};
11136    tcapi_get(AICLOUD, "db_tokenfile", tmp);
11137    nv = my_str_malloc(strlen(tmp)+1);
11138    sprintf(nv,"%s",tmp);
11139#endif
11140#else
11141    FILE *fp;
11142    fp = fopen(TOKENFILE_RECORD,"r");
11143    if (fp==NULL)
11144    {
11145        nv = my_str_malloc(2);
11146        sprintf(nv,"");
11147    }
11148    else
11149    {
11150        fseek( fp , 0 , SEEK_END );
11151        int file_size;
11152        file_size = ftell( fp );
11153        fseek(fp , 0 , SEEK_SET);
11154        wd_DEBUG("add_nvram_contents     file_size = %d\n",file_size);
11155        //nv =  (char *)malloc( file_size * sizeof( char ) );
11156        nv = my_str_malloc(file_size+2);
11157        //fread(nv , file_size ,1, fp);
11158        fscanf(fp,"%[^\n]%*c",nv);
11159        fclose(fp);
11160    }
11161#endif
11162
11163    wd_DEBUG("add_nvram_contents     nv = %s\n",nv);
11164    nv_len = strlen(nv);
11165
11166    if(nv_len)
11167    {
11168        new_nv = my_str_malloc(strlen(nv)+strlen(nvp)+2);
11169        sprintf(new_nv,"%s<%s",nv,nvp);
11170
11171    }
11172    else
11173    {
11174        new_nv = my_str_malloc(strlen(nvp)+1);
11175        sprintf(new_nv,"%s",nvp);
11176    }
11177    wd_DEBUG("add_nvram_contents     new_nv = %s\n",new_nv);
11178    free(nvp);
11179    free(nv);
11180    return new_nv;
11181}
11182int check_sync_disk_removed()
11183{
11184
11185    wd_DEBUG("check_sync_disk_removed start! \n");
11186
11187
11188    int ret;
11189
11190    free_tokenfile_info(tokenfile_info_start);
11191
11192    if(get_tokenfile_info()==-1)
11193    {
11194        wd_DEBUG("\nget_tokenfile_info failed\n");
11195        exit(-1);
11196    }
11197
11198    ret = check_config_path(0);
11199    return ret;
11200
11201}
11202int check_disk_change()
11203{
11204    int status = -1;
11205    disk_change = 0;
11206    status = check_sync_disk_removed();
11207
11208    if(status == 2 || status == 1)
11209    {
11210        exit_loop = 1;
11211
11212        sync_disk_removed = 1;
11213    }
11214
11215    return 0;
11216}
11217int free_tokenfile_info(struct tokenfile_info_tag *head)
11218{
11219    struct tokenfile_info_tag *p = head->next;
11220    while(p != NULL)
11221    {
11222        head->next = p->next;
11223        if(p->folder != NULL)
11224        {
11225            //printf("free CloudFile %s\n",p->href);
11226            free(p->folder);
11227        }
11228        if(p->mountpath != NULL)
11229        {
11230            free(p->mountpath);
11231        }
11232        if(p->url != NULL)
11233        {
11234            free(p->url);
11235        }
11236        free(p);
11237        p = head->next;
11238    }
11239    return 0;
11240}
11241int detect_client()
11242{
11243    unlink("/tmp/smartsync_app/dropbox_client_start");
11244    char *dir = "/tmp/smartsync_app";
11245    int flag = 0;
11246    if(access(dir,0) != 0)
11247        flag = 0;
11248    else
11249    {
11250        struct dirent* ent = NULL;
11251        DIR *pDir;
11252        pDir=opendir(dir);
11253        int file_num = 0;
11254        if(pDir != NULL )
11255        {
11256            while (NULL != (ent=readdir(pDir)))
11257            {
11258                if(!strcmp(ent->d_name,".") || !strcmp(ent->d_name,".."))
11259                    continue;
11260                file_num ++ ;
11261            }
11262            closedir(pDir);
11263
11264            if(file_num > 0)
11265                flag = 1;
11266            else
11267                flag = 0;
11268
11269        }
11270        else
11271            flag = 0;
11272    }
11273    if(!flag)
11274    {
11275        system("killall -9 inotify &");
11276    }
11277}
11278
11279
11280int detect_process(char * process_name)
11281{
11282    FILE *ptr;
11283    char buff[512];
11284    char ps[128];
11285    sprintf(ps,"ps | grep -c %s",process_name);
11286    strcpy(buff,"ABNORMAL");
11287    if((ptr=popen(ps, "r")) != NULL)
11288    {
11289        while (fgets(buff, 512, ptr) != NULL)
11290        {
11291            if(atoi(buff)>2)
11292            {
11293                pclose(ptr);
11294                return 1;
11295            }
11296        }
11297    }
11298    if(strcmp(buff,"ABNORMAL")==0)  /*ps command error*/
11299    {
11300        return 0;
11301    }
11302    pclose(ptr);
11303    return 0;
11304}
11305#ifdef NVRAM_
11306int create_shell_file(){
11307
11308    FILE *fp;
11309    char contents[1024];
11310    memset(contents,0,1024);
11311#ifndef USE_TCAPI
11312    strcpy(contents,"#! /bin/sh\nnvram set $2=\"$1\"\nnvram commit");
11313#else
11314    strcpy(contents,"#! /bin/sh\ntcapi set AiCloud_Entry $2 \"$1\"\ntcapi commit AiCloud\ntcapi save");
11315#endif
11316
11317    if(( fp = fopen(SHELL_FILE,"w"))==NULL)
11318    {
11319        fprintf(stderr,"create shell file error");
11320        return -1;
11321    }
11322
11323    fprintf(fp,"%s",contents);
11324    fclose(fp);
11325    return 0;
11326
11327}
11328/*process running,return 1;else return 0*/
11329
11330#endif
11331#endif
11332
11333void deal_big_low_conflcit(char *server_conflict_name,char *oldname,char *newname,char *newname_r,int index)
11334{
11335    /*get conflict name*/
11336
11337    char *local_conflcit_name = serverpath_to_localpath(server_conflict_name,index);
11338//    char *tmp_name = malloc(strlen(local_conflcit_name)+1);
11339//    memset(tmp_name,0,strlen(local_conflcit_name)+1);
11340//    sprintf(tmp_name,"%s",local_conflcit_name);
11341    char *g_newname = NULL;
11342    int is_folder = test_if_dir(local_conflcit_name);
11343
11344    g_newname = get_confilicted_name_case(local_conflcit_name,is_folder);
11345
11346    wd_DEBUG("case-conflict=%s\n",g_newname);
11347    my_free(local_conflcit_name);
11348
11349
11350//    char *prefix_name = get_prefix_name(tmp_name,is_folder);//a.txt --> a
11351
11352//    g_newname = get_confilicted_name_first(tmp_name,is_folder);//a.txt-->a(case-conflict).txt
11353
11354//    if(access(g_newname,F_OK) == 0)//a(case-conflict).txt-->a(case-conflict(n)).txt
11355//    {
11356//        my_free(tmp_name);
11357//        tmp_name = malloc(strlen(g_newname)+1);
11358//        memset(tmp_name,0,strlen(g_newname)+1);
11359//        sprintf(tmp_name,"%s",g_newname);
11360//        my_free(g_newname);
11361//        while(!exit_loop)
11362//        {
11363//            g_newname = get_confilicted_name_second(tmp_name,is_folder,prefix_name);
11364//            //printf("confilicted_name=%s\n",confilicted_name);
11365//            if(access(g_newname,F_OK) == 0)
11366//            {
11367//                my_free(tmp_name);
11368//                tmp_name = malloc(strlen(g_newname)+1);
11369//                memset(tmp_name,0,strlen(g_newname)+1);
11370//                sprintf(tmp_name,"%s",g_newname);
11371//                my_free(g_newname);
11372//                //have_same = 1;
11373//            }
11374//            else
11375//                break;
11376//        }
11377//        my_free(tmp_name);
11378//    }else
11379//    {
11380//        my_free(tmp_name);
11381//    }
11382//    my_free(prefix_name);
11383
11384//    while(!exit_loop)
11385//    {
11386//        g_newname = get_confilicted_name(tmp_name,is_folder);
11387//        //printf("confilicted_name=%s\n",confilicted_name);
11388//        if(access(g_newname,F_OK) == 0)
11389//        {
11390//            my_free(tmp_name);
11391//            tmp_name = malloc(strlen(g_newname)+1);
11392//            memset(tmp_name,0,strlen(g_newname)+1);
11393//            sprintf(tmp_name,"%s",g_newname);
11394//            my_free(g_newname);
11395//            //have_same = 1;
11396//        }
11397//        else
11398//            break;
11399//    }
11400//    my_free(tmp_name);
11401
11402    char *localname;
11403    /*rename local conflict name to newname*/
11404    if(newname_r == NULL)
11405    {
11406        localname = serverpath_to_localpath(newname,index);
11407    }
11408    else
11409        localname = newname_r;
11410
11411    updata_socket_list(localname,g_newname,index);
11412
11413    if(access(localname,F_OK) == 0)
11414    {
11415        add_action_item("rename",g_newname,g_pSyncList[index]->server_action_list);
11416        rename(localname,g_newname);
11417    }
11418
11419    if(newname_r == NULL)
11420        my_free(localname);
11421    /*reback to deal rename a--> bb(1)*/
11422    char *s_newname = localpath_to_serverpath(g_newname,index);
11423    my_free(g_newname);
11424    int status = 0;
11425    do{
11426        status = api_move(oldname,s_newname,index,1,NULL);
11427    }while(status != 0 && !exit_loop);
11428    my_free(s_newname);
11429}
11430