Пример #1
0
Octstr *bb_print_status(int status_type)
{
    char *s, *lb;
    char *frmt, *footer;
    Octstr *ret, *str, *version;
    time_t t;

    if ((lb = bb_status_linebreak(status_type)) == NULL)
        return octstr_create("Un-supported format");

    t = time(NULL) - start_time;
    
    if (bb_status == BB_RUNNING)
        s = "running";
    else if (bb_status == BB_ISOLATED)
        s = "isolated";
    else if (bb_status == BB_SUSPENDED)
        s = "suspended";
    else if (bb_status == BB_FULL)
        s = "filled";
    else
        s = "going down";

    version = version_report_string("bearerbox");

    if (status_type == BBSTATUS_HTML) {
        frmt = "%s</p>\n\n"
               " <p>Status: %s, uptime %ldd %ldh %ldm %lds</p>\n\n"
               " <p>WDP: received %ld (%ld queued), sent %ld "
               "(%ld queued)</p>\n\n"
               " <p>SMS: received %ld (%ld queued), sent %ld "
               "(%ld queued), store size %ld<br>\n"
               " SMS: inbound (%.2f,%.2f,%.2f) msg/sec, "
               "outbound (%.2f,%.2f,%.2f) msg/sec</p>\n\n"
               " <p>DLR: received %ld, sent %ld<br>\n"
               " DLR: inbound (%.2f,%.2f,%.2f) msg/sec, outbound (%.2f,%.2f,%.2f) msg/sec<br>\n"
               " DLR: %ld queued, using %s storage</p>\n\n";
        footer = "<p>";
    } else if (status_type == BBSTATUS_WML) {
        frmt = "%s</p>\n\n"
               "   <p>Status: %s, uptime %ldd %ldh %ldm %lds</p>\n\n"
               "   <p>WDP: received %ld (%ld queued)<br/>\n"
               "      WDP: sent %ld (%ld queued)</p>\n\n"
               "   <p>SMS: received %ld (%ld queued)<br/>\n"
               "      SMS: sent %ld (%ld queued)<br/>\n"
               "      SMS: store size %ld<br/>\n"
               "      SMS: inbound (%.2f,%.2f,%.2f) msg/sec<br/>\n"
               "      SMS: outbound (%.2f,%.2f,%.2f) msg/sec</p>\n"
               "   <p>DLR: received %ld<br/>\n"
               "      DLR: sent %ld<br/>\n"
               "      DLR: inbound (%.2f,%.2f,%.2f) msg/sec<br/>\n"
               "      DLR: outbound (%.2f,%.2f,%.2f) msg/sec<br/>\n"
               "      DLR: %ld queued<br/>\n"
               "      DLR: using %s storage</p>\n\n";
        footer = "<p>";
    } else if (status_type == BBSTATUS_XML) {
        frmt = "<version>%s</version>\n"
               "<status>%s, uptime %ldd %ldh %ldm %lds</status>\n"
               "\t<wdp>\n\t\t<received><total>%ld</total><queued>%ld</queued>"
               "</received>\n\t\t<sent><total>%ld</total><queued>%ld</queued>"
               "</sent>\n\t</wdp>\n"
               "\t<sms>\n\t\t<received><total>%ld</total><queued>%ld</queued>"
               "</received>\n\t\t<sent><total>%ld</total><queued>%ld</queued>"
               "</sent>\n\t\t<storesize>%ld</storesize>\n\t\t"
               "<inbound>%.2f,%.2f,%.2f</inbound>\n\t\t"
               "<outbound>%.2f,%.2f,%.2f</outbound>\n\t\t"
               "</sms>\n"
               "\t<dlr>\n\t\t<received><total>%ld</total></received>\n\t\t"
               "<sent><total>%ld</total></sent>\n\t\t"
               "<inbound>%.2f,%.2f,%.2f</inbound>\n\t\t"
               "<outbound>%.2f,%.2f,%.2f</outbound>\n\t\t"
               "<queued>%ld</queued>\n\t\t<storage>%s</storage>\n\t</dlr>\n";
        footer = "";
    } else {
        frmt = "%s\n\nStatus: %s, uptime %ldd %ldh %ldm %lds\n\n"
               "WDP: received %ld (%ld queued), sent %ld (%ld queued)\n\n"
               "SMS: received %ld (%ld queued), sent %ld (%ld queued), store size %ld\n"
               "SMS: inbound (%.2f,%.2f,%.2f) msg/sec, "
               "outbound (%.2f,%.2f,%.2f) msg/sec\n\n"
               "DLR: received %ld, sent %ld\n"
               "DLR: inbound (%.2f,%.2f,%.2f) msg/sec, outbound (%.2f,%.2f,%.2f) msg/sec\n"
               "DLR: %ld queued, using %s storage\n\n";
        footer = "";
    }
    
    ret = octstr_format(frmt,
        octstr_get_cstr(version),
        s, t/3600/24, t/3600%24, t/60%60, t%60,
        counter_value(incoming_wdp_counter),
        gwlist_len(incoming_wdp) + boxc_incoming_wdp_queue(),
        counter_value(outgoing_wdp_counter), gwlist_len(outgoing_wdp) + udp_outgoing_queue(),
        counter_value(incoming_sms_counter), gwlist_len(incoming_sms),
        counter_value(outgoing_sms_counter), gwlist_len(outgoing_sms),
        store_messages(),
        load_get(incoming_sms_load,0), load_get(incoming_sms_load,1), load_get(incoming_sms_load,2),
        load_get(outgoing_sms_load,0), load_get(outgoing_sms_load,1), load_get(outgoing_sms_load,2),
        counter_value(incoming_dlr_counter), counter_value(outgoing_dlr_counter),
        load_get(incoming_dlr_load,0), load_get(incoming_dlr_load,1), load_get(incoming_dlr_load,2),
        load_get(outgoing_dlr_load,0), load_get(outgoing_dlr_load,1), load_get(outgoing_dlr_load,2),
        dlr_messages(), dlr_type());

    octstr_destroy(version);
    
    append_status(ret, str, boxc_status, status_type);
    append_status(ret, str, smsc2_status, status_type);
    octstr_append_cstr(ret, footer);
    
    return ret;
}
Пример #2
0
Файл: mime.c Проект: frese/mbuni
/*
 * This routine is used for mime_[http|octstr]_to_entity() in order to
 * reduce code duplication. Basically the only difference is how the headers
 * are parsed or passed to the resulting MIMEEntity representation.
 */
static MIMEEntity *mime_something_to_entity(Octstr *mime, List *headers)
{
    MIMEEntity *e;
    ParseContext *context;
    Octstr *value, *boundary, *start;
    int len = 0;

	debug("mime.parse",0,"mime_something_to_entity");
	octstr_dump(mime,0);

    gw_assert(mime != NULL);

    value = boundary = start = NULL;
    context = parse_context_create(mime);
    e = mime_entity_create();
    
    /* parse the headers up to the body. If we have headers already passed 
     * from our caller, then duplicate them and continue */
    if (headers != NULL) {
        /* we have some headers to duplicate, first ensure we destroy
         * the list from the previous creation inside mime_entity_create() */
        http_destroy_headers(e->headers);
        e->headers = http_header_duplicate(headers);
    } else {
        /* parse the headers out of the mime block */
        if ((read_mime_headers(context, e->headers) != 0) || e->headers == NULL) {
            debug("mime.parse",0,"Failed to read MIME headers in Octstr block:");
            octstr_dump(mime, 0);
            mime_entity_destroy(e);
            parse_context_destroy(context);
            return NULL;
        }
    }

    /* 
     * Now check if the body is a multipart. This is indicated by an 'boundary'
     * parameter in the 'Content-Type' value. If yes, call ourself for the 
     * multipart entities after parsing them.
     */
    value = http_header_value(e->headers, octstr_imm("Content-Type"));
	debug("mime.parse",0,"value: %s", octstr_get_cstr(value));
    boundary = http_get_header_parameter(value, octstr_imm("boundary"));
	debug("mime.parse",0,"boundary: %s", octstr_get_cstr(boundary));
    start = get_start_param(value);

    /* Beware that we need *unquoted* strings to compare against in the
     * following parsing sections. */
    if (boundary && (len = octstr_len(boundary)) > 0 &&
        octstr_get_char(boundary, 0) == '"' && octstr_get_char(boundary, len-1) == '"') {
        octstr_delete(boundary, 0, 1);
        octstr_delete(boundary, len-2, 1);
    }

	debug("mime.parse",0, "Boundrary is %s", octstr_get_cstr(boundary));

    if (boundary != NULL) {
        /* we have a multipart block as body, parse the boundary blocks */
        Octstr *entity, *seperator, *os;
        
        /* loop by all boundary blocks we have in the body */
        seperator = octstr_create("--");
        octstr_append(seperator, boundary);
        while ((entity = parse_get_seperated_block(context, seperator)) != NULL) {
            MIMEEntity *m;
            int del2 = 0;
	    
            /* we have still linefeeds at the beginning and end that we 
             * need to remove, these are from the separator. 
             * We check if it is LF only or CRLF! */
            del2 = (octstr_get_char(entity, 0) == '\r');
            if (del2) 
                octstr_delete(entity, 0, 2);	      
            else
                octstr_delete(entity, 0, 1);

            /* we assume the same mechanism applies to beginning and end -- 
             * seems reasonable! */
            if (del2)
                octstr_delete(entity, octstr_len(entity) - 2, 2);
            else
                octstr_delete(entity, octstr_len(entity) - 1, 1);

            debug("mime.parse",0,"MIME multipart: Parsing entity:");
            octstr_dump(entity, 0);

            /* call ourself for this MIME entity and inject to list */
            if ((m = mime_octstr_to_entity(entity))) {
                gwlist_append(e->multiparts, m);
		 
                /* check if this entity is our start entity (in terms of related)
                 * and set our start pointer to it */
                if (cid_matches(m->headers, start)) {
                    /* set only if none has been set before */
                    e->start = (e->start == NULL) ? m : e->start;
                }
            }

            octstr_destroy(entity);
        }
        /* ok, we parsed all blocks, we expect to see now the end boundary */
        octstr_append_cstr(seperator, "--");
        os = parse_get_line(context);
        if (os != NULL && octstr_compare(os, seperator) != 0) {
            debug("mime.parse",0,"Failed to see end boundary, parsed line is '%s'.",
                  octstr_get_cstr(os));
        }

        octstr_destroy(seperator);
        octstr_destroy(os);
    }
    else {

        /* we don't have boundaries, so this is no multipart block, 
         * pass the body to the MIME entity. */
        e->body = parse_get_rest(context);

    }

    parse_context_destroy(context);
    octstr_destroy(value);
    octstr_destroy(boundary);
    octstr_destroy(start);

    return e;
}
Пример #3
0
static void do_mm1_push(Octstr *rcpt_to, int isphonenum, MmsEnvelope *e, MmsMsg *msg)
{
     List *pheaders;
     static unsigned char ct; /* Transaction counter -- do we need it? */
     Octstr *to = NULL;     
     Octstr *pduhdr = octstr_create("");     
     Octstr *s = NULL;     
     
     if (!rcpt_to) {
	  mms_error(0, "MM1", NULL, "mobilesender: Queue entry %s has no recipient address!", e->xqfname);
	  goto done;
     } else
	  to = octstr_duplicate(rcpt_to);
     

     ct++;    
     octstr_append_char(pduhdr, ct);  /* Pushd id */
     octstr_append_char(pduhdr, 0x06); /* PUSH */

     
#if 1
     octstr_append_char(pduhdr, 1 + 1 + 1);
     octstr_append_char(pduhdr, 0xbe); /* content type. */     
#else
     octstr_append_char(pduhdr, 
			1 + 1 + strlen("application/vnd.wap.mms-message") + 1); /*header length. */     
     octstr_append_cstr(pduhdr, "application/vnd.wap.mms-message");
     octstr_append_char(pduhdr, 0x0); /* string terminator. */
#endif
     octstr_append_char(pduhdr, 0xaf); /* push application ID header and value follows. */
     octstr_append_char(pduhdr, 0x84); /* ... */

     s = mms_tobinary(msg);
     if (isphonenum) {
	  Octstr *url = octstr_format("%S&text=%E%E&to=%E&udh=%%06%%05%%04%%0B%%84%%23%%F0",	
				      settings->sendsms_url, pduhdr, s, to);     
	  int status;
	  List *rph  = NULL;
	  Octstr *rbody = NULL;
	  MmsEnvelopeTo *xto = gwlist_get(e->to, 0);
	  
	  pheaders = http_create_empty_headers();
	  http_header_add(pheaders, "Connection", "close");
	  http_header_add(pheaders, "User-Agent", MM_NAME "/" MMSC_VERSION);	       
	  
	  if ((status = mms_url_fetch_content(HTTP_METHOD_GET, url, pheaders, NULL, &rph, &rbody)) < 0 ||
	      http_status_class(status) != HTTP_STATUS_SUCCESSFUL) {
	       
	       mms_error(0,  "MM1", NULL, " Push[%s] from %s, to %s, failed, HTTP code => %d", e->xqfname, 
			 octstr_get_cstr(e->from), octstr_get_cstr(to), status);	       

	       e = update_env(e,xto,0);
	  } else {	 /* Successful push. */      

	       mms_log2("Notify", octstr_imm("system"), to, 
			-1, e ? e->msgId : NULL, NULL, NULL, "MM1", NULL,NULL);
	       e = update_env(e, xto, 1);	       
	  }     
	  
	  http_destroy_headers(pheaders);
	  http_destroy_headers(rph);
	  octstr_destroy(rbody);
	  octstr_destroy(url);
     } else { /* An IP Address: Send packet, forget. */
	  Octstr *addr = udp_create_address(to, WAPPUSH_PORT);
	  int sock = udp_client_socket();
	  MmsEnvelopeTo *xto = gwlist_get(e->to,0);
	  
	  if (sock > 0) {
	       octstr_append(pduhdr, s);
#if 0
	       octstr_dump(pduhdr, 0);
#endif
	       udp_sendto(sock, pduhdr, addr);
	       close(sock); /* ?? */      
	       mms_log2("Notify", octstr_imm("system"), to, 
			-1, e ? e->msgId : NULL, 
			NULL, NULL, "MM1", NULL,NULL);
	       e = update_env(e, xto, 1);
	  } else {
	       e = update_env(e, xto, 0);
	       mms_error(0,  "MM1", NULL, "push to %s:%d failed: %s", 
			 octstr_get_cstr(to), WAPPUSH_PORT, strerror(errno));
	  }
	  octstr_destroy(addr);
     }
 done:
     octstr_destroy(to);
     octstr_destroy(pduhdr);
     octstr_destroy(s);
     
     if (e)
	  settings->qfs->mms_queue_free_env(e);     
}
Пример #4
0
/*
 * Tokenises an attribute, and in most cases, the start of its value (some-
 * times whole of it). Tokenisation is based on tables in si, chapters 9.3.2
 * and 9.3.3. 
 * Returns 0 when success, -1 when error.
 */
static int parse_attribute(xmlAttrPtr attr, simple_binary_t **sibxml)
{
    Octstr *name,
           *value,
           *valueos,
           *tokenized_date;
    unsigned char si_hex;
    size_t i,
           value_len;

    name = octstr_create((char *)attr->name);

    if (attr->children != NULL)
	value = create_octstr_from_node((char *)attr->children);
    else 
	value = NULL;

    if (value == NULL)
        goto error;

    i = 0;
    valueos = NULL;
    while (i < NUMBER_OF_ATTRIBUTES) {
        if (octstr_compare(name, octstr_imm(si_attributes[i].name)) == 0) {
	    if (si_attributes[i].value_part == NULL) {
	        break; 
            } else {
                value_len = octstr_len(valueos = 
                    octstr_imm(si_attributes[i].value_part));
	        if (octstr_ncompare(value, valueos, value_len) == 0) {
		    break;
                }
            }
        }
       ++i;
    }

    if (i == NUMBER_OF_ATTRIBUTES)
        goto error;

    tokenized_date = NULL;
    si_hex = si_attributes[i].token;
    if (action(si_hex)) {
        output_char(si_hex, sibxml);
    } else if (url(si_hex)) {
        output_char(si_hex, sibxml);
        octstr_delete(value, 0, octstr_len(valueos));
        parse_url_value(value, sibxml);
    } else if (date(si_hex)) {
        if ((tokenized_date = tokenize_date(value)) == NULL)
            goto error;
        output_char(si_hex, sibxml);
        output_octet_string(tokenized_date, sibxml);
    } else {
        output_char(si_hex, sibxml);
        parse_inline_string(value, sibxml);
    }  

    octstr_destroy(tokenized_date);
    octstr_destroy(name);
    octstr_destroy(value);
    return 0;

error:
    octstr_destroy(name);
    octstr_destroy(value);
    return -1;
}
Пример #5
0
int main(int argc, char **argv) {
	int opt;
	Octstr *address;
	int udpsock;

	gwlib_init();

	/* Set defaults that can't be set statically */
	hostname = octstr_create("localhost");

	while ((opt = getopt(argc, argv, "hg:p:i:m:")) != EOF) {
		switch(opt) {
		case 'g':
			octstr_destroy(hostname);
			hostname = octstr_create(optarg);
			break;

		case 'p':
			port = atoi(optarg);
			break;

		case 'i':
			interval = atof(optarg);
			break;

		case 'm':
			maxsize = atol(optarg);
			if (maxsize > UDP_MAXIMUM) {
				maxsize = UDP_MAXIMUM;
				warning(0, "-m: truncated to UDP maximum of"
					"%ld bytes.", maxsize);
			}
			break;

		case 'h':
			help();
			exit(0);
			break;

		case '?':
		default:
			error(0, "Unknown option '%c'", opt);
			help();
			exit(1);
			break;
		}
	}

	address = udp_create_address(hostname, port);
	udpsock = udp_client_socket();
	if (udpsock < 0)
		exit(1);

	for ( ; optind < argc; optind++) {
		send_file(udpsock, argv[optind], address);
		if (interval > 0 && optind + 1 < argc)
			gwthread_sleep(interval);
	}

	octstr_destroy(address);
	octstr_destroy(hostname);
	gwlib_shutdown();
    	return 0;
}
Пример #6
0
static int oracle_select(void *theconn, const Octstr *sql, List *binds, List **res)
{
    List *row;
    OCIStmt *stmt;
    OCIParam *dparam;
    sword status;
    ub4 columns;
    ub4 i;
    struct data_s {
        text *data;
        ub2 size;
        sb2 ind;
        ub2 type;
    };
    struct data_s *data;
    struct ora_conn *conn = (struct ora_conn*) theconn;
    int binds_len = (binds ? gwlist_len(binds) : 0);

    *res = NULL;

    /* allocate statement handle */
    status = OCIHandleAlloc(conn->envp, (dvoid**)&stmt, OCI_HTYPE_STMT, 0,0);
    if (OCI_SUCCESS != status) {
        oracle_checkerr(conn->errhp, status);
        return -1;
    }
    /* prepare statement */
    status = OCIStmtPrepare(stmt, conn->errhp, (unsigned char*)octstr_get_cstr(sql), 
                            octstr_len(sql), OCI_NTV_SYNTAX, OCI_DEFAULT);
    if (OCI_SUCCESS != status) {
        oracle_checkerr(conn->errhp, status);
        OCIHandleFree(stmt, OCI_HTYPE_STMT);
        return -1;
    }

    /* bind variables */
    for (i = 0; i < binds_len; i++) {
        OCIBind *bndhp = NULL;
        Octstr *bind = gwlist_get(binds, i);
        status = OCIBindByPos(stmt, &bndhp, 
                              conn->errhp, (i+1), (dvoid *) octstr_get_cstr(bind),
                              (sword) octstr_len(bind)+1, SQLT_STR, (dvoid *) 0, (ub2 *)0,
                              (ub2 *)0, (ub4)0, (ub4 *)0, OCI_DEFAULT);
        if (OCI_SUCCESS != status) {
            oracle_checkerr(conn->errhp, status);
            OCIHandleFree(stmt, OCI_HTYPE_STMT);
            return -1;
        }
    }
    /* execute our statement */
    status = OCIStmtExecute(conn->svchp, stmt, conn->errhp, 0, 0, NULL, NULL, 
                            OCI_DEFAULT);
    if (OCI_SUCCESS != status && OCI_NO_DATA != status) {
        oracle_checkerr(conn->errhp, status);
        OCIHandleFree(stmt, OCI_HTYPE_STMT);
        return -1;
    }
    /* receive column count */
    status = OCIAttrGet(stmt, OCI_HTYPE_STMT, &columns, 0, OCI_ATTR_PARAM_COUNT, 
                        conn->errhp);
    if (status != OCI_SUCCESS) {
        oracle_checkerr(conn->errhp, status);
        OCIHandleFree(stmt, OCI_HTYPE_STMT);
        return -1;
    }

    debug("dbpool.oracle",0,"SQL has %d columns", columns);

    /* allocate array of pointers */
    debug("dbpool.oracle",0,"alloc size=%ld",sizeof(text*)*columns);
    data = gw_malloc(sizeof(struct data_s)*columns);

    debug("dbpool.oracle",0,"retrieve data_size");
    /* retrieve data size for every column and allocate it */
    for (i=0 ; i < columns; i++) {
        OCIDefine *defh;

        status = OCIParamGet(stmt, OCI_HTYPE_STMT, conn->errhp, 
                             (dvoid**) &dparam, i+1);
        if (status != OCI_SUCCESS) {
            oracle_checkerr(conn->errhp, status);
            columns = i;
            for (i = 0; i < columns; i++)
                gw_free(data[i].data);
            gw_free(data);
            OCIHandleFree(stmt, OCI_HTYPE_STMT);
            return -1;
        }

        status = OCIAttrGet(dparam, OCI_DTYPE_PARAM, (dvoid*) &data[i].size, 
                            0, OCI_ATTR_DATA_SIZE, conn->errhp);
        if (status != OCI_SUCCESS) {
            oracle_checkerr(conn->errhp, status);
            columns = i;
            for (i = 0; i < columns; i++)
                gw_free(data[i].data);
            gw_free(data);
            OCIHandleFree(stmt, OCI_HTYPE_STMT);
            return -1;
        }

        status = OCIAttrGet(dparam, OCI_DTYPE_PARAM, (dvoid*) &data[i].type, 
                            0, OCI_ATTR_DATA_TYPE, conn->errhp);
        if (status != OCI_SUCCESS) {
            oracle_checkerr(conn->errhp, status);
            columns = i;
            for (i = 0; i < columns; i++)
                gw_free(data[i].data);
            gw_free(data);
            OCIHandleFree(stmt, OCI_HTYPE_STMT);
            return -1;
        }

        /* convert all data types to C-Strings except DATE */
        if (data[i].type != SQLT_DAT) {
            data[i].size++; /* terminating zero */
            data[i].type = SQLT_STR;
        }

        debug("dbpool.oracle",0,"alloc size=%d", data[i].size);
        data[i].data = gw_malloc(data[i].size);

        /* bind allocated values to statement handle */
        status = OCIDefineByPos(stmt, &defh, conn->errhp, i+1, data[i].data, 
                                data[i].size, data[i].type, &data[i].ind, 
                                0, 0, OCI_DEFAULT);
        if (status != OCI_SUCCESS) {
            oracle_checkerr(conn->errhp, status);
            columns = i;
            for (i = 0; i <= columns; i++)
                gw_free(data[i].data);
            gw_free(data);
            OCIHandleFree(stmt, OCI_HTYPE_STMT);
            return -1;
        }
    }

    *res = gwlist_create();
    /* fetch data */
    while ((status = OCIStmtFetch(stmt, conn->errhp, 1, 
                                  OCI_FETCH_NEXT, OCI_DEFAULT)) == OCI_SUCCESS ||
            status == OCI_SUCCESS_WITH_INFO) {

        row = gwlist_create();
        for (i = 0; i < columns; i++) {
            if (data[i].data == NULL || data[i].ind == -1) {
                gwlist_insert(row, i, octstr_create(""));
            } else {
                gwlist_insert(row, i, octstr_create_from_data((const char*)data[i].data, data[i].size));
            }
            /* debug("dbpool.oracle",0,"inserted value = '%s'", 
                     octstr_get_cstr(gwlist_get(row,i))); */
        }
        gwlist_append(*res, row);
    }

    /* ignore OCI_NO_DATA error */
    if (status != OCI_NO_DATA) {
        List *row;
        oracle_checkerr(conn->errhp, status);
        for (i = 0; i < columns; i++)
            gw_free(data[i].data);
        gw_free(data);
        while ((row = gwlist_extract_first(*res)) != NULL)
            gwlist_destroy(row, octstr_destroy_item);
        gwlist_destroy(*res, NULL);
        *res = NULL;
        OCIHandleFree(stmt, OCI_HTYPE_STMT);
        return -1;
    }

    for (i = 0; i < columns; i++)
        gw_free(data[i].data);

    gw_free(data);
    OCIHandleFree(stmt, OCI_HTYPE_STMT);

    return 0;
}
Пример #7
0
/* The main program. */
int main(int argc, char **argv) 
{
    Connection *server;
    Octstr *line;
    Octstr **msgs;
    int i;
    int mptr, num_msgs;
    long num_received, num_sent;
    double first_received_at, last_received_at;
    double first_sent_at, last_sent_at;
    double start_time, end_time;
    double delta;
    int interactive, maxfd;
    char *cptr;
    char buffer[IN_BUFSIZE];
    fd_set rset;
    struct timeval alarm;
    FILE *fp;

    gwlib_init();
    setup_signal_handlers();
    host = octstr_create("localhost");
    start_time = get_current_time();

    mptr = get_and_set_debugs(argc, argv, check_args);
    num_msgs = argc - mptr;
		
    interactive = 0;
    msgs = NULL;
    fp = NULL;
    if (num_msgs <= 0) {
        interactive = 1;
        num_msgs = 0;
        info(0, "Entering interactive mode. Type your message on the command line");
        /* set up file pointer to stdin */
        fp = stdin;
        /* initialize set for select */
        FD_ZERO(&rset);	
    } else {
        msgs = gw_malloc(sizeof(Octstr *) * num_msgs);
        for (i = 0; i < num_msgs; i ++) {
            msgs[i] = octstr_create(argv[mptr + i]);
            octstr_append_char(msgs[i], 10); /* End of line */
        }
        info(0, "Host %s Port %d interval %.3f max-messages %ld",
             octstr_get_cstr(host), port, interval, max_send);

        srand((unsigned int) time(NULL));
    }
    info(0, "fakesmsc starting");
    server = conn_open_tcp(host, port, NULL);
    if (server == NULL)
       panic(0, "Failed to open connection");

    num_sent = 0;
    num_received = 0;

    first_received_at = 0;
    first_sent_at = 0;
    last_received_at = 0;
    last_sent_at = 0;

    /* infinitely loop */
    while (1) {
        /* Are we on interactive mode? */ 
        if (interactive == 1) {
            /* Check if we need to clean things up beforehand */
            if ( num_msgs > 0 ) {
                for (i = 0; i < num_msgs; i ++)
                    octstr_destroy(msgs[i]);
                gw_free(msgs);
                num_msgs = 0;
            }

            /* we want either the file pointer or timer */
            FD_SET(fileno(fp), &rset);
            /* get the largest file descriptor */
            maxfd = fileno(fp) + 1;
        
            /* set timer to go off in 3 seconds */
            alarm.tv_sec = IN_TIMEOUT;
            alarm.tv_usec = 0;
        
            if (select(maxfd, &rset, NULL, NULL, &alarm) == -1)
                goto over;
            /* something went off, let's see if it's stdin */
            if (FD_ISSET(fileno(fp), &rset)) { /* stdin is readable */
                cptr = fgets(buffer, IN_BUFSIZE, stdin);
                if( strlen( cptr ) < 2 )
                    goto rcv;
            } else { /* timer kicked in */
                goto rcv;
            }
            num_msgs = 1;
            msgs = gw_malloc(sizeof(Octstr*));
            msgs[0] = octstr_create(cptr);
        }
        /* if we still have something to send as MO message */
        if (num_sent < max_send) {
            Octstr *os = choose_message(msgs, num_msgs);
            Octstr *msg = rnd > 0 ? randomize(os) : os;
 
            if (conn_write(server, msg) == -1)
                panic(0, "write failed");

            ++num_sent;
            if (num_sent == max_send)
                info(0, "fakesmsc: sent message %ld", num_sent);
            else
                debug("send", 0, "fakesmsc: sent message %ld", num_sent);
      
            if (rnd > 0)
                octstr_destroy(msg);

            last_sent_at = get_current_time();
            if (first_sent_at == 0)    
                first_sent_at = last_sent_at;
        }
rcv:
        do {
            delta = interval * num_sent - (get_current_time() - first_sent_at);
            if (delta < 0)
                delta = 0;
            if (num_sent >= max_send)
                delta = -1;
            conn_wait(server, delta);
            if (conn_error(server) || conn_eof(server) || sigint_received)
                goto over;

            /* read as much as the smsc module provides us */
            while ((line = conn_read_line(server))) {
                last_received_at = get_current_time();
                if (first_received_at == 0)
                    first_received_at = last_received_at;
                ++num_received;
                if (num_received == max_send) {
                    info(0, "Got message %ld: <%s>", num_received,
                           octstr_get_cstr(line));
                } else {
                    debug("receive", 0, "Got message %ld: <%s>", num_received,
                          octstr_get_cstr(line));
                }
                octstr_destroy(line);
            }
        } while (delta > 0 || num_sent >= max_send);
    }

over:
    conn_destroy(server);

    /* destroy the MO messages */
    for (i = 0; i < num_msgs; i ++)
        octstr_destroy(msgs[i]);
    gw_free(msgs);

    end_time = get_current_time();

    info(0, "fakesmsc: %ld messages sent and %ld received", num_sent, num_received);
    info(0, "fakesmsc: total running time %.1f seconds", end_time - start_time);
    delta = last_sent_at - first_sent_at;
    if (delta == 0)
        delta = .01;
    if (num_sent > 1)
        info(0, "fakesmsc: from first to last sent message %.1f s, "
                "%.1f msgs/s", delta, (num_sent - 1) / delta);
    delta = last_received_at - first_received_at;
    if (delta == 0)
        delta = .01;
    if (num_received > 1)
        info(0, "fakesmsc: from first to last received message %.1f s, "
                "%.1f msgs/s", delta, (num_received - 1) / delta);
    info(0, "fakesmsc: terminating");
    
    return 0;
}
Пример #8
0
octstr_t * octstr_create_from_str(const char *str)
{
    return octstr_create(str, strlen(str));
}
Пример #9
0
octstr_t * octstr_copy(octstr_t *s)
{
    return octstr_create(s->s, s->len);
}
Пример #10
0
int main(int argc, char **argv)
{
    int opt,
        ret;
    Octstr *pap_doc,
           *log_file;
    WAPEvent *e;

    log_file = NULL;
    gwlib_init();
    
    while ((opt = getopt(argc, argv, "h:v:l:")) != EOF) {
        switch (opt) {
        case 'h':
	    help();
            exit(1);
	break;

        case 'v':
	    log_set_output_level(atoi(optarg));
	break;

        case 'l':
	    octstr_destroy(log_file);
	    log_file = octstr_create(optarg);
	break;

        case '?':
        default:
	    error(0, "Invalid option %c", opt);
            help();
            panic(0, "Stopping");
	break;
        }
    }

    if (optind >= argc) {
        error(0, "Missing arguments");
        help();
        panic(0, "Stopping");
    }

    if (log_file != NULL) {
    	log_open(octstr_get_cstr(log_file), GW_DEBUG, GW_NON_EXCL);
	octstr_destroy(log_file);
    }

    pap_doc = octstr_read_file(argv[optind]);
    if (pap_doc == NULL)
        panic(0, "Cannot read the pap document");

    e = NULL;
    ret = pap_compile(pap_doc, &e);
    
    if (ret < 0) {
        debug("test.pap", 0, "Unable to compile the pap document, rc %d", ret); 
        return 1;           
    } 

    debug("test.pap", 0, "Compiling successfull, wap event being:\n");
    wap_event_dump(e);

    wap_event_destroy(e);
    octstr_destroy(pap_doc);
    gwlib_shutdown();
    return 0;
}
Пример #11
0
static int sqlite3_select(void *theconn, const Octstr *sql, List *binds, List **res)
{
    sqlite3 *db = theconn;
    sqlite3_stmt *stmt;
    const char *rem;
    List *row;
    int status;
    int columns;
    int i;
    int binds_len = (binds ? gwlist_len(binds) : 0);

    *res = NULL;

    /* prepare statement */
#if SQLITE_VERSION_NUMBER >= 3003009
    status = sqlite3_prepare_v2(db, octstr_get_cstr(sql), octstr_len(sql) + 1, &stmt, &rem);
#else
    status = sqlite3_prepare(db, octstr_get_cstr(sql), octstr_len(sql) + 1, &stmt, &rem);
#endif
    if (SQLITE_OK != status) {
        error(0, "SQLite3: %s", sqlite3_errmsg(db));
        return -1;
    }

    /* bind variables */
    for (i = 0; i < binds_len; i++) {
        Octstr *bind = gwlist_get(binds, i);
        status = sqlite3_bind_text(stmt, i + 1, octstr_get_cstr(bind), octstr_len(bind), SQLITE_STATIC);
        if (SQLITE_OK != status) {
            error(0, "SQLite3: %s", sqlite3_errmsg(db));
            sqlite3_finalize(stmt);
            return -1;
        }
    }

    /* execute our statement */
    *res = gwlist_create();
    while ((status = sqlite3_step(stmt)) == SQLITE_ROW) {
        columns = sqlite3_data_count(stmt);
        debug("dbpool.sqlite3",0,"SQL has %d columns", columns);
        row = gwlist_create();
        for (i = 0; i < columns; i++) {
            if (sqlite3_column_type(stmt, i) == SQLITE_NULL) {
                gwlist_insert(row, i, octstr_create(""));
            } else {
                gwlist_insert(row, i, octstr_create(sqlite3_column_text(stmt, i)));
            }
            /* debug("dbpool.sqlite3",0,"inserted value = '%s'",
                     octstr_get_cstr(gwlist_get(row,i))); */
        }
        gwlist_append(*res, row);
    }

    if (SQLITE_DONE != status) {
        error(0, "SQLite3: %s", sqlite3_errmsg(db));
        while ((row = gwlist_extract_first(*res)) != NULL)
            gwlist_destroy(row, octstr_destroy_item);
        gwlist_destroy(*res, NULL);
        *res = NULL;
        sqlite3_finalize(stmt);
        return -1;
    }

    sqlite3_finalize(stmt);

    return 0;
}
Пример #12
0
int main(int argc, char **argv)
{
    int opt;
    unsigned long sended = 0;
    Octstr *cf, *rf;

    gwlib_init();

    bb_host = octstr_create("localhost");
    bb_port = 13001;
    bb_ssl = 0;
        
    while ((opt = getopt(argc, argv, "hv:b:p:si:n:a:f:D:u:d:r:")) != EOF) {
        switch (opt) {
            case 'v':
                log_set_output_level(atoi(optarg));
                break;
            case 'b':
                octstr_destroy(bb_host);
                bb_host = octstr_create(optarg);
                break;
            case 'p':
                bb_port = atoi(optarg);
                break;
            case 's':
                bb_ssl = 1;
                break;
            case 'i':
                smsbox_id = octstr_create(optarg);
                break;
            case 'n':
                service = octstr_create(optarg);
                break;
            case 'a':
                account = octstr_create(optarg);
                break;
            case 'f':
                from = octstr_create(optarg);
                break;
            case 'D':
                dlr_mask = atoi(optarg);
                break;
            case 'u':
                dlr_url = octstr_create(optarg);
                break;
            case 'd':
                delay = atof(optarg);
                break;
            case 'r':
                smsc_id = octstr_create(optarg);
                break;
            case '?':
            default:
                error(0, "Invalid option %c", opt);
                help();
                panic(0, "Stopping.");
        }
    }
    
    if (optind == argc || argc-optind < 2) {
        help();
        exit(1);
    }

    /* check some mandatory elements */
    if (from == NULL)
        panic(0,"Sender address not specified. Use option -f to specify sender address.");

    if ((DLR_IS_ENABLED(dlr_mask) && dlr_url == NULL) || (!DLR_IS_ENABLED(dlr_mask) && dlr_url != NULL))
        panic(0,"dlr-url address OR dlr-mask not specified. Use option -D or -u to specify dlr values");

    rf = octstr_create(argv[argc-1]);
    cf = octstr_create(argv[argc-2]);

    report_versions("mtbatch");
    write_pid_file();
 
    init_batch(cf, rf);

    connect_to_bearerbox(bb_host, bb_port, bb_ssl, NULL /* bb_our_host */);
    identify_to_bearerbox();
    gwthread_create(read_messages_from_bearerbox, NULL);

    sended = run_batch();

    /* avoid exiting before sending all msgs */
    while(sended > counter_value(counter)) {
         gwthread_sleep(0.1);
    }

    program_status = shutting_down;
    gwthread_join_all();

    octstr_destroy(bb_host);
    octstr_destroy(smsbox_id);
    octstr_destroy(content);
    octstr_destroy(service);
    octstr_destroy(account);
    octstr_destroy(dlr_url);
    octstr_destroy(smsc_id);
    counter_destroy(counter);
    gwlist_destroy(lines, octstr_destroy_item); 
   
    gwlib_shutdown();

    return 0;
}
Пример #13
0
int main(int argc, char **argv)
{
    int cf_index;
    int restart = 0;
    Msg *msg;
    Cfg *cfg;
    double heartbeat_freq =  DEFAULT_HEARTBEAT;

    gwlib_init();
    cf_index = get_and_set_debugs(argc, argv, NULL);

    setup_signal_handlers();

    if (argv[cf_index] == NULL)
        config_filename = octstr_create("kannel.conf");
    else
        config_filename = octstr_create(argv[cf_index]);
    cfg = cfg_create(config_filename);

    if (cfg_read(cfg) == -1)
        panic(0, "Couldn't read configuration from `%s'.", octstr_get_cstr(config_filename));

    report_versions("wapbox");

    cfg = init_wapbox(cfg);

    info(0, "------------------------------------------------------------");
    info(0, GW_NAME " wapbox version %s starting up.", GW_VERSION);

    sequence_counter = counter_create();
    wsp_session_init(&wtp_resp_dispatch_event,
                     &wtp_initiator_dispatch_event,
                     &wap_appl_dispatch,
                     &wap_push_ppg_dispatch_event);
    wsp_unit_init(&dispatch_datagram, &wap_appl_dispatch);
    wsp_push_client_init(&wsp_push_client_dispatch_event,
                         &wtp_resp_dispatch_event);

    if (cfg)
        wtp_initiator_init(&dispatch_datagram, &wsp_session_dispatch_event,
                           timer_freq);

    wtp_resp_init(&dispatch_datagram, &wsp_session_dispatch_event,
                  &wsp_push_client_dispatch_event, timer_freq);
    wap_appl_init(cfg);

#if (HAVE_WTLS_OPENSSL)
    wtls_secmgr_init();
    wtls_init(&write_to_bearerbox);
#endif

    if (cfg) {
        wap_push_ota_init(&wsp_session_dispatch_event,
                          &wsp_unit_dispatch_event);
        wap_push_ppg_init(&wap_push_ota_dispatch_event, &wap_appl_dispatch,
                          cfg);
    }

    wml_init(wml_xml_strict);

    if (bearerbox_host == NULL)
        bearerbox_host = octstr_create(BB_DEFAULT_HOST);
    connect_to_bearerbox(bearerbox_host, bearerbox_port, bearerbox_ssl, NULL
                         /* bearerbox_our_port */);

    if (cfg)
        wap_push_ota_bb_address_set(bearerbox_host);

    program_status = running;
    if (0 > heartbeat_start(write_to_bearerbox, heartbeat_freq,
                            wap_appl_get_load)) {
        info(0, GW_NAME "Could not start heartbeat.");
    }

    while (program_status != shutting_down) {
        WAPEvent *dgram;
        int ret;

        /* block infinite for reading messages */
        ret = read_from_bearerbox(&msg, INFINITE_TIME);
        if (ret == -1)
            break;
        else if (ret == 1) /* timeout */
            continue;
        else if (msg == NULL) /* just to be sure, may not happens */
            break;
        if (msg_type(msg) == admin) {
            if (msg->admin.command == cmd_shutdown) {
                info(0, "Bearerbox told us to die");
                program_status = shutting_down;
            } else if (msg->admin.command == cmd_restart) {
                info(0, "Bearerbox told us to restart");
                restart = 1;
                program_status = shutting_down;
            }
            /*
             * XXXX here should be suspend/resume, add RSN
             */
        } else if (msg_type(msg) == wdp_datagram) {
            switch (msg->wdp_datagram.destination_port) {
            case CONNECTIONLESS_PORT:
            case CONNECTION_ORIENTED_PORT:
                dgram = wap_event_create(T_DUnitdata_Ind);
                dgram->u.T_DUnitdata_Ind.addr_tuple = wap_addr_tuple_create(
                        msg->wdp_datagram.source_address,
                        msg->wdp_datagram.source_port,
                        msg->wdp_datagram.destination_address,
                        msg->wdp_datagram.destination_port);
                dgram->u.T_DUnitdata_Ind.user_data = msg->wdp_datagram.user_data;
                msg->wdp_datagram.user_data = NULL;

                wap_dispatch_datagram(dgram);
                break;
            case WTLS_CONNECTIONLESS_PORT:
            case WTLS_CONNECTION_ORIENTED_PORT:
#if (HAVE_WTLS_OPENSSL)
                dgram = wtls_unpack_wdp_datagram(msg);
                if (dgram != NULL)
                    wtls_dispatch_event(dgram);
#endif
                break;
            default:
                panic(0,"Bad packet received! This shouldn't happen!");
                break;
            }
        } else {
            warning(0, "Received other message than wdp/admin, ignoring!");
        }
        msg_destroy(msg);
    }

    info(0, GW_NAME " wapbox terminating.");

    program_status = shutting_down;
    heartbeat_stop(ALL_HEARTBEATS);
    counter_destroy(sequence_counter);

    if (cfg)
        wtp_initiator_shutdown();

    wtp_resp_shutdown();
    wsp_push_client_shutdown();
    wsp_unit_shutdown();
    wsp_session_shutdown();
    wap_appl_shutdown();
    radius_acct_shutdown();

    if (cfg) {
        wap_push_ota_shutdown();
        wap_push_ppg_shutdown();
    }

    wml_shutdown();
    close_connection_to_bearerbox();
    alog_close();
    wap_map_destroy();
    wap_map_user_destroy();
    octstr_destroy(device_home);
    octstr_destroy(bearerbox_host);
    octstr_destroy(config_filename);

    /*
     * Just sleep for a while to get bearerbox chance to restart.
     * Otherwise we will fail while trying to connect to bearerbox!
     */
    if (restart) {
        gwthread_sleep(5.0);
    }

    gwlib_shutdown();

    /* now really restart */
    if (restart)
        execvp(argv[0], argv);

    return 0;
}
Пример #14
0
Numhash *numhash_create(const char *seek_url)
{
    int		loc, lines = 0;
    List	*request_headers, *reply_headers;
    Octstr	*url, *final_url, *reply_body;
    Octstr	*type, *charset;

    char *data, *ptr, numbuf[100];
    int		status;
    Numhash	*table;

    url = octstr_create(seek_url);
    request_headers = http_create_empty_headers();
    status = http_get_real(HTTP_METHOD_GET, url, request_headers, &final_url,
			    &reply_headers, &reply_body);
    octstr_destroy(url);
    octstr_destroy(final_url);
    http_destroy_headers(request_headers);

    if (status != HTTP_OK) {
	http_destroy_headers(reply_headers);
	octstr_destroy(reply_body);
	error(0, "Cannot load numhash!");
	return NULL;
    }
    http_header_get_content_type(reply_headers, &type, &charset);
    octstr_destroy(charset);
    http_destroy_headers(reply_headers);

    if (octstr_str_compare(type, "text/plain") != 0) {
        octstr_destroy(reply_body);
        error(0, "Strange content type <%s> for numhash - expecting 'text/plain'"
                 ", operatiom fails", octstr_get_cstr(type));
        octstr_destroy(type);
        return NULL;
    }
    octstr_destroy(type);

    ptr = data = octstr_get_cstr(reply_body);
    while(*ptr) {
	if (*ptr == '\n') lines++;
	ptr++;
    }
    debug("numhash", 0, "Total %d lines in %s", lines, seek_url);

    table = numhash_init(lines+10, NUMHASH_AUTO_HASH);  	/* automatic hash */

    /* now, parse the number information */

    lines = 0;

    while((ptr = strchr(data, '\n'))) {	/* each line is ended with linefeed */
	*ptr = '\0';
	while(*data != '\0' && isspace(*data))
	    data++;
	if (*data != '#') {
	    loc = 0;
	    while (*data != '\0') {
		if (isdigit(*data))
		    numbuf[loc++] = *data;
		else if (*data == ' ' || *data == '+' || *data == '-')
			;
		else break;
		data++;
	    }
	    if (loc) {
		numbuf[loc] = '\0';
		numhash_add_number(table, numbuf);
		lines++;
	    }
	    else
		warning(0, "Corrupted line '%s'", data);
	}
	data = ptr+1;	/* next row... */
    }
    octstr_destroy(reply_body);

    info(0, "Read from <%s> total of %ld numbers", seek_url, table->number_total);
    return table;
}
Пример #15
0
static void client_thread(void *arg) 
{
    HTTPClient *client;
    Octstr *body, *url, *ip;
    List *headers, *resph, *cgivars;
    HTTPCGIVar *v;
    Octstr *reply_body, *reply_type;
    unsigned long n = 0;
    int status, i;

    while (run) {
        client = http_accept_request(port, &ip, &url, &headers, &body, &cgivars);

        n++;
        if (client == NULL)
            break;

        info(0, "Request for <%s> from <%s>", 
             octstr_get_cstr(url), octstr_get_cstr(ip));
        if (verbose)
            debug("test.http", 0, "CGI vars were");

        /*
         * Don't use gwlist_extract() here, otherwise we don't have a chance
         * to re-use the cgivars later on.
         */
        for (i = 0; i < gwlist_len(cgivars); i++) {
            if ((v = gwlist_get(cgivars, i)) != NULL && verbose) {
                octstr_dump(v->name, 0);
                octstr_dump(v->value, 0);
            }
        }
    
        if (arg == NULL) {
            reply_body = octstr_duplicate(reply_text);
            reply_type = octstr_create("Content-Type: text/plain; "
                                       "charset=\"UTF-8\"");
        } else {
            reply_body = octstr_duplicate(arg);
            reply_type = octstr_create("Content-Type: text/vnd.wap.wml");
        }

        resph = gwlist_create();
        gwlist_append(resph, reply_type);

        status = HTTP_OK;

        /* check for special URIs and handle those */
        if (octstr_compare(url, octstr_imm("/quit")) == 0) {
	       run = 0;
        } else if (octstr_compare(url, octstr_imm("/whitelist")) == 0) {
	       octstr_destroy(reply_body);
            if (whitelist != NULL) {
                if (verbose) {
                    debug("test.http.server", 0, "we send a white list");
                    octstr_dump(whitelist, 0);
                }
                reply_body = octstr_duplicate(whitelist);
            } else {
	           reply_body = octstr_imm("");
	       }
        } else if (octstr_compare(url, octstr_imm("/blacklist")) == 0) {
            octstr_destroy(reply_body);
            if (blacklist != NULL) {
                if (verbose) {
                    debug("test.http.server", 0, "we send a blacklist");
                    octstr_dump(blacklist, 0);
                }
                reply_body = octstr_duplicate(blacklist);
            } else {
                reply_body = octstr_imm("");
            } 
        } else if (octstr_compare(url, octstr_imm("/save")) == 0) {
            /* safe the body into a temporary file */
            pid_t pid = getpid();
            FILE *f = fopen(octstr_get_cstr(octstr_format("/tmp/body.%ld.%ld", pid, n)), "w");
            octstr_print(f, body);
            fclose(f);
        } else if (octstr_compare(url, octstr_imm("/redirect/")) == 0) {
            /* provide us with a HTTP 302 redirection response
             * will return /redirect/<pid> for the location header 
             * and will return /redirect/ if cgivar loop is set to allow looping
             */
            Octstr *redirect_header, *scheme, *uri, *l;
            pid_t pid = getpid();

            uri = ((l = http_cgi_variable(cgivars, "loop")) != NULL) ?
                octstr_format("%s?loop=%s", octstr_get_cstr(url), 
                              octstr_get_cstr(l)) : 
                octstr_format("%s%ld", octstr_get_cstr(url), pid);

            octstr_destroy(reply_body);
            reply_body = octstr_imm("Here you got a redirection URL that you should follow.");
            scheme = ssl ? octstr_imm("https://") : octstr_imm("http://");
            redirect_header = octstr_format("Location: %s%s%s", 
                octstr_get_cstr(scheme),
                octstr_get_cstr(http_header_value(headers, octstr_imm("Host"))),
                octstr_get_cstr(uri));
            gwlist_append(resph, redirect_header);
            status = HTTP_FOUND; /* will provide 302 */
            octstr_destroy(uri);
        } else if (octstr_compare(url, octstr_imm("/mmsc")) == 0) {
            /* fake a M-Send.conf PDU which is using MMSEncapsulation as body */
            pid_t pid = getpid();
            FILE *f;
            gwlist_destroy(resph, octstr_destroy_item);
            octstr_destroy(reply_body);
            reply_type = octstr_create("Content-Type: application/vnd.wap.mms-message");
            reply_body = octstr_create("");
            octstr_append_from_hex(reply_body, 
                "8c81"              /* X-Mms-Message-Type: m-send-conf */
                "98632d3862343300"  /* X-Mms-Transaction-ID: c-8b43 */
                "8d90"              /* X-Mms-MMS-Version: 1.0 */
                "9280"              /* Response-status: Ok */
                "8b313331373939353434393639383434313731323400"
            );                      /* Message-Id: 13179954496984417124 */
            resph = gwlist_create();
            gwlist_append(resph, reply_type);
            /* safe the M-Send.req body into a temporary file */
            f = fopen(octstr_get_cstr(octstr_format("/tmp/mms-body.%ld.%ld", pid, n)), "w");
            octstr_print(f, body);
            fclose(f);
        }        
            
        if (verbose) {
            debug("test.http", 0, "request headers were");
            http_header_dump(headers);
            if (body != NULL) {
                debug("test.http", 0, "request body was");
                octstr_dump(body, 0);
            }
        }

        if (extra_headers != NULL)
        	http_header_combine(resph, extra_headers);

        /* return response to client */
        http_send_reply(client, status, resph, reply_body);

        octstr_destroy(ip);
        octstr_destroy(url);
        octstr_destroy(body);
        octstr_destroy(reply_body);
        http_destroy_cgiargs(cgivars);
        gwlist_destroy(headers, octstr_destroy_item);
        gwlist_destroy(resph, octstr_destroy_item);
    }

    octstr_destroy(whitelist);
    octstr_destroy(blacklist);
    debug("test.http", 0, "Working thread 'client_thread' terminates");
    http_close_all_ports();
}
Пример #16
0
void wap_map_url_config_device_home(char *to)
{
    wap_map_add_url(octstr_imm("Device Home"), octstr_imm("DEVICE:home*"),
                    octstr_create(to), NULL, NULL, NULL, -1);
}
Пример #17
0
int main(int argc, char **argv) {
    int i, opt, use_threads;
    struct sigaction act;
    char *filename;
    Octstr *log_filename;
    Octstr *file_contents;
#ifdef HAVE_LIBSSL
    Octstr *ssl_server_cert_file = NULL;
    Octstr *ssl_server_key_file = NULL;
#endif
    char *whitelist_name;
    char *blacklist_name;
    int white_asked,
        black_asked;
    long threads[MAX_THREADS];
    FILE *fp;

    gwlib_init();

    act.sa_handler = sigterm;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;
    sigaction(SIGTERM, &act, NULL);
    sigaction(SIGINT, &act, NULL);

    port = 8080;
    use_threads = 1;
    verbose = 1;
    run = 1;
    filename = NULL;
    log_filename = NULL;
    blacklist_name = NULL;
    whitelist_name = NULL;
    white_asked = 0;
    black_asked = 0;

    reply_text = octstr_create("Sent.");

    while ((opt = getopt(argc, argv, "hqv:p:t:f:l:sc:k:b:w:r:H:")) != EOF) {
	switch (opt) {
	case 'v':
	    log_set_output_level(atoi(optarg));
	    break;

        case 'q':
	    verbose = 0;                                           
	    break;

	case 'h':
	    help();
	    exit(0);

	case 'p':
	    port = atoi(optarg);
	    break;

	case 't':
	    use_threads = atoi(optarg);
	    if (use_threads > MAX_THREADS)
            use_threads = MAX_THREADS;
	    break;

        case 'c':
#ifdef HAVE_LIBSSL
	    octstr_destroy(ssl_server_cert_file);
	    ssl_server_cert_file = octstr_create(optarg);
#endif
        break;

        case 'k':
#ifdef HAVE_LIBSSL
	    octstr_destroy(ssl_server_key_file);
	    ssl_server_key_file = octstr_create(optarg);
#endif
        break;

	case 's':
#ifdef HAVE_LIBSSL
        ssl = 1;
#endif   
        break;

	case 'f':
	    filename = optarg;
	    break;

	case 'l':
	    octstr_destroy(log_filename);
	    log_filename = octstr_create(optarg);
	break;

    case 'w':
        whitelist_name = optarg;
        if (whitelist_name == NULL)
            whitelist_name = "";
        white_asked = 1;
	break;

    case 'b':
        blacklist_name = optarg;
        if (blacklist_name == NULL)
            blacklist_name = "";
        black_asked = 1;
	break;

	case 'r':
	    octstr_destroy(reply_text);
        reply_text = octstr_create(optarg);
        break;

	case 'H': {
		Octstr *cont;

        fp = fopen(optarg, "a");
        if (fp == NULL)
            panic(0, "Cannot open header text file %s", optarg);
        cont = octstr_read_file(optarg);
        if (cont == NULL)
            panic(0, "Cannot read header text");
        debug("", 0, "headers are");
        octstr_dump(cont, 0);
        split_headers(cont, &extra_headers);
        fclose(fp);
        octstr_destroy(cont);
        break;
	}

	case '?':
	default:
	    error(0, "Invalid option %c", opt);
	    help();
	    panic(0, "Stopping.");
	}
    }

    if (log_filename != NULL) {
    	log_open(octstr_get_cstr(log_filename), GW_DEBUG, GW_NON_EXCL);
	    octstr_destroy(log_filename);
    }

    if (filename == NULL)
    	file_contents = NULL;
    else
    	file_contents = octstr_read_file(filename);

    if (white_asked) {
        whitelist = octstr_read_file(whitelist_name);
        if (whitelist == NULL)
            panic(0, "Cannot read the whitelist");
    }
    
    if (black_asked) {
        blacklist = octstr_read_file(blacklist_name);
        if (blacklist == NULL)
            panic(0, "Cannot read the blacklist");
    }

#ifdef HAVE_LIBSSL
    /*
     * check if we are doing a SSL-enabled server version here
     * load the required cert and key file
     */
    if (ssl) {
        if (ssl_server_cert_file != NULL && ssl_server_key_file != NULL) {
            use_global_server_certkey_file(ssl_server_cert_file, ssl_server_key_file);
            octstr_destroy(ssl_server_cert_file);
            octstr_destroy(ssl_server_key_file);
        } else {
            panic(0, "certificate and public key need to be given!");
        }
    }
#endif
     
    if (http_open_port(port, ssl) == -1)
        panic(0, "http_open_server failed");

    /*
     * Do the real work in a separate thread so that the main
     * thread can catch signals safely.
     */
    for (i = 0; i < use_threads; ++i) 
        threads[i] = gwthread_create(client_thread, file_contents);

    /* wait for all working threads */
    for (i = 0; i < use_threads; ++i)
        gwthread_join(threads[i]);

    octstr_destroy(reply_text);
    gwlist_destroy(extra_headers, octstr_destroy_item);

    debug("test.http", 0, "Program exiting normally.");
    gwlib_shutdown();
    return 0;
}
Пример #18
0
int main (int argc, char **argv)
{
    Octstr *message, *whoami;
    struct emimsg *emimsg;

    printf("/* This tool can decode an UCP/EMI packet. <*****@*****.**> */\n\n");

    gwlib_init();

    if (argc < 2)
        panic(0, "Syntax: %s <packet_without_STX/ETX>\n", argv[0]);

    message = octstr_format("\02%s\03", argv[1]); // fit the UCP specs.
    whoami = octstr_create("DECODE");

    emimsg = get_fields(message, whoami);

    if (emimsg != NULL) {
        printf("\n");
        printf("TRN      \t%d\n", emimsg->trn);
        printf("TYPE     \t%c (%s)\n", emimsg->or, emimsg->or == 'R' ? "Result" : "Operation");
        printf("OPERATION\t%d (%s)\n", emimsg->ot, emi_typeop (emimsg->ot));

        if (emimsg->ot == 01) {
            printf("E01_ADC  \t%s\n",
                    octstr_get_cstr(emimsg->fields[E01_ADC]));
            printf("E01_OADC \t%s\n",
                    octstr_get_cstr(emimsg->fields[E01_OADC]));
            printf("E01_AC   \t%s\n",
                    octstr_get_cstr(emimsg->fields[E01_AC]));
            printf("E01_ADC  \t%s\n",
                    octstr_get_cstr(emimsg->fields[E01_ADC]));
            printf("E01_MT   \t%s\n",
                    octstr_get_cstr(emimsg->fields[E01_MT]));
            if (octstr_get_char(emimsg->fields[E01_MT], 0) == '3') {
                charset_gsm_to_latin1(emimsg->fields[E01_AMSG]);
            }
            printf("E01_AMSG \t%s\n",
                    octstr_get_cstr(emimsg->fields[E01_AMSG]));
        }

        if ((emimsg->ot == 31 || (emimsg->ot >= 50 && emimsg->ot <= 60))
                && emimsg->or == 'R' && 
                (octstr_get_char(emimsg->fields[E50_ADC], 0) == 'A' ||
                octstr_get_char(emimsg->fields[E50_ADC], 0) == 'N')) {
            printf("E%d_ACK  \t%s\n", emimsg->ot,
                    octstr_get_cstr(emimsg->fields[E50_ADC]));
            printf("E%d_SM   \t%s\n", emimsg->ot,
                    octstr_get_cstr(emimsg->fields[E50_OADC]));
        }

        if (emimsg->ot == 31 && emimsg->or == 'O') {
            printf("E50_ADC  \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_ADC]));
            printf("E50_PID  \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_OADC]));
        }

        if (emimsg->ot >= 50 && emimsg->ot <= 59 && 
                octstr_get_char(emimsg->fields[E50_ADC], 0) != 'A' &&
                octstr_get_char(emimsg->fields[E50_ADC], 0) != 'N') {
            printf("E50_ADC  \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_ADC]));
            printf("E50_OADC \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_OADC]));
            printf("E50_AC   \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_AC]));
            printf("E50_NRQ  \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_NRQ]));
            printf("E50_NADC \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_NADC]));
            printf("E50_NT   \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_NT]));
            printf("E50_NPID \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_NPID]));
            printf("E50_LRQ  \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_LRQ]));
            printf("E50_LRAD \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_LRAD]));
            printf("E50_LPID \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_LPID]));
            printf("E50_DD   \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_DD]));
            printf("E50_DDT  \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_DDT]));
            printf("E50_VP   \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_VP]));
            printf("E50_RPID \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_RPID]));
            printf("E50_SCTS \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_SCTS]));
            printf("E50_DST  \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_DST]));
            printf("E50_RSN  \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_RSN]));
            printf("E50_DSCTS\t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_DSCTS]));
            printf("E50_MT   \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_MT]));
            printf("E50_NB   \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_NB]));
            printf("E50_NMSG \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_NMSG]));
            if (emimsg->fields[E50_AMSG])
                octstr_hex_to_binary (emimsg->fields[E50_AMSG]);
            if (octstr_get_char(emimsg->fields[E50_MT], 0) == '3') {
                charset_gsm_to_latin1(emimsg->fields[E50_AMSG]);
            }

            printf("E50_AMSG \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_AMSG]));
            printf("E50_TMSG \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_TMSG]));
            printf("E50_MMS  \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_MMS]));
            printf("E50_PR   \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_PR]));
            printf("E50_DCS  \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_DCS]));
            printf("E50_MCLS \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_MCLS]));
            printf("E50_RPI  \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_RPI]));
            printf("E50_CPG  \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_CPG]));
            printf("E50_RPLY \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_RPLY]));
            printf("E50_OTOA \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_OTOA]));
            printf("E50_HPLMN\t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_HPLMN]));
            printf("E50_XSER \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_XSER]));
            printf("E50_RES4 \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_RES4]));
            printf("E50_RES5 \t%s\n",
                    octstr_get_cstr(emimsg->fields[E50_RES5]));
        }

        if ((emimsg->ot == 60 || emimsg->ot == 61) &&
                (octstr_get_char(emimsg->fields[E50_ADC], 0) != 'A' &&
                octstr_get_char(emimsg->fields[E50_ADC], 0) != 'N')) {
            printf("E60_OADC  \t%s\n",
                    octstr_get_cstr(emimsg->fields[E60_OADC]));
            printf("E60_OTON  \t%s\n",
                    octstr_get_cstr(emimsg->fields[E60_OTON]));
            printf("E60_ONPI  \t%s\n",
                    octstr_get_cstr(emimsg->fields[E60_ONPI]));
            printf("E60_STYP  \t%s\n",
                    octstr_get_cstr(emimsg->fields[E60_STYP]));
            if (emimsg->fields[E60_PWD])
                octstr_hex_to_binary (emimsg->fields[E60_PWD]);
            printf("E60_PWD   \t%s\n",
                    octstr_get_cstr(emimsg->fields[E60_PWD]));
            printf("E60_NPWD  \t%s\n",
                    octstr_get_cstr(emimsg->fields[E60_NPWD]));
            printf("E60_VERS  \t%s\n",
                    octstr_get_cstr(emimsg->fields[E60_VERS]));
            printf("E60_LADC  \t%s\n",
                    octstr_get_cstr(emimsg->fields[E60_LADC]));
            printf("E60_LTON  \t%s\n",
                    octstr_get_cstr(emimsg->fields[E60_LTON]));
            printf("E60_LNPI  \t%s\n",
                    octstr_get_cstr(emimsg->fields[E60_LNPI]));
            printf("E60_OPID  \t%s\n",
                    octstr_get_cstr(emimsg->fields[E60_OPID]));
            printf("E60_RES1  \t%s\n",
                    octstr_get_cstr(emimsg->fields[E60_RES1]));
        }
    }

    octstr_destroy(message);
    octstr_destroy(whoami);
    gwlib_shutdown();
    
    return 0;
}
Пример #19
0
int main(int argc, char **argv)
{
    DBPool *pool;
    DBConf *conf = NULL; /* for compiler please */
    unsigned int num_threads = 1;
    unsigned long i;
    int opt;
    time_t start = 0, end = 0;
    double run_time;
    Octstr *user, *pass, *db, *host, *db_type;
    int j, bail_out;

    user = pass = db = host = db_type = NULL;

    gwlib_init();

    sql = octstr_imm("SHOW STATUS");

    while ((opt = getopt(argc, argv, "v:h:u:p:d:s:q:t:S:T:")) != EOF) {
        switch (opt) {
            case 'v':
                log_set_output_level(atoi(optarg));
                break;

            case 'h':
                host = octstr_create(optarg);
                break;

            case 'u':
                user = octstr_create(optarg);
                break;

            case 'p':
                pass = octstr_create(optarg);
                break;

            case 'd':
                db = octstr_create(optarg);
                break;

            case 'S':
                octstr_destroy(sql);
                sql = octstr_create(optarg);
                break;

            case 's':
                pool_size = atoi(optarg);
                break;

            case 'q':
                queries = atoi(optarg);
                break;

            case 't':
                num_threads = atoi(optarg);
                break;

            case 'T':
                db_type = octstr_create(optarg);
                break;

            case '?':
            default:
                error(0, "Invalid option %c", opt);
                help();
                panic(0, "Stopping.");
        }
    }

    if (!optind) {
        help();
        exit(0);
    }

    if (!db_type) {
        info(0, "No database type given assuming MySQL.");
    }
    else if (octstr_case_compare(db_type, octstr_imm("mysql")) == 0) {
        info(0, "Do tests for mysql database.");
        database_type = DBPOOL_MYSQL;
    }
    else if (octstr_case_compare(db_type, octstr_imm("oracle")) == 0) {
        info(0, "Do tests for oracle database.");
        database_type = DBPOOL_ORACLE;
    }
    else if (octstr_case_compare(db_type, octstr_imm("sqlite")) == 0) {
        info(0, "Do tests for sqlite database.");
        database_type = DBPOOL_SQLITE;
    }
    else if (octstr_case_compare(db_type, octstr_imm("sqlite3")) == 0) {
        info(0, "Do tests for sqlite3 database.");
        database_type = DBPOOL_SQLITE3;
    }
    else {
        panic(0, "Unknown database type '%s'", octstr_get_cstr(db_type));
    }

    /* check if we have the database connection details */
    switch (database_type) {
        case DBPOOL_ORACLE:
            bail_out = (!user || !pass || !db) ? 1 : 0;
            break;
        case DBPOOL_SQLITE:
        case DBPOOL_SQLITE3:
            bail_out = (!db) ? 1 : 0;
            break;
        default:
            bail_out = (!host || !user || !pass || !db) ? 1 : 0;
            break;
    }
    if (bail_out) {
        help();
        panic(0, "Database connection details are not fully provided!");
    }

    for (j = 0; j < 1; j++) {

    /* create DBConf */
    switch (database_type) {
#ifdef HAVE_MYSQL
        case DBPOOL_MYSQL:
            conf = mysql_create_conf(user,pass,db,host);
            client_thread = mysql_client_thread;
            break;
#endif
#ifdef HAVE_ORACLE
        case DBPOOL_ORACLE:
            conf = oracle_create_conf(user, pass, db);
            client_thread = oracle_client_thread;
            break;
#endif
#ifdef HAVE_SQLITE
        case DBPOOL_SQLITE:
            conf = sqlite_create_conf(db);
            client_thread = sqlite_client_thread;
            break;
#endif
#ifdef HAVE_SQLITE3
        case DBPOOL_SQLITE3:
            conf = sqlite3_create_conf(db);
            client_thread = sqlite3_client_thread;
            break;
#endif
        default:
            panic(0, "ooops ....");
    };

    /* create */
    info(0,"Creating database pool to `%s' with %d connections type '%s'.",
          (host ? octstr_get_cstr(host) : octstr_get_cstr(db)), pool_size, octstr_get_cstr(db_type));
    pool = dbpool_create(database_type, conf, pool_size);
    debug("",0,"Connections within pool: %ld", dbpool_conn_count(pool));

    for (i = 0; i < num_threads; ++i) {
        if (gwthread_create(inc_dec_thread, pool) == -1)
            panic(0, "Could not create thread %ld", i);
    }
    gwthread_join_all();

    info(0, "Connections within pool: %ld", dbpool_conn_count(pool));
    info(0, "Checked pool, %d connections still active and ok", dbpool_check(pool));

    /* queries */
    info(0,"SQL query is `%s'", octstr_get_cstr(sql));
    time(&start);
    for (i = 0; i < num_threads; ++i) {
#if 0
        if (gwthread_create(inc_dec_thread, pool) == -1)
            panic(0, "Couldnot create thread %ld", i);
#endif
        if (gwthread_create(client_thread, pool) == -1)
            panic(0, "Couldnot create thread %ld", i);
    }

    gwthread_join_all();
    time(&end);

    run_time = difftime(end, start);
    info(0, "%ld requests in %.2f seconds, %.2f requests/s.",
         (queries * num_threads), run_time, (float) (queries * num_threads) / (run_time==0?1:run_time));

    /* check all active connections */
    debug("",0,"Connections within pool: %ld", dbpool_conn_count(pool));
    info(0,"Checked pool, %d connections still active and ok", dbpool_check(pool));

    info(0,"Destroying pool");
    dbpool_destroy(pool);

    } /* for loop */

    octstr_destroy(sql);
    octstr_destroy(db_type);
    octstr_destroy(user);
    octstr_destroy(pass);
    octstr_destroy(db);
    octstr_destroy(host);
    gwlib_shutdown();

    return 0;
}
Пример #20
0
int main(int argc, char **argv) 
{
    int i, opt, num_threads;
    Octstr *proxy;
    List *exceptions;
    long proxy_port;
    int proxy_ssl = 0;
    Octstr *proxy_username;
    Octstr *proxy_password;
    Octstr *exceptions_regex;
    char *p;
    long threads[MAX_THREADS];
    time_t start, end;
    double run_time;
    FILE *fp;
    int ssl = 0;
    
    gwlib_init();
    
    proxy = NULL;
    proxy_port = -1;
    exceptions = gwlist_create();
    proxy_username = NULL;
    proxy_password = NULL;
    exceptions_regex = NULL;
    num_threads = 1;
    file = 0;
    fp = NULL;
    
    while ((opt = getopt(argc, argv, "hv:qr:p:P:Se:t:i:a:u:sc:H:B:m:f")) != EOF) {
	switch (opt) {
	case 'v':
	    log_set_output_level(atoi(optarg));
	    break;
	
	case 'q':
	    verbose = 0;
	    break;
	
	case 'r':
	    max_requests = atoi(optarg);
	    break;
	
	case 't':
	    num_threads = atoi(optarg);
	    if (num_threads > MAX_THREADS)
		num_threads = MAX_THREADS;
	    break;

	case 'i':
	    interval = atof(optarg);
	    break;

    case 'u':
        file = 1;
        fp = fopen(optarg, "a");
        if (fp == NULL)
            panic(0, "Cannot open message text file %s", optarg);
        msg_text = octstr_read_file(optarg);
        if (msg_text == NULL)
            panic(0, "Cannot read message text");
        debug("", 0, "message text is");
        octstr_dump(msg_text, 0);
        octstr_url_encode(msg_text);
        fclose(fp);
        break;
	
	case 'h':
	    help();
	    exit(0);
	
	case 'p':
	    proxy = octstr_create(optarg);
	    break;
	
	case 'P':
	    proxy_port = atoi(optarg);
	    break;

	case 'S':
        proxy_ssl = 1;
        break;
	
	case 'e':
	    p = strtok(optarg, ":");
	    while (p != NULL) {
		gwlist_append(exceptions, octstr_create(p));
		p = strtok(NULL, ":");
	    }
	    break;

   case 'E':
       exceptions_regex = octstr_create(optarg);
       break;

	case 'a':
	    p = strtok(optarg, ":");
	    if (p != NULL) {
		auth_username = octstr_create(p);
		p = strtok(NULL, "");
		if (p != NULL)
		    auth_password = octstr_create(p);
	    }
	    break;

    case 's':
        ssl = 1;
        break;

    case 'c':
	    octstr_destroy(ssl_client_certkey_file);
	    ssl_client_certkey_file = octstr_create(optarg);
        break;

    case 'H':
        fp = fopen(optarg, "a");
        if (fp == NULL)
            panic(0, "Cannot open header text file %s", optarg);
        extra_headers = octstr_read_file(optarg);
        if (extra_headers == NULL)
            panic(0, "Cannot read header text");
        debug("", 0, "headers are");
        octstr_dump(extra_headers, 0);
        split_headers(extra_headers, &split);
        fclose(fp);
        break;

    case 'B':
        content_file = octstr_create(optarg);
        break;

	case 'm':
	    method_name = octstr_create(optarg);
	    break;

    case 'f':
        follow_redirect = 0;
        break;

    case '?':
	default:
	    error(0, "Invalid option %c", opt);
	    help();
	    panic(0, "Stopping.");
	}
    }
    
    if (optind == argc) {
        help();
        exit(0);
    }

#ifdef HAVE_LIBSSL
    /*
     * check if we are doing a SSL-enabled client version here
     * load the required cert and key file
     */
    if (ssl || proxy_ssl) {
        if (ssl_client_certkey_file != NULL) {
            use_global_client_certkey_file(ssl_client_certkey_file);
        } else {
            panic(0, "client certkey file need to be given!");
        }
    }
#endif

    if (method_name != NULL) {
        method = http_name2method(method_name);
    }
    
    if (proxy != NULL && proxy_port > 0) {
        http_use_proxy(proxy, proxy_port, proxy_ssl, exceptions,
        proxy_username, proxy_password, exceptions_regex);
    }
    octstr_destroy(proxy);
    octstr_destroy(proxy_username);
    octstr_destroy(proxy_password);
    octstr_destroy(exceptions_regex);
    gwlist_destroy(exceptions, octstr_destroy_item);
    
    urls = argv + optind;
    num_urls = argc - optind;
    
    time(&start);
    if (num_threads == 1)
        client_thread(http_caller_create());
    else {
        for (i = 0; i < num_threads; ++i)
            threads[i] = gwthread_create(client_thread, http_caller_create());
        for (i = 0; i < num_threads; ++i)
            gwthread_join(threads[i]);
    }
    time(&end);
    
    run_time = difftime(end, start);
    info(0, "%ld requests in %f seconds, %f requests/s.",
         (max_requests * num_threads), run_time, (max_requests * num_threads) / run_time);
    
    octstr_destroy(ssl_client_certkey_file);
    octstr_destroy(auth_username);
    octstr_destroy(auth_password);
    octstr_destroy(extra_headers);
    octstr_destroy(content_file);
    gwlist_destroy(split, octstr_destroy_item);
    
    gwlib_shutdown();
    
    return 0;
}
Пример #21
0
/*
 * Parse an element node. Check if there is a token for an element tag; if not
 * output the element as a string, else ouput the token. After that, call 
 * attribute parsing functions
 * Returns:      1, add an end tag (element node has no children)
 *               0, do not add an end tag (it has children)
 *              -1, an error occurred
 */
static int parse_element(xmlNodePtr node, simple_binary_t **sibxml)
{
    Octstr *name,
           *outos;
    size_t i;
    unsigned char status_bits,
             si_hex;
    int add_end_tag;
    xmlAttrPtr attribute;

    name = octstr_create((char *)node->name);
    outos = NULL;
    if (octstr_len(name) == 0) {
        octstr_destroy(name);
        return -1;
    }

    i = 0;
    while (i < NUMBER_OF_ELEMENTS) {
        if (octstr_compare(name, octstr_imm(si_elements[i].name)) == 0)
            break;
        ++i;
    }

    status_bits = 0x00;
    si_hex = 0x00;
    add_end_tag = 0;

    if (i != NUMBER_OF_ELEMENTS) {
        si_hex = si_elements[i].token;
        if ((status_bits = element_check_content(node)) > 0) {
	    si_hex = si_hex | status_bits;
	    
	    if ((status_bits & WBXML_CONTENT_BIT) == WBXML_CONTENT_BIT)
	        add_end_tag = 1;
        }
        output_char(si_hex, sibxml);
    } else {
        warning(0, "unknown tag %s in SI source", octstr_get_cstr(name));
        si_hex = WBXML_LITERAL;
        if ((status_bits = element_check_content(node)) > 0) {
	    si_hex = si_hex | status_bits;
	    /* If this node has children, the end tag must be added after 
	       them. */
	    if ((status_bits & WBXML_CONTENT_BIT) == WBXML_CONTENT_BIT)
		add_end_tag = 1;
	}
	output_char(si_hex, sibxml);
        output_octet_string(outos = octstr_duplicate(name), sibxml);
    }

    if (node->properties != NULL) {
	attribute = node->properties;
	while (attribute != NULL) {
	    parse_attribute(attribute, sibxml);
	    attribute = attribute->next;
	}
	parse_end(sibxml);
    }

    octstr_destroy(outos);
    octstr_destroy(name);
    return add_end_tag;
}
Пример #22
0
static struct dlr_entry* dlr_mysql_get(const Octstr *smsc, const Octstr *ts, const Octstr *dst)
{
    Octstr *sql, *like;
    DBPoolConn *pconn;
    List *result = NULL, *row;
    struct dlr_entry *res = NULL;
    List *binds = gwlist_create();

    pconn = dbpool_conn_consume(pool);
    if (pconn == NULL) /* should not happens, but sure is sure */
        return NULL;

    if (dst)
        like = octstr_format("AND `%S` LIKE CONCAT('%%', ?)", fields->field_dst);
    else
        like = octstr_imm("");

    sql = octstr_format("SELECT `%S`, `%S`, `%S`, `%S`, `%S`, `%S` FROM `%S` WHERE `%S`=? AND `%S`=? %S LIMIT 1",
                        fields->field_mask, fields->field_serv,
                        fields->field_url, fields->field_src,
                        fields->field_dst, fields->field_boxc,
                        fields->table, fields->field_smsc,
                        fields->field_ts, like);

    gwlist_append(binds, (Octstr *)smsc);
    gwlist_append(binds, (Octstr *)ts);
    if (dst)
        gwlist_append(binds, (Octstr *)dst);

#if defined(DLR_TRACE)
    debug("dlr.mysql", 0, "sql: %s", octstr_get_cstr(sql));
#endif

    if (dbpool_conn_select(pconn, sql, binds, &result) != 0) {
        octstr_destroy(sql);
        octstr_destroy(like);
        gwlist_destroy(binds, NULL);
        dbpool_conn_produce(pconn);
        return NULL;
    }
    octstr_destroy(sql);
    octstr_destroy(like);
    gwlist_destroy(binds, NULL);
    dbpool_conn_produce(pconn);

#define LO2CSTR(r, i) octstr_get_cstr(gwlist_get(r, i))

    if (gwlist_len(result) > 0) {
        row = gwlist_extract_first(result);
        res = dlr_entry_create();
        gw_assert(res != NULL);
        res->mask = atoi(LO2CSTR(row,0));
        res->service = octstr_create(LO2CSTR(row, 1));
        res->url = octstr_create(LO2CSTR(row,2));
        res->source = octstr_create(LO2CSTR(row, 3));
        res->destination = octstr_create(LO2CSTR(row, 4));
        res->boxc_id = octstr_create(LO2CSTR(row, 5));
        gwlist_destroy(row, octstr_destroy_item);
        res->smsc = octstr_duplicate(smsc);
    }
    gwlist_destroy(result, NULL);

#undef LO2CSTR

    return res;
}
Пример #23
0
static int store_spool_save(Msg *msg)
{
    char id[UUID_STR_LEN + 1];
    Octstr *id_s;

    /* always set msg id and timestamp */
    if (msg_type(msg) == sms && uuid_is_null(msg->sms.id))
        uuid_generate(msg->sms.id);

    if (msg_type(msg) == sms && msg->sms.time == MSG_PARAM_UNDEFINED)
        time(&msg->sms.time);

    if (spool == NULL)
        return 0;

    /* blocke here if store still not loaded */
    gwlist_consume(loaded);

    switch(msg_type(msg)) {
        case sms:
        {
            Octstr *os = store_msg_pack(msg);
            Octstr *filename, *dir;
            int fd;
            size_t wrc;

            if (os == NULL) {
                error(0, "Could not pack message.");
                return -1;
            }
            uuid_unparse(msg->sms.id, id);
            id_s = octstr_create(id);
            dir = octstr_format("%S/%ld", spool, octstr_hash_key(id_s) % MAX_DIRS);
            octstr_destroy(id_s);
            if (mkdir(octstr_get_cstr(dir), S_IRUSR|S_IWUSR|S_IXUSR) == -1 && errno != EEXIST) {
                error(errno, "Could not create directory `%s'.", octstr_get_cstr(dir));
                octstr_destroy(dir);
                octstr_destroy(os);
                return -1;
            }
            filename = octstr_format("%S/%s", dir, id);
            octstr_destroy(dir);
            if ((fd = open(octstr_get_cstr(filename), O_CREAT|O_EXCL|O_WRONLY, S_IRUSR|S_IWUSR)) == -1) {
                error(errno, "Could not open file `%s'.", octstr_get_cstr(filename));
                octstr_destroy(filename);
                octstr_destroy(os);
                return -1;
            }
            for (wrc = 0; wrc < octstr_len(os); ) {
                size_t rc = write(fd, octstr_get_cstr(os) + wrc, octstr_len(os) - wrc);
                if (rc == -1) {
                    /* remove file */
                    error(errno, "Could not write message to `%s'.", octstr_get_cstr(filename));
                    close(fd);
                    if (unlink(octstr_get_cstr(filename)) == -1)
                        error(errno, "Oops, Could not remove failed file `%s'.", octstr_get_cstr(filename));
                    octstr_destroy(os);
                    octstr_destroy(filename);
                    return -1;
                }
                wrc += rc;
            }
            close(fd);
            counter_increase(counter);
            octstr_destroy(filename);
            octstr_destroy(os);
            break;
        }
        case ack:
        {
            Octstr *filename;
            uuid_unparse(msg->ack.id, id);
            id_s = octstr_create(id);
            filename = octstr_format("%S/%ld/%s", spool, octstr_hash_key(id_s) % MAX_DIRS, id);
            octstr_destroy(id_s);
            if (unlink(octstr_get_cstr(filename)) == -1) {
                error(errno, "Could not unlink file `%s'.", octstr_get_cstr(filename));
                octstr_destroy(filename);
                return -1;
            }
            counter_decrease(counter);
            octstr_destroy(filename);
            break;
        }
        default:
            return -1;
    }

    return 0;
}
Пример #24
0
struct server_type *sqlbox_init_mssql(Cfg* cfg)
{
    CfgGroup *grp;
    List *grplist;
    Octstr *mssql_user, *mssql_pass, *mssql_server, *mssql_database, *mssql_id;
    Octstr *p = NULL;
    long pool_size;
    DBConf *db_conf = NULL;
    struct server_type *res = NULL;

    /*
     * check for all mandatory directives that specify the field names
     * of the used MSSql table
     */
    if (!(grp = cfg_get_single_group(cfg, octstr_imm("sqlbox"))))
        panic(0, "SQLBOX: MSSql: group 'sqlbox' is not specified!");

    if (!(mssql_id = cfg_get(grp, octstr_imm("id"))))
           panic(0, "SQLBOX: MSSql: directive 'id' is not specified!");

    /*
     * now grap the required information from the 'mssql-connection' group
     * with the mssql-id we just obtained
     *
     * we have to loop through all available MSSql connection definitions
     * and search for the one we are looking for
     */

     grplist = cfg_get_multi_group(cfg, octstr_imm("mssql-connection"));
     while (grplist && (grp = (CfgGroup *)gwlist_extract_first(grplist)) != NULL) {
        p = cfg_get(grp, octstr_imm("id"));
        if (p != NULL && octstr_compare(p, mssql_id) == 0) {
            goto found;
        }
        if (p != NULL) octstr_destroy(p);
     }
     panic(0, "SQLBOX: MSSql: connection settings for id '%s' are not specified!",
           octstr_get_cstr(mssql_id));

found:
    octstr_destroy(p);
    gwlist_destroy(grplist, NULL);

    if (cfg_get_integer(&pool_size, grp, octstr_imm("max-connections")) == -1 || pool_size == 0)
        pool_size = 1;

    if (!(mssql_user = cfg_get(grp, octstr_imm("username"))))
           panic(0, "SQLBOX: MSSql: directive 'username' is not specified!");
    if (!(mssql_pass = cfg_get(grp, octstr_imm("password"))))
           panic(0, "SQLBOX: MSSql: directive 'password' is not specified!");
    if (!(mssql_server = cfg_get(grp, octstr_imm("server"))))
           panic(0, "SQLBOX: MSSql: directive 'server' is not specified!");
    if (!(mssql_database = cfg_get(grp, octstr_imm("database"))))
           panic(0, "SQLBOX: MSSql: directive 'database' is not specified!");

    /*
     * ok, ready to connect to MSSql
     */
    db_conf = gw_malloc(sizeof(DBConf));
    gw_assert(db_conf != NULL);

    db_conf->mssql = gw_malloc(sizeof(MSSQLConf));
    gw_assert(db_conf->mssql != NULL);

    db_conf->mssql->username = mssql_user;
    db_conf->mssql->password = mssql_pass;
    db_conf->mssql->server = mssql_server;
    db_conf->mssql->database = mssql_database;

    pool = dbpool_create(DBPOOL_MSSQL, db_conf, pool_size);
    gw_assert(pool != NULL);

    /*
     * XXX should a failing connect throw panic?!
     */
    if (dbpool_conn_count(pool) == 0)
        panic(0,"SQLBOX: MSSql: database pool has no connections!");

    octstr_destroy(mssql_id);

    res = gw_malloc(sizeof(struct server_type));
    gw_assert(res != NULL);

    res->type = octstr_create("MSSql");
    res->sql_enter = sqlbox_configure_mssql;
    res->sql_leave = mssql_leave;
    res->sql_fetch_msg = mssql_fetch_msg;
    res->sql_save_msg = mssql_save_msg;
    return res;
}
Пример #25
0
Файл: mime.c Проект: frese/mbuni
Octstr *mime_entity_to_octstr(MIMEEntity *m)
{
    Octstr *mime, *boundary = NULL;
    List *headers;
    long i;

    gw_assert(m != NULL && m->headers != NULL);

    mime = octstr_create("");

    /* 
     * First of all check if we have further MIME entity dependencies,
     * which means we have further MIMEEntities in our m->multiparts
     * list. If no, then add headers and body and return. This is the
     * easy case. Otherwise we have to loop inside our entities.
     */
    if (gwlist_len(m->multiparts) == 0) {
        for (i = 0; i < gwlist_len(m->headers); i++) {
            octstr_append(mime, gwlist_get(m->headers, i));
            octstr_append(mime, octstr_imm("\r\n"));
        }
        octstr_append(mime, octstr_imm("\r\n"));
        if (m->body != NULL)
            octstr_append(mime, m->body);
        goto finished;
    }

    /* This call ensures boundary exists, and returns it */
    fix_boundary_element(m->headers, &boundary);
    headers = http_header_duplicate(m->headers);

    /* headers */
    for (i = 0; i < gwlist_len(headers); i++) {
        octstr_append(mime, gwlist_get(headers, i));
        octstr_append(mime, octstr_imm("\r\n"));
    }
    http_destroy_headers(headers);
    octstr_append(mime, octstr_imm("\r\n")); /* Mark end of headers. */

    /* loop through all MIME multipart entities of this entity */
    for (i = 0; i < gwlist_len(m->multiparts); i++) {
        MIMEEntity *e = gwlist_get(m->multiparts, i);
        Octstr *body;

        octstr_append(mime, octstr_imm("\r\n--"));
        octstr_append(mime, boundary);
        octstr_append(mime, octstr_imm("\r\n"));

        /* call ourself to produce the MIME entity body */
        body = mime_entity_to_octstr(e);
        octstr_append(mime, body);

        octstr_destroy(body);
    }

    octstr_append(mime, octstr_imm("\r\n--"));
    octstr_append(mime, boundary);
    octstr_append(mime, octstr_imm("--\r\n"));

    octstr_destroy(boundary);

finished:

    return mime;
}
Пример #26
0
static void reply_known_capabilities(List *caps, List *req, WSPMachine *m) {
	unsigned long ui;
	Capability *cap;
	Octstr *data;

	if (wsp_cap_count(caps, WSP_CAPS_CLIENT_SDU_SIZE, NULL) == 0) {
		if (wsp_cap_get_client_sdu(req, &ui) > 0) {
			/* Accept value if it is not silly. */
			if ((ui >= 256 && ui < LONG_MAX) || ui == 0) {
				m->client_SDU_size = ui;
			}
		}
		/* Reply with the client SDU we decided on */
		data = octstr_create("");
		octstr_append_uintvar(data, m->client_SDU_size);
		cap = wsp_cap_create(WSP_CAPS_CLIENT_SDU_SIZE,
			NULL, data);
		gwlist_append(caps, cap);
	}

	if (wsp_cap_count(caps, WSP_CAPS_SERVER_SDU_SIZE, NULL) == 0) {
		/* Accept whatever size the client is willing
		 * to send.  If the client did not specify anything,
		 * then use the default. */
		if (wsp_cap_get_server_sdu(req, &ui) <= 0) {
			ui = 1400;
		}
		data = octstr_create("");
		octstr_append_uintvar(data, ui);
		cap = wsp_cap_create(WSP_CAPS_SERVER_SDU_SIZE, NULL, data);
		gwlist_append(caps, cap);
	}

	/* Currently we cannot handle any protocol options */
	if (wsp_cap_count(caps, WSP_CAPS_PROTOCOL_OPTIONS, NULL) == 0) {
		data = octstr_create("");
		octstr_append_char(data, 0);
		cap = wsp_cap_create(WSP_CAPS_PROTOCOL_OPTIONS, NULL, data);
		gwlist_append(caps, cap);
	}

	/* Accept any Method-MOR the client sent; if it sent none,
	 * use the default. */
	if (wsp_cap_count(caps, WSP_CAPS_METHOD_MOR, NULL) == 0) {
		if (wsp_cap_get_method_mor(req, &ui) <= 0) {
			ui = 1;
		}
		data = octstr_create("");
		octstr_append_char(data, ui);
		cap = wsp_cap_create(WSP_CAPS_METHOD_MOR, NULL, data);
		gwlist_append(caps, cap);
	}

	/* We will never send any Push requests because we don't support
	 * that yet.  But we already specified that in protocol options;
	 * so, pretend we do, and handle the value that way. */
	if (wsp_cap_count(caps, WSP_CAPS_PUSH_MOR, NULL) == 0) {
		if (wsp_cap_get_push_mor(req, &ui) > 0) {
			m->MOR_push = ui;
		}
		data = octstr_create("");
		octstr_append_char(data, m->MOR_push);
		cap = wsp_cap_create(WSP_CAPS_PUSH_MOR, NULL, data);
		gwlist_append(caps, cap);
	}

	/* Supporting extended methods is up to the application layer,
	 * not up to us.  If the application layer didn't specify any,
	 * then we refuse whatever the client requested.  The default
	 * is to support none, so we don't really have to add anything here. */

	/* We do not support any header code pages.  sanitize_capabilities
	 * must have already deleted any reply that indicates otherwise.
	 * Again, not adding anything here is the same as refusing support. */

	/* Listing aliases is something the application layer can do if
	 * it wants to.  We don't care. */
}
Пример #27
0
static int sendNotify(MmsEnvelope *e)
{
     Octstr *to;
     MmsMsg *smsg = NULL;
     MmsEnvelopeTo *xto = gwlist_get(e->to, 0);
     Octstr *err = NULL;
     time_t tnow = time(NULL);
     int j, k, len;
     Octstr *phonenum = NULL, *rcpt_ip = NULL, *msgId, *from, *fromproxy;
     int mtype, msize;
     int res = MMS_SEND_OK, dlr;
     time_t expiryt;
     char *prov_notify_event = NULL;
     char *rtype = NULL;
     
#if 0 /* ... because we don't want fetched messages sticking around in queue forever */           
     
     if (e->lastaccess != 0) { /* This message has been fetched at least once, no more signals. */	  

	  mms_info(0,  "MM1", NULL, "Message [ID: %s] fetched/touched at least once. Skipping",
	       e->xqfname);
	  return settings->qfs->mms_queue_update(e);
     }
#endif

     if (!xto) {
	  mms_error(0,  "MM1", NULL, "mobilesender: Queue entry %s with no recipients!", 
		e->xqfname);
	  return 0;
     }

     to = octstr_duplicate(xto->rcpt);
     expiryt = e->expiryt;
     msgId = e->msgId ? octstr_duplicate(e->msgId) : NULL;
     from = octstr_duplicate(e->from);
     fromproxy = e->fromproxy ? octstr_duplicate(e->fromproxy) : NULL;
     msize = e->msize;
     dlr = e->dlr;
     mtype = e->msgtype;

     if (e->expiryt != 0 &&  /* Handle message expiry. */
	 e->expiryt < tnow) {
	  err = octstr_format("MM1 error: Message expired while sending to %S!", to);
	  res = MMS_SEND_ERROR_FATAL;
	  prov_notify_event = "failedfetch";
	  rtype = "Expired";	  
	  goto done;
     } else if (e->attempts >= settings->mm1_maxsendattempts) {
	  err = octstr_format("MM1: Maximum delivery attempts [%d] to %S reached. Delivery suspended!", 
			      e->attempts, to);
	  res = MMS_SEND_OK;

	  e->sendt = e->expiryt + 1; /* no retry until expiry */	  
	  if (settings->qfs->mms_queue_update(e) != 1) 
	       settings->qfs->mms_queue_free_env(e);		    
	  e = NULL;
	  goto done;

     } else if (e->lastaccess != 0) {
	  e->sendt = e->expiryt + 1;
	  res = MMS_SEND_OK; 
	  err = octstr_create("Skipped");

	  mms_info(0,  "MM1", NULL, "Message [ID: %s] fetched/touched at least once. Skipping",
		   e->xqfname);
	  if (settings->qfs->mms_queue_update(e) != 1) 
	       settings->qfs->mms_queue_free_env(e);
	  e = NULL;

	  goto done;
     }
     

     j = octstr_case_search(to, octstr_imm("/TYPE=PLMN"), 0);
     k = octstr_case_search(to, octstr_imm("/TYPE=IPv"), 0);
     len = octstr_len(to);
     
     if (j > 0 && j - 1 +  sizeof "/TYPE=PLMN" == len) { /* A proper number. */
	  phonenum = octstr_copy(to, 0, j);
	  mms_normalize_phonenum(&phonenum, 
				 octstr_get_cstr(settings->unified_prefix), 
				 settings->strip_prefixes);	  
     } else if (k > 0 && k + sizeof "/TYPE=IPv" == len) 
	  rcpt_ip = octstr_copy(to, 0, k);
     else {
	  /* We only handle phone numbers here. */
	  err = octstr_format("Unexpected recipient %s in MT queue!", octstr_get_cstr(to));	  
	  res = MMS_SEND_ERROR_FATAL;	  
	  goto done;
     }
     
     
     /* For phone, getting here means the message can be delivered. So: 
      * - Check whether the recipient is provisioned, if not, wait (script called will queue creation req)
      * - If the recipient can't take MMS, then send SMS.
      */
     
     /* We handle two types of requests: send and delivery/read notifications. 
      * other types of messages cannot possibly be in this queue!
      */
     
     if (mtype == MMS_MSGTYPE_SEND_REQ ||
	 mtype == MMS_MSGTYPE_RETRIEVE_CONF) {
	  Octstr *url, *transid;
	  
	  if (phonenum) {
	       int send_ind = mms_ind_send(settings->prov_getstatus, phonenum);
	       
	       if (send_ind < 0 && 
		   settings->notify_unprovisioned)
		    send_ind = 0;

	       if (send_ind < 0) { /* That is, recipient is not (yet) provisioned. */
		    res = MMS_SEND_ERROR_TRANSIENT;
		    err = octstr_format("%S is not provisioned for MMS reception, delivery deferred!", 
					phonenum);
		    
		    /* Do not increase delivery attempts counter. */
		    e->lasttry = tnow;		    
		    e->sendt = e->lasttry + settings->send_back_off * (1 + e->attempts);
		    
		    if (settings->qfs->mms_queue_update(e) == 1) 
			 e = NULL; /* Queue entry gone. */	
		    else 	  
			 settings->qfs->mms_queue_free_env(e);		    		    
		    goto done;
	       } else if (send_ind == 0) { /*  provisioned but does not support */		    
		    Octstr *s = octstr_format(octstr_get_cstr(settings->mms_notify_txt),
					      from);
		    if (settings->notify_unprovisioned && s && octstr_len(s) > 0) { /* Only send if the string was set. */
			 List *pheaders =  http_create_empty_headers(), *rph = NULL;
			 Octstr *rbody = NULL;
			 int status;
			 
			 url = octstr_format("%S&text=%E&to=%E",settings->sendsms_url,s, phonenum);

			 http_header_add(pheaders, "Connection", "close");
			 http_header_add(pheaders, "User-Agent", MM_NAME "/" VERSION);      
			 
			 if ((status = mms_url_fetch_content(HTTP_METHOD_GET, url, 
							     pheaders, NULL, &rph, &rbody)) <0 ||
			     http_status_class(status) != HTTP_STATUS_SUCCESSFUL)
			      mms_error(0, "MM1", NULL, "Notify unprovisioned url fetch failed => %d", status);
			 
			 http_destroy_headers(pheaders);
			 http_destroy_headers(rph);
			 octstr_destroy(url);
			 octstr_destroy(rbody);

		    } 
		    
		    octstr_destroy(s);	
		    res = MMS_SEND_OK;
		    err = octstr_imm("No MMS Ind support, sent SMS instead");
		    
		    xto->process = 0; /* No more processing. */
		    if (settings->qfs->mms_queue_update(e) == 1) 
			 e = NULL; 
		    else 	  
			 settings->qfs->mms_queue_free_env(e);		    
		    goto done;

	       }	       
	  }
	  
	  /* To get here means we can send Ind. */
	  url = mms_makefetchurl(e->xqfname, e->token, MMS_LOC_MQUEUE,
				 phonenum ? phonenum : to,
				 settings);
	  mms_info(0,  "MM1", NULL, "Preparing to notify client to fetch message at URL: %s",
	       octstr_get_cstr(url));
	  transid = mms_maketransid(e->xqfname, settings->host_alias);	  
	  
	  smsg = mms_notification(e->from, e->subject, e->mclass, e->msize, url, transid, 
				  e->expiryt ? e->expiryt :
				  tnow + settings->default_msgexpiry,
				  settings->optimize_notification_size);
	  octstr_destroy(transid);
	  octstr_destroy(url);
     } else if (mtype == MMS_MSGTYPE_DELIVERY_IND ||
		mtype == MMS_MSGTYPE_READ_ORIG_IND) 
	  smsg = settings->qfs->mms_queue_getdata(e);
     else {
	  mms_error(0,  "MM1", NULL, "Unexpected message type [%s] for [%s] found in MT queue!", 
		mms_message_type_to_cstr(mtype), octstr_get_cstr(to));
	  res = MMS_SEND_ERROR_FATAL;
	  goto done;
     }
     
     if (smsg) {
	  do_mm1_push(phonenum ? phonenum : rcpt_ip, 
		      phonenum ? 1 : 0, 
		      e, smsg); /* Don't touch 'e' after this point. It is gone */
	  e = NULL;
     }
     
     if (smsg)
	  mms_destroy(smsg);
    
 done:
     if (e != NULL && 
	 err != NULL && 
	 res != MMS_SEND_ERROR_TRANSIENT && dlr) { /* If there was a report request and this is a legit error
						    *  queue it. 
						    */	 
	       MmsMsg *m = mms_deliveryreport(msgId, to, e->from, tnow, 
					      rtype ? octstr_imm(rtype) : 
					      octstr_imm("Indeterminate"));
	       
	       List *l = gwlist_create();
	       Octstr *res;
	       gwlist_append(l, from);
	       
	       /* Add to queue, switch via proxy to be from proxy. */
	       res = settings->qfs->mms_queue_add(to ? to : settings->system_user, l,  err, 
						  NULL, fromproxy,  
						  tnow, tnow+settings->default_msgexpiry, m, NULL, 
						  NULL, NULL,
						  NULL, NULL,
						  NULL,
						  0,
						  octstr_get_cstr(settings->global_queuedir), 
						  "MM2",
						  settings->host_alias);
	       gwlist_destroy(l, NULL);
	       mms_destroy(m);
	       octstr_destroy(res);	  	  
     }
     
     /* Write to log */
     mms_info(0,  "MM1", NULL, "%s Mobile Queue MMS Send Notify: From=%s, to=%s, msgsize=%d, reason=%s. Processed in %d secs", 
	      SEND_ERROR_STR(res),
	      octstr_get_cstr(from), octstr_get_cstr(to), msize,
	      err ? octstr_get_cstr(err) : "",
	      (int)(time(NULL) - tnow));
     
     
     if (xto && e) {
	  if (res == MMS_SEND_ERROR_FATAL)
	       xto->process = 0;  /* No more attempts to deliver, delete this. */	       
	  if (settings->qfs->mms_queue_update(e) == 1) 
	       e = NULL; /* Queue entry gone. */	
	  else 	  
	       settings->qfs->mms_queue_free_env(e);
     }    /* Else queue will be updated/freed elsewhere. */
     
     
     if (prov_notify_event)
	  notify_prov_server(octstr_get_cstr(settings->prov_notify), 
			     to ? octstr_get_cstr(to) : "unknown", 
			     prov_notify_event, 
			     rtype ? rtype : "",
			     e ? e->msgId : NULL, NULL, NULL);
     
     octstr_destroy(phonenum);
     
     octstr_destroy(rcpt_ip);
     octstr_destroy(to);
     octstr_destroy(msgId);
     octstr_destroy(fromproxy);
     octstr_destroy(from);
     octstr_destroy(err);

     return 1; /* Tell caller we dealt with envelope */
}
Пример #28
0
int main(int argc, char **argv)
{
    output_t outputti = NORMAL_OUT;
    FILE *fp = NULL;
    Octstr *output = NULL;
    Octstr *filename = NULL;
    Octstr *wml_text = NULL;
    Octstr *charset = NULL;
    Octstr *wml_binary = NULL;
    int i, ret = 0, opt, file = 0, zero = 0, numstatus = 0, wml_strict = 1;
    long num = 0;

    /* You can give an wml text file as an argument './wml_tester main.wml' */

    gwlib_init();

    while ((opt = getopt(argc, argv, "hsbzrn:f:c:")) != EOF) {
	switch (opt) {
	case 'h':
	    help();
	    exit(0);
	case 's':
	    if (outputti == NORMAL_OUT)
		outputti = SOURCE_OUT;
	    else {
		help();
		exit(0);
	    }
	    break;
	case 'b':
	    if (outputti == NORMAL_OUT)
		outputti = BINARY_OUT;
	    else {
		help();
		exit(0);
	    }
	    break;
	case 'z':
	    zero = 1;
	    break;
    case 'r':
        wml_strict = 0;
        break;
	case 'n':
	    numstatus = octstr_parse_long(&num, octstr_imm(optarg), 0, 0);
	    if (numstatus == -1) { 
		/* Error in the octstr_parse_long */
		error(num, "Error in the handling of argument to option n");
		help();
		panic(0, "Stopping.");
	    }
	    break;
	case 'f':
	    file = 1;
	    filename = octstr_create(optarg);
	    fp = fopen(optarg, "a");
	    if (fp == NULL)
		panic(0, "Couldn't open output file.");	
	    break;
	case 'c':
	    charset = octstr_create(optarg);
	    break;
	case '?':
	default:
	    error(0, "Invalid option %c", opt);
	    help();
	    panic(0, "Stopping.");
	}
    }

    if (optind >= argc) {
	error(0, "Missing arguments.");
	help();
	panic(0, "Stopping.");
    }

    if (outputti == BINARY_OUT)
	 log_set_output_level(GW_PANIC);
    wml_init(wml_strict);

    while (optind < argc) {
	wml_text = octstr_read_file(argv[optind]);
	if (wml_text == NULL)
	    panic(0, "Couldn't read WML source file.");

	if (zero)
	    set_zero(wml_text);

	for (i = 0; i <= num; i++) {
	    ret = wml_compile(wml_text, charset, &wml_binary, NULL);
	    if (i < num)
		octstr_destroy(wml_binary);
	}
	optind++;

	output = octstr_format("wml_compile returned: %d\n\n", ret);
    
	if (ret == 0) {
	    if (fp == NULL)
		fp = stdout;

	    if (outputti != BINARY_OUT) {
		if (outputti == SOURCE_OUT) {
		    octstr_insert(output, wml_text, octstr_len(output));
		    octstr_append_char(output, '\n');
		}

		octstr_append(output, octstr_imm(
		    "Here's the binary output: \n\n"));
		octstr_print(fp, output);
	    }

	    if (file && outputti != BINARY_OUT) {
		fclose(fp);
		log_open(octstr_get_cstr(filename), 0, GW_NON_EXCL);
		octstr_dump(wml_binary, 0);
		log_close_all();
		fp = fopen(octstr_get_cstr(filename), "a");
	    } else if (outputti != BINARY_OUT)
		octstr_dump(wml_binary, 0);
	    else 
		octstr_print(fp, wml_binary);

	    if (outputti != BINARY_OUT) {
		octstr_destroy(output);
		output = octstr_format("\n And as a text: \n\n");
		octstr_print(fp, output);
      
		octstr_pretty_print(fp, wml_binary);
		octstr_destroy(output);
		output = octstr_format("\n\n");
		octstr_print(fp, output);
	    }
	}

	octstr_destroy(wml_text);
	octstr_destroy(output);
	octstr_destroy(wml_binary);
    }
	
    if (file) {
	fclose(fp);
	octstr_destroy(filename);
    }
    
    if (charset != NULL)
	octstr_destroy(charset);

    wml_shutdown();
    gwlib_shutdown();
    
    return ret;
}
Пример #29
0
int main(int argc, char **argv)
{
    Octstr *mime_content,
           *pap_content,
           *push_data,
           *rdf_content,
           *boundary,
           *push_content_file = NULL,
           *this_header,
           *pap_osname,
           *data_osname;
    List *content_headers,
         *source_parts;
    char *pap_content_file,
         *push_data_file,
         *rdf_content_file;
    int ret,
        std_out,
        opt,
        d_file,
        c_file;
    FILE *fp1,
         *fp2,
         *fp3;

    gwlib_init();
    std_out = 0;
    d_file = 0;
    c_file = 0;
    data_osname = NULL;
    pap_osname = NULL;

    while ((opt = getopt(argc, argv, "hd:sc:")) != EOF) {
        switch(opt) {
            case 'h':
                help();
                exit(1);
            break;

            case 'd':
	        d_file = 1;
                data_osname = octstr_create(optarg);
            break;

            case 'c':
	        c_file = 1;
                pap_osname = octstr_create(optarg);
            break;

            case 's':
                std_out = 1;
            break;

            case '?':
            default:
                error(0, "Invalid option %c", opt);
                help();
                panic(0, "Stopping");
            break;
        }
    }    

    if (optind >= argc) {
        help();
        panic(0, "missing arguments, stopping");
    }

    if (!c_file)
        pap_content_file = "test/pap.txt";
    else
        pap_content_file = octstr_get_cstr(pap_osname);
    if (!d_file)
        push_data_file = "test/data.txt";
    else
        push_data_file = octstr_get_cstr(data_osname);
    rdf_content_file = "test/rdf.txt";

    mime_content = octstr_read_file(argv[optind]);
    if (mime_content == NULL) {
        octstr_destroy(mime_content);
        error(0, "No MIME source");
        panic(0, "Stopping");
    }

    source_parts = octstr_split(mime_content, octstr_imm("content="));
    if (gwlist_len(source_parts) == 1) {     /* a hack to circumvent a bug */
        error(0, "Badly formatted source:");
        octstr_destroy(mime_content);
        gwlist_destroy(source_parts, octstr_destroy_item);
        panic(0, "Stopping");
    }

    boundary = gwlist_extract_first(source_parts);
    octstr_delete(boundary, 0, octstr_len(octstr_imm("boundary=")));
    if (skip_tail(&boundary, ';') == 0) {
        error(0, "Cannot determine boundary, no delimiter; possible");
        octstr_dump(boundary, 0);
        goto no_parse;
    }
    
    octstr_destroy(mime_content);
    mime_content = gwlist_extract_first(source_parts);
    if (skip_tail(&mime_content, ';') == 0){
        error(0, "Cannot determine mime content, no delimiter");
        octstr_dump(mime_content, 0);
        goto no_parse;
    }
    prepend_crlf(&mime_content);
    add_crs(mime_content);
    append_crlf(mime_content);
    
    ret = mime_parse(boundary, mime_content, &pap_content, &push_data, 
                     &content_headers, &rdf_content);
    if (ret == 0) {
        error(0, "Mime_parse returned 0, cannot continue");
        goto error;
    }

    remove_crs(pap_content);
    if (!std_out) {
        fp1 = fopen(pap_content_file, "a");
        if (fp1 == NULL) {
            error(0, "Cannot open the file for pap control message");
            goto error;
        }
        octstr_print(fp1, pap_content);
        debug("test.mime", 0, "pap control message appended to the file");
        fclose(fp1);
    } else {
        debug("test.mime", 0, "pap control message was");
        octstr_dump(pap_content, 0);
    }

    remove_crs(push_data);
    if (!std_out) {
        fp2 = fopen(push_data_file, "a");
        if (fp2 == NULL) {
            error(0, "Cannot open the push data file");
            goto error;
        }
        push_content_file = octstr_create("");
        octstr_append(push_content_file, octstr_imm("headers="));
        while (gwlist_len(content_headers) > 0) {
            octstr_append(push_content_file, 
                          this_header = gwlist_extract_first(content_headers));
            octstr_format_append(push_content_file, "%c", ' ');
            octstr_destroy(this_header);
        }
        octstr_append(push_content_file, octstr_imm(";\n"));
        octstr_append(push_content_file, octstr_imm("content="));
        octstr_append(push_content_file, push_data);
        octstr_append(push_content_file, octstr_imm(";\n"));
        octstr_print(fp2, push_content_file);
        debug("test.mime", 0, "push content appended to the file");
        fclose(fp2);
    } else {
        debug("test.mime", 0, "Content headers were");
        http_header_dump(content_headers);
        debug("test.mime", 0, "And push content itself");
        octstr_dump(push_data, 0);
    }

    if (rdf_content != NULL)
        remove_crs(rdf_content);
    if (!std_out && rdf_content != NULL) {
        fp3 = NULL;
        if (rdf_content != NULL) {
            fp3 = fopen(rdf_content_file, "a");
            if (fp3 == NULL) {
                error(0, "Cannot open the rdf file");
                goto cerror;
             }
            octstr_print(fp3, rdf_content);
            debug("test.mime", 0, "push caps message appended to the file");
            fclose(fp3);
        }
    } else {
        if (rdf_content != NULL) {
            debug("test.mime", 0, "push caps message was");
            octstr_dump(rdf_content, 0);
        }
    }
    
    octstr_destroy(boundary);
    octstr_destroy(mime_content);
    octstr_destroy(pap_content);
    octstr_destroy(push_data);
    octstr_destroy(rdf_content);
    octstr_destroy(pap_osname);
    octstr_destroy(data_osname);
    http_destroy_headers(content_headers);
    gwlist_destroy(source_parts, octstr_destroy_item);
    octstr_destroy(push_content_file);
    gwlib_shutdown();

    info(0, "MIME data parsed successfully");
    return 0;

no_parse:
    octstr_destroy(mime_content);
    octstr_destroy(pap_osname);
    octstr_destroy(data_osname);
    gwlist_destroy(source_parts, octstr_destroy_item);
    octstr_destroy(boundary);
    gwlib_shutdown();
    panic(0, "Stopping");

error:
    octstr_destroy(mime_content);
    gwlist_destroy(source_parts, octstr_destroy_item);
    octstr_destroy(boundary);
    octstr_destroy(pap_content);
    octstr_destroy(push_data);
    octstr_destroy(pap_osname);
    octstr_destroy(data_osname);
    http_destroy_headers(content_headers);
    octstr_destroy(rdf_content);
    gwlib_shutdown();
    panic(0, "Stopping");

cerror:
    octstr_destroy(mime_content);
    gwlist_destroy(source_parts, octstr_destroy_item);
    octstr_destroy(boundary);
    octstr_destroy(pap_content);
    octstr_destroy(push_data);
    octstr_destroy(push_content_file);
    octstr_destroy(pap_osname);
    octstr_destroy(data_osname);
    http_destroy_headers(content_headers);
    octstr_destroy(rdf_content);
    gwlib_shutdown();
    panic(0, "Stopping");
/* return after panic always required by gcc */
    return 1;
}
Пример #30
0
int main(int argc, char **argv)
{
    int cf_index;
    Cfg *cfg;

    bb_status = BB_RUNNING;
    
    gwlib_init();
    start_time = time(NULL);

    suspended = gwlist_create();
    isolated = gwlist_create();
    gwlist_add_producer(suspended);
    gwlist_add_producer(isolated);

    cf_index = get_and_set_debugs(argc, argv, check_args);

    if (argv[cf_index] == NULL)
        cfg_filename = octstr_create("kannel.conf");
    else
        cfg_filename = octstr_create(argv[cf_index]);
    cfg = cfg_create(cfg_filename);
    
    if (cfg_read(cfg) == -1)
        panic(0, "Couldn't read configuration from `%s'.", octstr_get_cstr(cfg_filename));

    dlr_init(cfg);
    
    report_versions("bearerbox");

    flow_threads = gwlist_create();
    
    if (init_bearerbox(cfg) == NULL)
        panic(0, "Initialization failed.");

    info(0, "----------------------------------------");
    info(0, GW_NAME " bearerbox II version %s starting", GW_VERSION);

    gwthread_sleep(5.0); /* give time to threads to register themselves */

    if (store_load(dispatch_into_queue) == -1)
        panic(0, "Cannot start with store-file failing");
    
    info(0, "MAIN: Start-up done, entering mainloop");
    if (bb_status == BB_SUSPENDED) {
        info(0, "Gateway is now SUSPENDED by startup arguments");
    } else if (bb_status == BB_ISOLATED) {
        info(0, "Gateway is now ISOLATED by startup arguments");
        gwlist_remove_producer(suspended);
    } else {
        smsc2_resume(1);
        gwlist_remove_producer(suspended);	
        gwlist_remove_producer(isolated);
    }

    while (bb_status != BB_SHUTDOWN && bb_status != BB_DEAD && 
           gwlist_producer_count(flow_threads) > 0) {
        /* debug("bb", 0, "Main Thread: going to sleep."); */
        /*
         * Not infinite sleep here, because we should notice
         * when all "flow threads" are dead and shutting bearerbox
         * down.
         * XXX if all "flow threads" call gwthread_wakeup(MAIN_THREAD_ID),
         * we can enter infinite sleep then.
         */
        gwthread_sleep(10.0);
        /* debug("bb", 0, "Main Thread: woken up."); */

        if (bb_todo == 0) {
            continue;
        }

        if (bb_todo & BB_LOGREOPEN) {
            warning(0, "SIGHUP received, catching and re-opening logs");
            log_reopen();
            alog_reopen();
            bb_todo = bb_todo & ~BB_LOGREOPEN;
        }

        if (bb_todo & BB_CHECKLEAKS) {
            warning(0, "SIGQUIT received, reporting memory usage.");
            gw_check_leaks();
            bb_todo = bb_todo & ~BB_CHECKLEAKS;
        }
    }

    if (bb_status == BB_SHUTDOWN || bb_status == BB_DEAD)
        warning(0, "Killing signal or HTTP admin command received, shutting down...");

    /* call shutdown */
    bb_shutdown();

    /* wait until flow threads exit */
    while (gwlist_consume(flow_threads) != NULL)
        ;

    info(0, "All flow threads have died, killing core");
    bb_status = BB_DEAD;
    httpadmin_stop();

    boxc_cleanup();
    smsc2_cleanup();
    store_shutdown();
    empty_msg_lists();
    gwlist_destroy(flow_threads, NULL);
    gwlist_destroy(suspended, NULL);
    gwlist_destroy(isolated, NULL);
    mutex_destroy(status_mutex);

    alog_close();		/* if we have any */
    bb_alog_shutdown();
    cfg_destroy(cfg);
    octstr_destroy(cfg_filename);
    dlr_shutdown();

    /* now really restart */
    if (restart)
        restart_box(argv);

    gwlib_shutdown();

    return 0;
}