Esempio n. 1
0
/* get from the BDII the list of supported protocols with their associated
 * port number
 */
int g2_sd_get_seap_info(const char *host, char ***access_protocol, int **port, char *errbuf, int errbufsz) {
    char **ap = NULL, *attr = NULL;
    char *query = NULL;
    struct berval **value = NULL;
    BerElement *ber = NULL;
    int nbentries, i = 0, n = 0, rc = 0;
    int *pn = NULL;
    LDAPMessage *entry = NULL, *reply = NULL;
    SDException exception;
    int sav_errno = 0;
    char *tempUrl = NULL;
    char *base_scheme = NULL;
    char *base_host = NULL;
    char *base_path = NULL;
    int base_port = 0;
    LDAP *ld = NULL;
    char *service_id = NULL;
    char *endpoint_id = NULL;    

    if (!host) {
        SD_setException(&exception, SDStatus_FAILURE, "[BDII][g2_sd_get_seap_info]: Hostname in null", errbuf, errbufsz);
        return -1;
    }


    if ((ld = get_connection(&exception, errbuf, errbufsz)) == NULL) {
        SD_setException(&exception, SDStatus_FAILURE, "[BDII][g2_sd_get_seap_info]: Cannot connect to BDII", errbuf, errbufsz);
        return (-1);
    }

    
    g2_sd_get_service_id(ld, host, &service_id, &endpoint_id, errbuf, errbufsz);
    if(!service_id)
    {
        SD_setException(&exception, SDStatus_FAILURE, "[BDII][g2_sd_get_seap_info]: ServiceID cannot be found", errbuf, errbufsz);
	if(ld)
		close_connection(ld);	
	return (-1);      
	
    }       

    /*prepare the query */
    query = g_strdup_printf(GLUE2_QUERY_PROTO_PORT_TYPE, service_id);



    while (n < 1 && !sav_errno) {

        /*send query to bdii server*/
        rc = connect_search_ldap(glue2_base, query, g2_seap_attrs, ld, &exception, &reply, errbuf, errbufsz);
        if (rc != LDAP_SUCCESS) {
            if (reply) {
                ldap_msgfree(reply);
            }
            rc = -1;
            sav_errno = errno;
            break;
        }

        /*count entry # */
        if ((nbentries = ldap_count_entries(ld, reply)) < 1) {
            SD_setException(&exception, SDStatus_FAILURE, "[BDII][g2_sd_get_seap_info]: No entries for host.", errbuf, errbufsz);
            if (reply) {
                ldap_msgfree(reply);
            }
            sav_errno = errno ? errno : ENOMEM;
            rc = -1;
            break;
        }


        nbentries++;
        /*allocate memory */
        if ((ap = (char **) calloc(nbentries, sizeof (char *))) == NULL || (pn
                = (int *) calloc(nbentries, sizeof (int))) == NULL) {
            if (reply) {
                ldap_msgfree(reply);
            }

            sav_errno = errno ? errno : ENOMEM;
            rc = -1;
            break;
        }


        for (entry = ldap_first_entry(ld, reply), n = 0; entry != NULL && rc
                == 0; entry = ldap_next_entry(ld, entry), ++n) {

            for (attr = ldap_first_attribute(ld, entry, &ber); attr != NULL
                    && rc == 0; attr = ldap_next_attribute(ld, entry, ber)) {

                if (!ap[n] && (value = ldap_get_values_len(ld, entry, attr))) {
                    if (value && value[0]->bv_val) {
                        if (strcmp(attr, "GLUE2EndpointURL") == 0) {
                            if ((ap[n] = strdup(value[0]->bv_val)) == NULL) {
                                rc = -1;
                                sav_errno = errno ? errno : ENOMEM;
                            } else {
                                tempUrl = ap[n];
                                if (tempUrl)
                                    parse_url(tempUrl, &base_scheme, &base_host, &base_port, &base_path);
                                if (base_scheme && base_port > 0) {
				    free(ap[n]);
                                    ap[n] = base_scheme; /* protocol */
                                    pn[n] = base_port; /* port */
                                } else {
                                    rc = -1;
                                    sav_errno = errno ? errno : ENOMEM;
                                }
                            }
                            if (value)
                                ber_bvecfree(value);
                        }
                    }
                }
                if (attr)
                    ldap_memfree(attr);
            }
            if (ber) {
                ber_free(ber, 0);
                ber = NULL;
            }
        }
        if (reply) {
            ldap_msgfree(reply);
        }

        if (base_host)
            free(base_host);
        if (base_path)
            free(base_path);
    }


    /* if something went wrong, give the memory free */
    if (rc < 0) {
        for (i = 0; i < n; ++i) {
            if (ap[i]) {
                free(ap[i]);
            }
        }
        if (ap && pn) {
            free(ap);
            free(pn);
        }
        SD_setException(&exception, SDStatus_FAILURE, "[BDII][g2_sd_get_seap_info]: No available information", errbuf, errbufsz);
        errno = sav_errno ? sav_errno : EINVAL;
    } else /*return the values via pointer*/ {
        *access_protocol = ap;
        *port = pn;
    }

    if (query)
        g_free(query);
    if (ld)
        close_connection(ld);
    if (service_id)
    	free(service_id);	
    if (endpoint_id)
    	free(endpoint_id);	

    return (rc);
}
Esempio n. 2
0
/* get from the BDII the endpoint for the LFC */
int g2_sd_get_lfc_endpoint(char **lfc_endpoint, char *errbuf, int errbufsz) {
    LDAPMessage *entry = NULL;
    char *filter = NULL, *filter_tmp = NULL;
    int rc = 0;
    LDAPMessage *reply = NULL;
    struct berval **value = NULL;
    int sav_errno = 0;
    *lfc_endpoint = NULL;
    SDException exception;
    char *query_policy = NULL;
    char *lfc_fk = NULL;
    LDAP *ld = NULL;

    if ((filter_tmp = g2_generate_acbr("GLUE2PolicyID")) == NULL) {
        SD_setException(&exception, SDStatus_FAILURE, "[BDII][g2_sd_get_lfc_endpoint]: No GLUE2PolicyID found", errbuf, errbufsz);
        return (-1);
    }

    if ((ld = get_connection(&exception, errbuf, errbufsz)) == NULL) {
        SD_setException(&exception, SDStatus_FAILURE, "[BDII][g2_sd_get_lfc_endpoint]: Cannot connect to BDII", errbuf, errbufsz);
        return (-1);
    }

    query_policy = g_strdup_printf(GLUE2_QUERY_LFC_POLICY, filter_tmp);
    free(filter_tmp);



    while (!*lfc_endpoint && !sav_errno) {

        /*get first the policy rule for a particular vo*/
        rc = connect_search_ldap(glue2_base, query_policy, g2_lfc_endpoint_foreign_key_attrs, ld, &exception, &reply, errbuf, errbufsz);
        if (rc != LDAP_SUCCESS) {
            if (reply) {
                ldap_msgfree(reply);
            }
            sav_errno = errno;
            break;
        }
        if ((entry = ldap_first_entry(ld, reply)) && (value = ldap_get_values_len(ld, entry, GLUE2_ACCESS_POLICY_FK))) {
            if (value && value[0]->bv_val) {
                if ((lfc_fk = strdup(value[0]->bv_val)) == NULL)
                    sav_errno = errno ? errno : ENOMEM;
                ldap_value_free_len(value);
            }
        }

        /*now get the lfc endpoint*/
        rc = asprintf(&filter, GLUE2_QUERY_LFC_ENDPOINT, lfc_fk);
        free(lfc_fk);



        if (rc < 0) {
            if (reply) {
                ldap_msgfree(reply);
            }
            if (filter)
                free(filter);
            break;
        }

        rc = connect_search_ldap(glue2_base, filter, g2_lfc_endpoint_attrs, ld, &exception, &reply, errbuf, errbufsz);
        if (rc != LDAP_SUCCESS) {
            if (reply) {
                ldap_msgfree(reply);
            }
            if (filter)
                free(filter);
            sav_errno = errno;
            break;
        }
        if ((entry = ldap_first_entry(ld, reply)) && (value = ldap_get_values_len(ld, entry, GLUE2_ATTR_ENDPOINT))) {
            if (value && value[0]->bv_val) {
                if ((*lfc_endpoint = strdup(value[0]->bv_val)) == NULL)
                    sav_errno = errno ? errno : ENOMEM;
                ldap_value_free_len(value);
            }
        }

        if (reply)
            ldap_msgfree(reply);
        if (filter)
            free(filter);
	    
	if(!*lfc_endpoint)
	  break;
    }

    if (query_policy)
        g_free(query_policy);
    if (ld)
        close_connection(ld);


    if (!*lfc_endpoint) {
        if (!sav_errno) {            
            sav_errno = EINVAL;
        }
        SD_setException(&exception, SDStatus_FAILURE, "[BDII][g2_sd_get_lfc_endpoint]: No LFC Endpoint found", errbuf, errbufsz);
        errno = sav_errno;
        return (-1);
    }

    return 0;
}
Esempio n. 3
0
int g2_sd_get_se_types_and_endpoints(const char *host, char ***se_types,
        char ***se_endpoints, char *errbuf, int errbufsz) {
    char host_tmp[255];
    int len_tmp = 0;
    char *port = NULL;
    LDAPMessage *entry = NULL;
    SDException exception;
    char *query = NULL;
    int i, nbentries = 0, n = 0, rc = 0;
    char **sep = NULL, **stp = NULL, **st = NULL, **sv = NULL, **ep = NULL;
    struct berval **value = NULL;
    int sav_errno = 0;
    LDAPMessage *reply = NULL;
    LDAP *ld = NULL;
    char *service_id = NULL;
    char *endpoint_id = NULL;    

    *se_types = NULL;
    *se_endpoints = NULL;

    if (!host) {
        SD_setException(&exception, SDStatus_FAILURE, "[BDII][g2_sd_get_se_types_and_endpoints]: Hostname in empty", errbuf, errbufsz);
        return -1;
    }


    if ((ld = get_connection(&exception, errbuf, errbufsz)) == NULL) {
        SD_setException(&exception, SDStatus_FAILURE, "[BDII][g2_sd_get_se_types_and_endpoints]: Cannot connect to BDII", errbuf, errbufsz);
        return (-1);
    }

    g2_sd_get_service_id(ld, host, &service_id, &endpoint_id, errbuf, errbufsz);
    if(!service_id)
    {
        SD_setException(&exception, SDStatus_FAILURE, "[BDII][g2_sd_get_se_types_and_endpoints]: ServiceID cannot be found", errbuf, errbufsz);
	if(ld)
		close_connection(ld);
	return (-1);      
	
    }       

    strncpy(host_tmp, host, 255);

    if ((port = strchr(host_tmp, ':')) != NULL)
        *port = 0;

    query = g_strdup_printf(GLUE2_QUERY_TYPE_ENDPOINTS, service_id);



    while (nbentries < 1 && !sav_errno) {

        rc = connect_search_ldap(glue2_base, query, NULL, ld, &exception, &reply, errbuf, errbufsz);
        if (rc != LDAP_SUCCESS) {
            if (reply) {
                ldap_msgfree(reply);
            }
            rc = -1;
            sav_errno = errno;
            break;
        }

        if ((nbentries = ldap_count_entries(ld, reply)) < 1) {
            SD_setException(&exception, SDStatus_FAILURE, "[BDII][g2_sd_get_se_types_and_endpoints]: No entries found for host.", errbuf, errbufsz);
            if (reply) {
                ldap_msgfree(reply);
            }
            rc = -1;
            break;
        }

        ++nbentries;
        if ((st = calloc(nbentries, sizeof (char *))) == NULL || (sv = calloc(
                nbentries, sizeof (char *))) == NULL || (ep = calloc(nbentries,
                sizeof (char *))) == NULL || (stp = calloc(nbentries,
                sizeof (char *))) == NULL || (sep = calloc(nbentries,
                sizeof (char *))) == NULL) {
            if (reply) {
                ldap_msgfree(reply);
            }

            sav_errno = errno ? errno : ENOMEM;
            rc = -1;
            break;
        }

        for (entry = ldap_first_entry(ld, reply); entry != NULL && rc == 0; entry
                = ldap_next_entry(ld, entry)) {

            if ((value = ldap_get_values_len(ld, entry, GLUE2_ATTR_ENDPOINT)) != NULL) {
                if (value && value[0]->bv_val) {
                    ep[n] = strdup(value[0]->bv_val);
                    if (value)
                        ber_bvecfree(value);

                    if ((value = ldap_get_values_len(ld, entry, GLUE2_ATTR_TYPE)) == NULL) {
                        if (value && ep[n]) {
                            ber_bvecfree(value);
                            free(ep[n]);
                            continue;
                        }
                    }
                    if (st)
                        st[n] = strdup(value[0]->bv_val);
                    if (value)
                        ber_bvecfree(value);

                    if ((value = ldap_get_values_len(ld, entry, GLUE2_ATTR_VERSION))
                            == NULL) {
                        if (value && ep[n] && st[n]) {
                            ber_bvecfree(value);
                            free(ep[n]);
                            free(st[n]);
                            continue;
                        }
                    }
                    if (sv && value && value[0]->bv_val)
                        sv[n] = strdup(value[0]->bv_val);
                    if (value)
                        ber_bvecfree(value);
                    ++n;
                }
            } else {
                if (port == NULL) {
                    /* If port is not yet defined in host_tmp, and is available
                    // it is copied to host_tmp buffer
                    // ... But it will only be used if there is no GLUE2EndpointURL entry */
                    if (value)
                        ber_bvecfree(value);

                    value = ldap_get_values_len(ld, entry, "GLUE2EndpointURL");
                    if (value == NULL) {
                        if (nbentries == 1) {
                            sav_errno = EINVAL;
                            SD_setException(&exception, SDStatus_FAILURE, "[BDII][g2_sd_get_se_types_and_endpoints]: No port published in the BDII for Glue2", errbuf, errbufsz);
                        }
                    } else if (value && value[0]->bv_val && len_tmp + strlen(value[0]->bv_val) + 1 < 255) {
                        port = host_tmp + len_tmp;
                        strcpy(port + 1, value[0]->bv_val);

                    } else {
                        if (value)
                            ber_bvecfree(value);
                        sav_errno = ENAMETOOLONG;
                        if (reply) {
                            ldap_msgfree(reply);
                        }

                        break;
                    }

                }
                if (value)
                    ber_bvecfree(value);
            }
        }
        if (reply) {
            ldap_msgfree(reply);
        }

    }

    if (rc < 0) {
        for (i = 0; i < n; ++i) {
            if (st && st[i])
                free(st[i]);
            if (sv && sv[i])
                free(sv[i]);
            if (ep && ep[i])
                free(ep[i]);
        }
        if (st)
            free(st);
        if (sv)
            free(sv);
        if (ep)
            free(ep);
        if (stp)
            free(stp);
        if (sep)
            free(sep);
        errno = sav_errno ? sav_errno : EINVAL;
        SD_setException(&exception, SDStatus_FAILURE, "[BDII][g2_sd_get_se_types_and_endpoints]: No available information", errbuf, errbufsz);
    } else {
        if (n > 0) {

            for (i = 0; i < n; ++i) {
                if ((strcmp(st[i], "srm_v1") == 0 || strcmp(st[i], "srm_v2")
                        == 0) && ep[i]) {
                    stp[i] = strdup(st[i]);
                    sep[i] = strdup(ep[i]);
                } else if ((strcasecmp(st[i], "SRM") == 0) && (strncmp(sv[i],
                        "1.", 2)) == 0 && ep[i]) {
                    stp[i] = strdup("srm_v1");
                    sep[i] = strdup(ep[i]);
                } else if ((strcasecmp(st[i], "SRM") == 0) && (strncmp(sv[i],
                        "2.2", 3)) == 0 && ep[i]) {
                    stp[i] = strdup("srm_v2");
                    sep[i] = strdup(ep[i]);
                }
                free(st[i]);
                free(sv[i]);
                free(ep[i]);
            }
            free(st);
            free(sv);
            free(ep);
        } else if (n == 0 && port != NULL && stp && sep) {
            /* There were no GLUE2EndpointID entries...
            // ... so endpoint is hostname:port, and type is disk */
            *port = ':';
            stp[0] = strdup("disk");
            sep[0] = strdup(host_tmp);
        } else {
            free(stp);
            free(sep);
            rc = -1;
            SD_setException(&exception, SDStatus_FAILURE, "[BDII][g2_sd_get_se_types_and_endpoints]: No available information found for SE", errbuf, errbufsz);
            errno = EINVAL;

        }

        if (rc == 0) {
            *se_types = stp;
            *se_endpoints = sep;
        }
    }

    if (ld)
        close_connection(ld);
    if (query)
        g_free(query);
    if (service_id)
    	free(service_id);	 
    if (endpoint_id)
    	free(endpoint_id);	 

    return (rc);
}
Esempio n. 4
0
int g2_sd_is_online(char *host, char *errbuf, int errbufsz) {
    char host_tmp[255];
    LDAPMessage *reply = NULL;
    SDException exception;
    LDAP *ld = NULL;
    char *query = NULL;
    int rc = 0;
    int is_production = 0;
    char *service_id = NULL;
    char *endpoint_id = NULL;    

    if (!host) {
        SD_setException(&exception, SDStatus_FAILURE, "[BDII][g2_sd_is_online]: Host is empty", errbuf, errbufsz);
        return (-1);
    }

    if ((ld = get_connection(&exception, errbuf, errbufsz)) == NULL) {
        SD_setException(&exception, SDStatus_FAILURE, "[BDII][g2_sd_is_online]: Cannot connect to BDII", errbuf, errbufsz);
        return (-1);
    }

    g2_sd_get_service_id(ld, host, &service_id, &endpoint_id, errbuf, errbufsz);
    if(!service_id)
    {
        SD_setException(&exception, SDStatus_FAILURE, "[BDII][g2_sd_is_online]: ServiceID cannot be found", errbuf, errbufsz);
	if(ld)
		close_connection(ld);
	return (-1);      
        	
    }        

    strncpy(host_tmp, host, 255);

    query = g_strdup_printf(GLUE2_QUERY_SE_STATUS, service_id);



    rc = connect_search_ldap(glue2_base, query, NULL, ld, &exception, &reply, errbuf, errbufsz);
    if (rc != LDAP_SUCCESS) {
        SD_setException(&exception, SDStatus_FAILURE, "[BDII][g2_sd_is_online]: No available information", errbuf, errbufsz);
        goto out;
    }

    if ((ldap_count_entries(ld, reply)) < 1)
        is_production = 0;
    else
        is_production = 1;


out:
    if (service_id)
    	free(service_id);
    if (endpoint_id)
    	free(endpoint_id);	
    if (reply)
        ldap_msgfree(reply);
    if (query)
        g_free(query);
    if (ld)
        close_connection(ld);

    if (is_production == 0)
        return (-1);

    return 0;
}
Esempio n. 5
0
int g2_sd_get_ce_ap(const char *host, char **ce_ap, char *errbuf, int errbufsz) {
    LDAPMessage *entry = NULL;
    SDException exception;
    LDAPMessage *reply = NULL;
    struct berval **value = NULL;
    char *query = NULL;
    int sav_errno = 0;
    *ce_ap = NULL;
    int rc = 0;
    LDAP *ld = NULL;
    char *service_id = NULL;
    char *endpoint_id = NULL;

    if (!host) {
        SD_setException(&exception, SDStatus_FAILURE, "[BDII][g2_sd_get_ce_ap]: Hostname is not specified", errbuf, errbufsz);
        return (-1);
    }



    if ((ld = get_connection(&exception, errbuf, errbufsz)) == NULL) {
        SD_setException(&exception, SDStatus_FAILURE, "[BDII][g2_sd_get_ce_ap]: Cannot connect to BDII", errbuf, errbufsz);
        if (query)
            g_free(query);
        return (-1);
    }

    g2_sd_get_service_id(ld, host, &service_id, &endpoint_id, errbuf, errbufsz);
    if(!service_id)
    {
        SD_setException(&exception, SDStatus_FAILURE, "[BDII][g2_sd_get_ce_ap]: ServiceID cannot be found", errbuf, errbufsz);
        if(endpoint_id)
		free(endpoint_id);
	if(ld)
		close_connection(ld);
	return (-1);      
	
    }        

    query = g_strdup_printf(GLUE2_QUERY_CESE_BIND, service_id);



       rc = connect_search_ldap(glue2_base, query, g2_ce_ap_attrs, ld, &exception, &reply, errbuf, errbufsz);
        if (rc != LDAP_SUCCESS) {
           if (reply)
                ldap_msgfree(reply);
            if (query)
               g_free(query);
	    if (ld)
        	close_connection(ld);
	    if(service_id)
	    	free(service_id);		
            sav_errno = errno;
	    rc = -1;
	    goto out;
            
        }



        if ((1 > ldap_count_entries(ld, reply))) {
            if (reply)
                ldap_msgfree(reply);
            if (query)
               g_free(query);
	    if (ld)
        	close_connection(ld);	       
	    if(service_id)
	    	free(service_id);				
            goto out;
        }


        for (entry = ldap_first_entry(ld, reply); entry != NULL && rc == 0; entry
                = ldap_next_entry(ld, entry)) {


        if ((entry = ldap_first_entry(ld, reply)) && (value
                = ldap_get_values_len(ld, entry, GLUE2_ATTR_CE_AP_ATNM))) {
            if (value && value[0]->bv_val) {
                if ((*ce_ap = strdup(value[0]->bv_val)) == NULL) {
                    sav_errno = errno ? errno : ENOMEM;
                }
                ber_bvecfree(value);
            }
        }

        if (reply)
            ldap_msgfree(reply);
        if(*ce_ap)
	    break;
    }

    if (query)
        g_free(query);
    if (ld)
        close_connection(ld);
    if(service_id)
	    	free(service_id);			
    if(endpoint_id)
	    	free(endpoint_id);					

out:
    if (!*ce_ap) {
        if (!sav_errno) {
            sav_errno = EINVAL;
        }
        SD_setException(&exception, SDStatus_FAILURE, "[BDII][g2_sd_get_ce_ap]: No GLUE2ToComputingServiceID or GLUE2ToComputingServiceLocalPath found.", errbuf, errbufsz);
        errno = sav_errno;
        return (-1);
    }
    return (0);
}
Esempio n. 6
0
int player::init(OBJECT *parent)
{
	// check the connection
	if ( get_connection()!=NULL )
		db = (database*)(get_connection()+1);
	if ( db==NULL )
		exception("no database connection available or specified");
	if ( !db->isa("database") )
		exception("connection is not a mysql database");
	gl_verbose("connection to mysql server '%s', schema '%s' ok", db->get_hostname(), db->get_schema());

	// check mode
	if ( strlen(mode)>0 )
	{
		int options = 0xffffffff;
		struct {
			char *str;
			set bits;
		} modes[] = {
			{"r",	0x0000},
			{"r+",	0x0000},
			{"w",	0xffff},
			{"w+",	0xffff},
			{"a",	0xffff},
			{"a+",	0xffff},
		};
		int n;
		for ( n=0 ; n<sizeof(modes)/sizeof(modes[0]) ; n++ )
		{
			if ( strcmp(mode,modes[n].str)==0 )
			{
				options = modes[n].bits;
				break;
			}
		}
		if ( options==0xffffffff )
			exception("mode '%s' is not recognized",mode);
		else if ( options==0xffff )
			exception("mode '%s' is not valid for a recorder", mode);
	}

	// connect the target property
	if ( get_parent()==NULL )
		exception("parent is not set");
	target.set_object(get_parent());
	char propname[64]="", propunit[64]="";
	switch ( sscanf(get_property(),"%[^[][%[^]]",propname,propunit) ) {
	case 2:
		if ( !unit.set_unit(propunit) )
			exception("property '%s' has an invalid unit", get_property());
		// drop through
	case 1:
		strncpy(field,propname,sizeof(field)-1);
		target.set_property(propname);
		scale = 1.0;
		if ( unit.is_valid() && target.get_unit()!=NULL )
		{
			target.get_unit()->convert(unit,scale);
			sprintf(field,"%s[%s]",propname,propunit);
		}
		else if ( propunit[0]=='\0' && options&MO_USEUNITS && target.get_unit() )
			sprintf(field,"%s[%s]",propname,target.get_unit()->get_name());
		break;
	default:
		exception("property '%s' is not valid", get_property());
		break;
	}

	// check for table existence and create if not found
	if ( !target.is_valid() )
		exception("target property '%s' is not valid", get_property());
	if ( !db->table_exists(get_table()) )
		exception("table '%s' does not exist", get_table());

	// run the main query
	gld_clock start;
	data = db->select("SELECT t,`%s` FROM `%s` WHERE t>=from_unixtime(%llu) ORDER BY id",get_property(),get_table(),start.get_localtimestamp());
	if ( data==NULL )
		return 0; // no data
	n_rows = mysql_num_rows(data);
	n_fields = mysql_num_fields(data);
	row_num = 0;
	gl_verbose("%s: %d rows with %d fields found", get_name(), n_rows, n_fields);

	// fetch first row
	row = mysql_fetch_row(data);
	row_num++;
	fields = mysql_fetch_fields(data);

	// get the time of the next data item (assume in first column)
	gld_clock next(row[0]);
	next_t = next.get_timestamp();
	gl_verbose("%s: row %d, %s='%s', %s='%s'", get_name(), row_num, fields[0].name, row[0], fields[1].name, row[1]);
	return 1;
}
Esempio n. 7
0
/* Send a packet to the TCP connection.
 *
 * return -1 on failure.
 * return 0 on success.
 */
int send_packet_tcp_connection(TCP_Connections *tcp_c, int connections_number, const uint8_t *packet, uint16_t length)
{
    TCP_Connection_to *con_to = get_connection(tcp_c, connections_number);

    if (!con_to) {
        return -1;
    }

    // TODO(irungentoo): detect and kill bad relays.
    // TODO(irungentoo): thread safety?
    unsigned int i;
    int ret = -1;

    bool limit_reached = 0;

    for (i = 0; i < MAX_FRIEND_TCP_CONNECTIONS; ++i) {
        uint32_t tcp_con_num = con_to->connections[i].tcp_connection;
        uint8_t status = con_to->connections[i].status;
        uint8_t connection_id = con_to->connections[i].connection_id;

        if (tcp_con_num && status == TCP_CONNECTIONS_STATUS_ONLINE) {
            tcp_con_num -= 1;
            TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_con_num);

            if (!tcp_con) {
                continue;
            }

            ret = send_data(tcp_con->connection, connection_id, packet, length);

            if (ret == 0) {
                limit_reached = 1;
            }

            if (ret == 1) {
                break;
            }
        }
    }

    if (ret == 1) {
        return 0;
    }

    if (!limit_reached) {
        ret = 0;

        /* Send oob packets to all relays tied to the connection. */
        for (i = 0; i < MAX_FRIEND_TCP_CONNECTIONS; ++i) {
            uint32_t tcp_con_num = con_to->connections[i].tcp_connection;
            uint8_t status = con_to->connections[i].status;

            if (tcp_con_num && status == TCP_CONNECTIONS_STATUS_REGISTERED) {
                tcp_con_num -= 1;
                TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_con_num);

                if (!tcp_con) {
                    continue;
                }

                if (send_oob_packet(tcp_con->connection, con_to->public_key, packet, length) == 1) {
                    ret += 1;
                }
            }
        }

        if (ret >= 1) {
            return 0;
        }

        return -1;
    }

    return -1;
}
Esempio n. 8
0
SharingPluginInterfaceSendResult
sharing_plugin_interface_send (SharingTransfer* transfer, ConIcConnection* con,
    gboolean* dead_mans_switch)
{
	SharingEntry *entry = sharing_transfer_get_entry (transfer);
	DBusGConnection* connection = get_connection ();
	GSList* p;
	DBusGProxy *uploader = NULL;

	if (!connection)
	{
		return SHARING_SEND_ERROR_UNKNOWN;
	}

	uploader = dbus_g_proxy_new_for_name (connection,
			"com.imgur", 
			"/com/imgur",
			"com.imgur");
	
	for (p=sharing_entry_get_media (entry); p; p=g_slist_next (p))
	{
		SharingEntryMedia* media = p->data;
		GError *error = NULL;
		gchar *url = NULL;
		GHashTable *result = NULL;
		const gchar *filename =
			sharing_entry_media_get_localpath (media);
	
		if (sharing_entry_media_get_sent (media))
			continue; /* it was already sent */

		/* Great, so let's send it. */

		if (com_imgur_upload (uploader, filename, &result, &error))
		{
			GValue *url_v = g_hash_table_lookup (result, "imgur_page");

			if (url_v)
				url = g_strdup (g_value_get_string (url_v));

			if (result)
				g_hash_table_unref (result);
		}
		else
		{
			g_warning ("Error in upload: %s", error->message);
			g_error_free (error);
			return SHARING_SEND_ERROR_UNKNOWN;
		}

		if (url)
		{
			/* looks like a successful operation */
	
			/*
			 * At some point we may want a configuration
			 * setting that means that the libsharing
			 * plugin does *not* launch the browser.
			 * But this will only become useful when
			 * there is a GUI app to look at existing
			 * uploads.
			 */
	
			if (!launch_browser (connection, url))
			{
				g_free (url);
				return SHARING_SEND_ERROR_UNKNOWN;
			}

			g_free (url);
			sharing_entry_media_set_sent (media, TRUE);
		}
		else
		{
			return SHARING_SEND_ERROR_UNKNOWN;
		}

		*dead_mans_switch = 0; /* keepalive */
	}

	/* FIXME: don't we want to unref the connection? */
	
	return SHARING_SEND_SUCCESS;
}
Esempio n. 9
0
static int send_request(char *method, const char *path, FILE *fp, xmlParserCtxtPtr xmlctx, curl_slist *extra_headers)
{
  long response = -1;
  int tries = 0;

  // retry on failures
  for (tries = 0; tries < REQUEST_RETRIES; tries++)
  {
    CURL *curl = get_connection(path);
    curl_slist *headers = NULL;
    add_header(&headers, "X-Auth-Token", storage_token);
    curl_easy_setopt(curl, CURLOPT_VERBOSE, debug);
    if (!strcasecmp(method, "MKDIR"))
    {
      curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
      curl_easy_setopt(curl, CURLOPT_INFILESIZE, 0);
      add_header(&headers, "Content-Type", "application/directory");
    }
    else if (!strcasecmp(method, "PUT") && fp)
    {
      rewind(fp);
      curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
      curl_easy_setopt(curl, CURLOPT_INFILESIZE, file_size(fileno(fp)));
      curl_easy_setopt(curl, CURLOPT_READDATA, fp);
    }
    else if (!strcasecmp(method, "GET"))
    {
      if (fp)
      {
        rewind(fp); // make sure the file is ready for a-writin'
        fflush(fp);
        ftruncate(fileno(fp), 0);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
      }
      else if (xmlctx)
      {
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, xmlctx);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &xml_dispatch);
      }
    }
    else
      curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, method);
    /* add the headers from extra_headers if any */
    curl_slist *extra;
    for (extra = extra_headers; extra; extra = extra->next)
    {
      debugf("adding header: %s", extra->data);
      headers = curl_slist_append(headers, extra->data);
    }
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_perform(curl);
    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response);
    curl_slist_free_all(headers);
    return_connection(curl);
    if (response >= 200 && response < 400)
      return response;
    sleep(8 << tries); // backoff
    if (response == 401 && !cloudfs_connect(0, 0, 0, 0)) // re-authenticate on 401s
      return response;
    if (xmlctx)
      xmlCtxtResetPush(xmlctx, NULL, 0, NULL, NULL);
  }
  return response;
}
Esempio n. 10
0
int main(int argc, char **argv)
{
    s_options _opts;
    opts = &_opts; /* Set global pointer */ 

    memset(opts,'\0',sizeof(s_options));
    opts->fcheck = 1; // Check files are available before setting up socket
    
    int opt = getopt( argc, argv, "Cvc:p:i:" );
	while( opt != -1 )
	{
	    switch( opt ) {
                case 'v':
                    opts->verbose = 1;
                    break;
                case 'c':
                    opts->count = *optarg;
                    break;
                case 'C':
                    /* Don't check if files exist before listening */
                    opts->fcheck = 0;
                    break;
                case 'p':
                    opts->port = validate_port(optarg);
                    break;
                case 'i':
                    opts->ifname = (char *)validate_if(optarg);
                    if (NULL == opts->ifname)
                        die("Copying interface name failed - %s\n",strerror(errno));
                    break;
                default:
                    die(USAGE_MSG, argv[0]);
	    };
	    opt = getopt( argc, argv, "Cvc:p:i:" );
	}
    opts->files = argv + optind;
    opts->files_num = argc - optind;
    
    // Validate arguments
    if (! opts->files[0] || strlen(*(opts->files))==0)
        die("No files to send.\n" USAGE_MSG, argv[0]);
        
    if (opts->files_num > 10)
        die("Too many files to offer. Maximum is 10 files, got %d\n", opts->files_num);
    
    int i;
    size_t a = 0;
    size_t file_args_length = 0; 

    for(i=0;i<opts->files_num;i++)
    {
        PRINTV("checking element %s\n",opts->files[i]);
        a = strlen(opts->files[i]);
        if ( a > FILENAME_MAXLEN)
            die("File name number %d is too long.\n", i);
                
        /* Check if file exists */
        if ((opts->fcheck) && (! check_file(opts->files[i])) )
            die(
                    "Failed accessing %s - %s\n", 
                    opts->files[i], 
                    strerror(errno)
            );
        file_args_length += a; // used later in http replies to calculate length
    };


    int htsock;
    conn_hdls.htsock_ptr = &htsock;

    if ((htsock = net_init()) == FAILURE)
        die("Failed initializing network connection\n");
        

    FILE *fp = NULL;
//    fp_ptr = &fp;
    conn_hdls.fp_ptr = &fp;
    int conn;
//    conn_ptr = &conn;
    conn_hdls.conn_ptr = &conn;

        
    /* Added to line breaks at the end of the reply, adjusted length accordingly */
    size_t reply_err_len = 254 + 140 + 2*file_args_length + 27*(opts->files_num); 
//    unsigned int reply_err_len = 254 + 138 + 2*file_args_length + 27*(opts->files_num); 
    char reply_error[ reply_err_len ];
    prep_reply_text(reply_error, reply_err_len);
        

    if (signal(SIGINT,sigint_handler) == SIG_ERR)
        die("Failed installing signal handler (%s)", strerror(errno));
        
    
    while((conn = get_connection(htsock)))
    {
		
        if ((fp = fdopen(conn, "w+")) == NULL)
        {
            /* Failed open a stream for this connection, close
             * connection and listen for another one
             */
            close_conn(NULL,&conn);
            continue;
        }

        if (FAILURE == handle_connection(fp, reply_error))
        {
            close_conn(&fp,&conn);
            continue;
        }
        else
        {
            /* Success */
            close_conn(&fp,&conn);
            break;
        }
                
    } //while()
    
    if (close(htsock))
        fprintf(stderr, "Failed closing socket - %s", strerror(errno));

    free_am(); /* Free general purpose allocated memory */
    return(EXIT_SUCCESS); 
} // main()
Esempio n. 11
0
static int send_request(char *method, const char *path, FILE *fp,
                        xmlParserCtxtPtr xmlctx, curl_slist *extra_headers)
{
  char url[MAX_URL_SIZE];
  char *slash;
  long response = -1;
  int tries = 0;

  if (!storage_url[0])
  {
    debugf("send_request with no storage_url?");
    abort();
  }

  while ((slash = strstr(path, "%2F")) || (slash = strstr(path, "%2f")))
  {
    *slash = '/';
    memmove(slash+1, slash+3, strlen(slash+3)+1);
  }
  while (*path == '/')
    path++;
  snprintf(url, sizeof(url), "%s/%s", storage_url, path);

  // retry on failures
  for (tries = 0; tries < REQUEST_RETRIES; tries++)
  {
    CURL *curl = get_connection(path);
    if (rhel5_mode)
      curl_easy_setopt(curl, CURLOPT_CAINFO, RHEL5_CERTIFICATE_FILE);
    curl_slist *headers = NULL;
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_HEADER, 0);
    curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
    curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1);
    curl_easy_setopt(curl, CURLOPT_USERAGENT, USER_AGENT);
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, verify_ssl);
    curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);
    curl_easy_setopt(curl, CURLOPT_VERBOSE, debug);
    add_header(&headers, "X-Auth-Token", storage_token);
    if (!strcasecmp(method, "MKDIR"))
    {
      curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
      curl_easy_setopt(curl, CURLOPT_INFILESIZE, 0);
      add_header(&headers, "Content-Type", "application/directory");
    }
    else if (!strcasecmp(method, "PUT") && fp)
    {
      rewind(fp);
      curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
      curl_easy_setopt(curl, CURLOPT_INFILESIZE, cloudfs_file_size(fileno(fp)));
      curl_easy_setopt(curl, CURLOPT_READDATA, fp);
    }
    else if (!strcasecmp(method, "GET"))
    {
      if (fp)
      {
        rewind(fp); // make sure the file is ready for a-writin'
        fflush(fp);
        if (ftruncate(fileno(fp), 0) < 0)
        {
          debugf("ftruncate failed.  I don't know what to do about that.");
          abort();
        }
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
      }
      else if (xmlctx)
      {
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, xmlctx);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &xml_dispatch);
      }
    }
    else
      curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, method);
    /* add the headers from extra_headers if any */
    curl_slist *extra;
    for (extra = extra_headers; extra; extra = extra->next)
    {
      debugf("adding header: %s", extra->data);
      headers = curl_slist_append(headers, extra->data);
    }
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_perform(curl);
    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response);
    curl_slist_free_all(headers);
    curl_easy_reset(curl);
    return_connection(curl);
    if (response >= 200 && response < 400)
      return response;
    sleep(8 << tries); // backoff
    if (response == 401 && !cloudfs_connect()) // re-authenticate on 401s
      return response;
    if (xmlctx)
      xmlCtxtResetPush(xmlctx, NULL, 0, NULL, NULL);
  }
  return response;
}
Esempio n. 12
0
static HippoPlatform*
get_platform(HippoQuipWindow *quip_window)
{
    return hippo_connection_get_platform(get_connection(quip_window));
}
Esempio n. 13
0
void MainWindow::openGDHE()
{
    char nomfich[1000];
	char* junk;
	size_t junklength = 1000;
	
	//char * fileName = strdup(LOG_NAME);
    //sprintf(nomfich, "%s/scan%06d.txt", fileName.c_str(), nb_scan);
	sprintf(nomfich, "%s", MTI_LOG_NAME);
	printf("mti file:%s\n", nomfich);
	Fscanmti = fopen(nomfich, "rt");
	
	junk = (char *) malloc (junklength + 1);
	for (int i=0;i<4;i++) { 
		getline(&junk,&junklength,Fscanmti);
		printf("Junk %s",junk);
	}
	/*int res = fscanf(Fscanmti,"%s\n", junk);
	printf("Junk %s",junk);
	res = fscanf(Fscanmti,"%s\n", junk);
	printf("Junk %s",junk);
	res = fscanf(Fscanmti,"%s\n", junk);
	printf("Junk %s",junk);*/

    if( gdhe_open == false ) {
        button_open_gdhe->setText("close GDHE");
        gdhe_open=true;

        // Open GDHE
        //int res = system("gdhe &");
		//if (res == 0) {printf("gdhe started ok\n");}
        // Sleep to allow full opening of GDHE, then connect
        //sleep(3);

        int error = get_connection((char *)"localhost");
		//int error = get_connection((char *)"140.93.7.255");
		//int error = get_connection((char *)"140.93.4.43");
 
        printf("get_con ret: %d\n",error);

        // Coordinate Frame at origin
        //eval_expression((char *)"set robots(coordFrame) { color 0 255 0; repere }");
        //eval_expression((char *)"set pos(coordFrame) { 0 0 0 0 0 0  }");

        // Draw IMU Coordinate System
        //eval_expression((char *)"set robots(IMU) { color 0 0 255; repere }");
        // eval_expression("set pos(IMU) { -90 0 -90 0 0 8 }");

        // Draw Camera
        //eval_expression("set robots(Drone) { camera 7.5 47.5 39.6 }");
        //eval_expression("set pos(Drone) { -90 0 -90 0 0 8 }");
        //eval_expression("set robots(esfera) { color 0 0 255 ; sphere 1 1 3 .05 }");
        //eval_expression("set pos(esfera) { 0 0 0 0 0 0 }");

        // Grid
        eval_expression((char *)"set robots(grid) { color 75 75 0; grille -50 -50 50 50 1 }");
        eval_expression((char *)"set pos(grid) { 0 0 0 0 0 0 }");
		
		eval_expression(truc.toLatin1().data());
		printf("%s\n",truc.toLatin1().data());
		
		//eval_expression((char *)"set robots(truc) { truc }");
        //eval_expression((char *)"set pos(truc) { 0 0 0 }");
	
		//eval_expression((char *)"set robots(r1) { xr4000 }");
        //eval_expression((char *)"set pos(r1) { 0 0 0 0 0 0 }");

        //GDHE_client_prot::disconnect();??
        /*
        while(1)
        {
            bool success = mti.read(&data, true);

            // If GDHE is open, show in real time the IMU orientation
                // Form instruction to change IMU orientation on-screen
                QString setIMU = "set pos(IMU) { ";
                QTextStream(&setIMU) << data.EULER[2] << " " << data.EULER[1] << " " << data.EULER[0] << " 0 0 8 }";
                // Evaluate expression
                QByteArray text = setIMU.toLatin1();
                char *text2 = text.data();
                eval_expression(text2);
            }*/
    // (gdhe == true)
    } else {
        gdhe_open = false;
        button_open_gdhe->setText("open GDHE");
        /*
            QString disconnect = "disconnect()";
            QByteArray textdisconnect = disconnect.toLatin1();
            char *text2disconnect = textdisconnect.data();
            eval_expression(text2disconnect);*/
        QString exit = "exit";
        eval_expression(exit.toLatin1().data());
    }
}
Esempio n. 14
0
/*
 * ip_main --
 *      This is the main loop for the vi-as-library editor.
 */
int
main(int argc, char **argv)
{
	IP_PRIVATE *ipp;
	int rval;
	char *ip_arg;
	char **p_av, **t_av;
	GS *gp;
	WIN *wp;
	int i_fd, o_fd, t_fd, main_ifd, main_ofd;

	/* Create and initialize the global structure. */
	__global_list = gp = gs_init(argv[0]);

	/*
	 * Strip out any arguments that vi isn't going to understand.  There's
	 * no way to portably call getopt twice, so arguments parsed here must
	 * be removed from the argument list.
	 */
	ip_arg = NULL;
	for (p_av = t_av = argv;;) {
		if (*t_av == NULL) {
			*p_av = NULL;
			break;
		}
		if (!strcmp(*t_av, "--")) {
			while ((*p_av++ = *t_av++) != NULL);
			break;
		}
		if (!memcmp(*t_av, "-I", sizeof("-I") - 1)) {
			if (t_av[0][2] != '\0') {
				ip_arg = t_av[0] + 2;
				++t_av;
				--argc;
				continue;
			}
			else if (t_av[1] != NULL) {
				ip_arg = t_av[1];
				t_av += 2;
				argc -= 2;
				continue;
			}
		}
		*p_av++ = *t_av++;
	}

	if (get_fds(ip_arg, &main_ifd, &main_ofd))
		return 1;

	wp = NULL;

	while (get_connection(wp, main_ifd, main_ofd, &i_fd, &o_fd, &t_fd, 1) == 0) {
		/* Create new window */
		wp = gs_new_win(gp);

		/* Create and partially initialize the IP structure. */
		if ((ipp = ip_init(wp, i_fd, o_fd, t_fd, argc, argv)) == NULL)
			return (1);

		gp->run(wp, run_editor, (void *)wp);
	}

	/* Clean out the global structure. */
	gs_end(gp);

	/* Free the global and IP private areas. */
#if defined(DEBUG) || defined(PURIFY) || defined(LIBRARY)
	free(gp);
#endif
	exit (rval);
}
Esempio n. 15
0
/**************************** SUBROUTINES ******************************/
int main()
{
        int sfd, device_type, channel,num_of_3g;
        struct sockaddr_in saddr;
        socklen_t len;
	pthread_t wifi, threeg;
	char name[16];
	

        init_vrms_connection();
        init_logging_network_changes();	
#if 0
	while(1){

		send_vrms_data("wlan0", 5);
		printf("wlan0 sent\n");
		sleep(30);
		send_vrms_data("ppp1", 4);
		printf("ppp1 sent\n");
		sleep(22);
#if 0
		send_vrms_data("ppp1", 4);
		printf("wlan0 sent\n");
		sleep(30);
		send_vrms_data("ppp2", 4);
		printf("ppp2 sent\n");
		sleep(30);
#endif
		send_vrms_data("ppp2", 4);
		printf("ppp2 sent\n");
		sleep(20);
	}
#endif
	openlog("SeaMo:VHO", LOG_PID, LOG_DAEMON);

	/* Obtain a D-Bus connection handler for all D-Bus activities */
	conn = (DBusConnection *) get_connection();

        init_3g_connections();
	/* socket creation for communication with vrms. (earlier this was 
  	   done in get_current_network every time it was called which is not
 	   necessary)*/
 /* Connect to the available modems */
	connect_all_modems(conn); 
	/* Check if the system is currently connected to any network */
	while (!isconnected(conn)) {
		syslog(LOG_WARNING,
		       "Please connect to any available network\n");
		sleep(1);
	}
/*
	char *active_conn[30];
	get_active_conn(conn, active_conn);

	while (1) {
		syslog(LOG_INFO, "Inside while\n");
		int conn_state = get_active_conn_state(conn, *active_conn);
		if (conn_state == 0 || conn_state == -1)	//Unknown state
			syslog(LOG_ERR, "Not Connected to any network\n");
		else if (conn_state == CONNECTED)
			break;
		else if (conn_state == ACTIVATING)
			continue;
	}
*/
	system ("sh /usr/local/seamo/sbin/ip_rules_all.sh");	

	/* Create threads to receive data from pre-handoff */
	if (pthread_create(&threeg, NULL, threeg_data, NULL)) {
		syslog(LOG_ERR, "error in server threads\n");
	}
	if (pthread_create(&wifi, NULL, wifi_data, NULL)) {
		syslog(LOG_ERR, "error in server threads\n");
	}

	read_config();

	/* Get the signal when the parent process dies */
	prctl(PR_SET_PDEATHSIG, SIGHUP);


	while (1) {
		wifi_avail = wifi_param();

      	
                num_of_3g = get_num_of_modems(conn);
          
                if ( num_of_3g >=1){
               	threeg_avail = threeg_param();
                }
                
                else {
                   threeg_avail == -1 ;
                   }



		syslog(LOG_INFO, "wifi_avail: %d, threeg_avail: %d\n",
		       wifi_avail, threeg_avail);

		if (wifi_avail == 1 || threeg_avail == 1) {
			get_current_network(&device_type, name, &channel);

#ifdef DEBUG_L1
			syslog(LOG_INFO, "Current network: %s %d\n", name,
			       channel);
#endif

			/* If currently connected to Wi-Fi then keep the network
			 * under Observation. If the network conditions goes down
			 * then trigger the algorithm. But in case of 3G we dont 
			 * keep the network under observation, because 3G is assumed
			 * to be every where, the conditions of 3G will remain almost
			 * the same, hence we look for better Wi-Fi instead of waiting 
			 * for 3G network to degrade  */
			sleep(1);
			if (device_type == WIFI) {
				observe_wifi(name, channel);
				vho_trigger();
			} else if (device_type == GSM){
				observe_3g(name);
				vho_trigger();
			}
		}

		/* Check if parent process is alive */
		if (getppid() == 1)
			kill(getpid(), SIGHUP);
	}
	closelog();
	return 0;
}
Esempio n. 16
0
 int main(void){
	char user_input[BUFFER_SIZE];
	uint8_t tid = 0;
	bzero((char *)&server_addr, sizeof(server_addr));
	/******************************************
	Peripheral initialization
	gpio and i2c PCA9685
	Gain access to peripheral memory structures
	******************************************/
	map_peripheral_BCM2835(&gpio);
	map_peripheral_BCM2835(&bsc0);
	init_I2C_protocol();
	
	// Board setup 
	init_PCA9685(SERVOHATADDR);
	set_PWM_frequency_PCA9685(SERVOHATADDR, SERVO_FREQUENCY);
	init_angle_to_pulse_length_lookup_table();
	
	printf("Set Servo Driver...\n");
	
	init_PCA9685(MOTORADDRESS);
	set_PWM_frequency_PCA9685(MOTORADDRESS, MOTOR_FREQUENCY);
	stop_DC_motor(MOTORADDRESS, 0);
	stop_DC_motor(MOTORADDRESS, 1);
	stop_DC_motor(MOTORADDRESS, 2);
	stop_DC_motor(MOTORADDRESS, 3); 
	printf("Set Motor Driver...\n");
  
	/*****************************************/
	printf("main Thread Creating Threads\n");
	printf("Creating servo thread...\n");
	thread_id = pthread_create(&thread_base, NULL, (void*)thread_maintain_database, (void *)&tid);


	//main thread for getting control data from pi
	get_connection(&server_addr, &sockfd);
	listen(sockfd, 5);
	bzero((char *)&client_addr, sizeof(client_addr));
	clienlen = sizeof(client_addr);
	newconnection = accept(sockfd, (struct sockaddr*)&client_addr, &clienlen);

	if(newconnection < 0){
		perror("Accept Error: ");
		exit(1);
	}

	printf("Connected to a Client\n");
	//printf("************************\n");
	printf("Main thread listen to data port\n" );
	
	//main thread reading data from client
	//********************************************
	
	

	while(1){
		//printf("haha\n");
		bzero(user_input, BUFFER_SIZE);
		int n = read(newconnection, user_input, BUFFER_SIZE);
		
		if(n < 0)
			 perror("error: ");
		else if (n == 0) 
			continue;
		
		
		//printf("dido\n");
		if(n < BUFFER_SIZE){    
			raw_newdata = (struct data *)malloc(sizeof(struct data));
			raw_newdata->data = (char *)malloc(sizeof(char) * BUFFER_SIZE);

			
			pthread_mutex_lock(&raw_data_lock);
			if(raw_head == NULL){
				raw_head = raw_newdata;
				raw_head->next = NULL;
				raw_head->prev = raw_head;
				strcpy(raw_head->data, user_input);
				printf("new data: %s\n",raw_head->data);
				raw_curr = raw_head;

				printf("-----------------------\n");
				raw_curr = raw_head;
				int counter = 0;

				while(raw_curr != NULL){
					//printf("old data: %s\n", raw_curr->data);
					raw_curr = raw_curr->next;
					counter++;
				}
				//printf("counter is %d\n", counter);
				//printf("-----------------------\n");
			}
			else if(raw_head != NULL){
				raw_curr = raw_head;	
				while(raw_curr->next != NULL)
					raw_curr = raw_curr->next;
				

				raw_curr->next = raw_newdata;
				strcpy(raw_newdata->data, user_input);
				raw_newdata->next = NULL;
				raw_newdata->prev = raw_curr;
				//printf("new data: %s\n",raw_head->data);

				//printf("-----------------------\n");
				raw_curr = raw_head;
				int counter = 0;
				while(raw_curr != NULL){
					//printf("old data: %s\n", raw_curr->data);
					raw_curr = raw_curr->next;
					counter++;
				}
				//printf("counter is %d\n", counter);
				//printf("-----------------------\n");
				//printf("%s\n",raw_newdata->data);
			}
			pthread_mutex_unlock(&raw_data_lock);
		}	   
	}

	pthread_exit(NULL);
// ERROR_HANDLER:

 }