• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C++ send_error函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中send_error函数的典型用法代码示例。如果您正苦于以下问题:C++ send_error函数的具体用法?C++ send_error怎么用?C++ send_error使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了send_error函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: translate

static void translate(char *filename) {
  int count = 0;
  
  char *text = get_file_text(filename);
  char *start = text;
  if (text == NULL) {
    fprintf(stderr,"file %s not found\n",filename);
    return;
  }
  printf("translating %s:",filename);
  String result(1000,1000);
  while (*text) {
    if (isalpha(*text)) {
      String name;
      int len = get_name(text,name);
      if (len <= 0) {
	send_error(filename, start,text,"invalid identifier found",false);
	exit(-1);
      }
      text += len;
      suif_hash_map<String,String>::iterator iter = renames.find(name);
      if (iter != renames.end()) {
	count ++;
	result += (*iter).second;
      }
      else
	result += name;
    }
    else {
      result.push(*text);
      text ++;
    }
  }
  write_text(filename,(const char *)result);
  printf("%d substitutions made\n",count);
}// end translate
开发者ID:JehandadKhan,项目名称:roccc-2.0,代码行数:36,代码来源:rename.cpp


示例2: reply_with_perror_errno

void
reply_with_perror_errno (int err, const char *fs, ...)
{
  CLEANUP_FREE char *buf1 = NULL;
  CLEANUP_FREE char *buf2 = NULL;
  va_list args;
  int r;

  va_start (args, fs);
  r = vasprintf (&buf1, fs, args);
  va_end (args);

  if (r == -1) {
  error:
    perror ("vasprintf");
    exit (EXIT_FAILURE);
  }

  r = asprintf (&buf2, "%s: %s", buf1, strerror (err));
  if (r == -1)
    goto error;

  send_error (err, buf2);
}
开发者ID:rwmjones,项目名称:libguestfs,代码行数:24,代码来源:proto.c


示例3: cmd_resps

static bool cmd_resps(int srv, struct message *response)
{
  switch(current_request) {
  case(CMD_QUIT):
  case(CMD_END):
  case(CMD_PUSH):
  case(CMD_CLEAN):
  case(CMD_RESPS):
  case(CMD_RESPI):
  case(CMD_SIZE):
  case(CMD_NBCLI):
  case(CMD_NBSRV):
  case(CMD_NBRCV):
  case(CMD_NBSND):
  case(CMD_NBERR):
  case(CMD_MAXNSEC):
  case(CMD_MINNSEC):
  case(CMD_SUMNSEC):
    warnx("unexpected string from server");
    send_error(srv, E_INVAL);
    break;
  case(CMD_POP):
  case(CMD_POPF):
  case(CMD_GET):
  case(CMD_GETF):
    printf("%s\n", response->p_string);
    break;
  case(CMD_GETALL):
    printf("%d - %s\n", getall_counter++, response->p_string);
    break;
  default:
    break;
  }

  return true;
}
开发者ID:gawen947,项目名称:sunix,代码行数:36,代码来源:gpushd-client.c


示例4: client_thread

void* client_thread(void * client_queue) {

    int confd;
    status res;
    char* message = NULL;

    queue *cq = (queue *)client_queue;

    for(;;) {

        confd = dequeue(cq);
        printf("Connection %d\n acquired by thread %lu\n", confd, pthread_self());
        /*  Serve client until they close connection, or
         *  there is an error when attempting to read/write to/from them */
        do {
            /*  Obtain the request message as a string ending in '\r\n\r\n */
            if ((res = obtain_request(&message, confd)) != OK) {
                printf("Failed to obtain HTTP request from connection %d\n",confd);
                if (res != CONNECTION_ERROR) {
                   res = send_error(res, confd);
                }
            } else { /* If request message recieved successfully */
                res = respond_to(message, confd); 
            }
            
           
        } while (res != CONNECTION_ERROR);
        printf("Closing connection %d for thread %lu\n",confd, pthread_self());
        close(confd);       
    }
    /*  Should never get here, but if it does
     *  might as well attempt to avoid any memory leaks */
    free(message);
    return NULL;
        
}
开发者ID:RossMeikleham,项目名称:Webserver-C,代码行数:36,代码来源:web_server.c


示例5: kill_clients

void kill_clients(int pipe, const char* msg)
{
	struct client* p;                       /* Used to traverse clients linked list */
	int socket_buff[1];                     /* Send socket fd to main thread to remove from
	                                                           master fd list */

	// LOCK : Make sure clients is not altered while removing all client connections
	pthread_mutex_lock(&clients_lock);
	if (clients->count > 0) {
		p = clients->head;
		while (p != NULL) {
			// Send the socket fd to the main thread to remove
			// it from the master fd list
			socket_buff[0] = p->socket;
			write(pipe, socket_buff, 1);

			// Make sure that the socket is removed from
			// the master list before preceding any farther
			// (Removes a race condition which would cause
			// select() to break)
			pthread_mutex_lock(&slock);
			while (done == 0)
				pthread_cond_wait(&sready, &slock);
			done = 0;
			pthread_mutex_unlock(&slock);

			send_error(p->socket, msg);
			close(p->socket);
			remove_client_ref(p->socket);

			p = clients->head;
		}
	}
	// UNLOCK
	pthread_mutex_unlock(&clients_lock);
}
开发者ID:cmoresid,项目名称:dirapp,代码行数:36,代码来源:server.c


示例6: handle_init

void handle_init(MSICall *call, const MSIMessage *msg)
{
    assert(call);
    LOGGER_DEBUG(call->session->messenger->log,
                 "Session: %p Handling 'init' friend: %d", call->session, call->friend_number);

    if (!msg->capabilities.exists) {
        LOGGER_WARNING(call->session->messenger->log, "Session: %p Invalid capabilities on 'init'");
        call->error = msi_EInvalidMessage;
        goto FAILURE;
    }

    switch (call->state) {
        case msi_CallInactive: {
            /* Call requested */
            call->peer_capabilities = msg->capabilities.value;
            call->state = msi_CallRequested;

            if (invoke_callback(call, msi_OnInvite) == -1) {
                goto FAILURE;
            }
        }
        break;

        case msi_CallActive: {
            /* If peer sent init while the call is already
             * active it's probable that he is trying to
             * re-call us while the call is not terminated
             * on our side. We can assume that in this case
             * we can automatically answer the re-call.
             */

            LOGGER_INFO(call->session->messenger->log, "Friend is recalling us");

            MSIMessage out_msg;
            msg_init(&out_msg, requ_push);

            out_msg.capabilities.exists = true;
            out_msg.capabilities.value = call->self_capabilities;

            send_message(call->session->messenger, call->friend_number, &out_msg);

            /* If peer changed capabilities during re-call they will
             * be handled accordingly during the next step
             */
        }
        break;

        case msi_CallRequested: // fall-through
        case msi_CallRequesting: {
            LOGGER_WARNING(call->session->messenger->log, "Session: %p Invalid state on 'init'");
            call->error = msi_EInvalidState;
            goto FAILURE;
        }
    }

    return;
FAILURE:
    send_error(call->session->messenger, call->friend_number, call->error);
    kill_call(call);
}
开发者ID:GrayHatter,项目名称:toxcore,代码行数:61,代码来源:msi.c


示例7: ident

/*
	<% ident(arg, "arg", 'arg'); %>

	Syntax checking is very relaxed and all arguments are considered a
	string. Example, the following are the same:

		<% ident(foo); %>
		<% ident('foo'); %>

*/
int parse_asp(const char *path)
{
	char *buffer;
	char *cp;
	char *a, *b, *c;
	char x;
	int argc;
	char *argv[32];
	char *ident;
	const aspapi_t *api;

	if (f_read_alloc_string(path, &buffer, 128 * 1024) < 0) {
		free(buffer);
		if (!header_sent) send_error(500, NULL, "Read error");
		return 0;
	}

	if (!header_sent) send_header(200, NULL, mime_html, 0);

	// <% id(arg, arg); %>
	cp = buffer;
	while (*cp) {
		if ((b = strstr(cp, "%>")) == NULL) {
			web_puts(cp);
			break;
		}
		*b = 0;

		//xx <% <% %>
		//xx %>

		a = cp;
		while ((c = strstr(a, "<%")) != NULL) {
			a = c + 2;
		}

		if (a == cp) {
			*b = '%';
			b += 2;
			web_write(cp, b - cp);
			cp = b;
			continue;
		}

		web_write(cp, (a - cp) - 2);

		cp = b + 2;

		while (*a == ' ') ++a;
		ident = a;
		while (((*a >= 'a') && (*a <= 'z')) || ((*a >= 'A') && (*a <= 'Z')) || ((*a >= '0') && (*a <= '9')) || (*a == '_')) {
			++a;
		}
		if (ident == a) {
#ifdef DEBUG
			syslog(LOG_WARNING, "Identifier not found in %s @%u", path, a - buffer);
#endif
			continue;
		}
		b = a;
		while (*a == ' ') ++a;
		if (*a++ != '(') {
#ifdef DEBUG
			syslog(LOG_WARNING, "Expecting ( in %s @%u", path, a - buffer);
#endif
			continue;
		}
		*b = 0;

		// <% foo(123, "arg"); %>
		// a -----^            ^--- null

//		printf("\n[[['%s'\n", ident);

		argc = 0;
		while (*a) {
			while (*a == ' ') ++a;
			if (*a == ')') {
FINAL:
				++a;
				while ((*a == ' ') || (*a == ';')) ++a;
				if (*a != 0) break;

				for (api = aspapi; api->name; ++api) {
					if (strcmp(api->name, ident) == 0) {
						api->exec(argc, argv);
						break;
					}
				}

//.........这里部分代码省略.........
开发者ID:NieHao,项目名称:Tomato-RAF,代码行数:101,代码来源:parser.c


示例8: main

int main(int argc, char *argv[])
{
	int sock;
	struct sockaddr_in server_address;
	struct sockaddr_in client_address;
	int client_address_size;
	unsigned short server_port;
    int loss_percentage;

	if (argc < 3 || argc > 4){
		fprintf(stderr, "Usage:  %s <Server Port> <Loss Percentage> [-d]\n", argv[0]);
		exit(1);
	}

	server_port = atoi(argv[1]);
    loss_percentage = atoi(argv[2]);

    if (argc == 4 && strcmp(argv[3], "-d") == 0) {
        printf("Debug mode on.\n");
        debug = 1;
    }

    // Set up ARQ with loss_percentage and max packet size
    if (arq_init(loss_percentage, 0) < 0) {
        fprintf(stderr, "Unable to set up ARQ\n");
        fprintf(stderr, "Invalid loss percentage - Must be between 0 and 100.\n");
        exit(2);
    }
	// Create socket for incoming connections
	if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
		fprintf(stderr, "Could not create socket.");
		exit(2);
	}

	memset(&server_address, 0, sizeof(server_address));
	server_address.sin_family = AF_INET;
	server_address.sin_addr.s_addr = htonl(INADDR_ANY);
	server_address.sin_port = htons(server_port);

	// Bind to the server address
	if (bind(sock, (struct sockaddr *) &server_address, sizeof(server_address)) < 0) {
		fprintf(stderr, "Could not bind to server address.");
		exit(2);
	}

	printf("Server started...\n");

	while(1) {
		client_address_size = sizeof(client_address);

        char *buffer = calloc(1, sizeof(char) * arq_get_max_packet_size());

        if (arq_recvfrom(sock, buffer, arq_get_max_packet_size(), 0, (struct sockaddr *) &client_address, &client_address_size) < 0) {
            continue;
        }

        char *client = inet_ntoa(client_address.sin_addr);

        int split_size = 0;
        char **split_buffer = split(buffer, " ", &split_size);

        free(buffer);

        if (split_size > 0) {
            // Handle REQUEST
            if (strcmp(split_buffer[0], "REQUEST") == 0) {
                if (split_size >= 2) {
                    // Got a request with a file name
                    char *file = split_buffer[1];

                    printf("%s - Received request for %s\n", client, file);

                    FILE *fp = fopen(file, "r");

                    if (!fp) {
                        // Oh no the file error
                        printf("%s - Could not open file %s\n", client, file);

                        if (send_error(sock, (struct sockaddr *) &client_address, client_address_size) < 0) {
                            fprintf(stderr, "%s - Unable to contact client.\n", client);
                        }
                    } else {
                        // File was opened successfully
                        printf("%s - Starting transfer\n", client);

                        // 5 b/c number of bytes for "SEND "
                        const int command_size = 5;
                        int chunk_size = arq_get_max_data_size() - command_size;

                        int read_chunk_size = 0;

                        do {
                            void *chunk = calloc((size_t) chunk_size, sizeof(char));
                            read_chunk_size = fread(chunk, 1, chunk_size, fp);

                            if (read_chunk_size > 0) {
                                buffer = calloc(arq_get_max_packet_size(), sizeof(char));

                                sprintf(buffer, "SEND %s", (char *) chunk);

//.........这里部分代码省略.........
开发者ID:Tanner,项目名称:File-Transfer,代码行数:101,代码来源:server.c


示例9: while

void *worker(void *data)
{
  int hSocket;
  char pBuffer[BUFFER_SIZE];
  char method[BUFFER_SIZE];
  char path[BUFFER_SIZE];
  while(1)
    {
      pthread_mutex_lock(&lock);
      while(num == 0)
	pthread_cond_wait(&empty, &lock);
      hSocket = queue[rem];
      rem = (rem + 1) % Q_SIZE;
      num--;
      pthread_mutex_unlock(&lock);
      pthread_cond_signal(&full);
      
      /* Process information */ 
      read(hSocket, pBuffer, BUFFER_SIZE);
      
      if(sscanf(pBuffer, "%[^ ] %[^ ]", method, path) < 2)
      {
	send_error(hSocket, BAD_REQUEST, "Not the accepted protocol");
	continue;
      }
      
      if(strcasecmp(method, "get") != 0)
      {
	send_error(hSocket, NOT_IMPLEMENTED, "Only implemented GET");
	continue;
      }

      char *path_ptr = path;
      if(path[0] == '/')
	path_ptr = &(path[1]);
      
      int len = strlen(path_ptr);
      if(*path_ptr == '/' || strcmp(path_ptr, "..") == 0 || strncmp(path_ptr, "../", 3) == 0 || strstr(path_ptr, "/../") != NULL || strcmp(&(path_ptr[len-3]), "/..") == 0)
      {
	send_error(hSocket, BAD_REQUEST, "Tried to access a private file");
	continue;
      }
      
      FILE *f = fopen(path_ptr, "r");
      if(f)
      {
	fgets(pBuffer, BUFFER_SIZE, f);
	write(hSocket, pBuffer, strlen(pBuffer));
      }
      else
      {
	send_error(hSocket, NOT_FOUND, "Unable to locate file");
	continue;
      } 
     
      fclose(f);
      if(close(hSocket) == SOCKET_ERROR)
      {
	printf("Could not close socket\n");
	continue;
      }
    }
  return NULL;
}
开发者ID:mscott64,项目名称:8803_project1,代码行数:64,代码来源:server.c


示例10: handle_request

int handle_request(int connfd) {
    char *buf = (char *) malloc(MAXLINE);
    char *method, *uri, *version;
    char *fullpath;
    int nread;
    struct stat fs;
    int is_dir;
    int error_code = 0, ret = 0;
    rio_t rio;

    rio_initb(&rio, connfd);

    nread = rio_readlineb(&rio, buf, MAXLINE - 1);
    if (nread == 0) {
        error_code = 400;
        goto fail;
    } else if (buf[nread - 1] != '\n') {
        error_code = 414;
        goto fail;
    } else {
        buf[nread - 1] = 0;
        if (nread >= 2 && buf[nread - 2] == '\r') {
            buf[nread - 2] = 0;
        }
    }
    method = buf;
    for (uri = method; *uri != 0; ++uri) {
        if (*uri == ' ') {
            *uri = 0;
            ++uri;
            break;
        }
    }
    for (version = uri; *version != 0; ++version) {
        if (*version == ' ') {
            *version = 0;
            ++version;
            break;
        }
    }
    if (*method == 0 || *uri == 0 || *version == 0) {
        /* missing some fields in http request header */
        error_code = 400;
        goto fail;
    }
    if (strcmp(method, "GET") != 0) {
        /* only allow GET method */
        error_code = 405;
        goto fail;
    }

    goto next;

fail:
    free(buf);
    if (error_code > 0) {
        send_error(connfd, error_code);
        return 0;
    }

next:
    /* translate path and dispatch HTTP request according to path */
    uri = translate_path(uri);
    fullpath = (char *) malloc(strlen(uri) + 2);
    fullpath[0] = '.';
    strcpy(fullpath + 1, uri);

    if (stat(fullpath, &fs) != 0) {
        send_error(connfd, 404);
    } else {
        is_dir = S_ISDIR(fs.st_mode);
        if (is_dir) {
            if (fullpath[(int) strlen(fullpath) - 1] != '/') {
                send_response(connfd, 301, NULL);
                send_header(connfd, "Location", "%s/", fullpath);
                end_headers(connfd);
            } else {
                ret = list_directory(connfd, fullpath);
            }
        } else {
            ret = fetch_file(connfd, fullpath);
        }
    }
    free(fullpath);
    free(buf);

    return ret;
}
开发者ID:foreverbell,项目名称:playground,代码行数:88,代码来源:http-server.c


示例11: main

int main(int argc, char **argv) 
{
  ETERM *tuplep;
  ETERM *fnp, *argp;
  byte buf[1024];

  sqlite3 *db;
  char *zErrMsg = 0;
  int rc;

  log = fopen("/tmp/sqlite_port.log", "a+");
  fprintf(log, "******start log (%s)******\n", argv[1]);
  fflush(log);

  rc = sqlite3_open(argv[1], &db);
  if (rc) {
    sqlite3_close(db);
    exit(1);
  }

  erl_init(NULL, 0);

  while (read_cmd(buf) > 0) {
    tuplep = erl_decode(buf);
    fnp = erl_element(1, tuplep);
    argp = erl_element(2, tuplep);
    
    if (strncmp((const char *)ERL_ATOM_PTR(fnp), "close", 5) == 0) {
      fprintf(log, "closing sqlite3_close\n");
      fflush(log);

      sqlite3_close(db);
      break;
    }
    else if (strncmp((const char *)ERL_ATOM_PTR(fnp), "list_tables", 11) == 0) {
      fprintf(log, "calling list_tables\n");

      result = 0;

      rc = sqlite3_exec(db, MASTER_QUERY, list_tables, 0, &zErrMsg);
      if (rc != SQLITE_OK) {
	send_error(zErrMsg);
	sqlite3_free(zErrMsg);
      }
      else if (result != 0)  {
	send_result();
      }
      else {
	// not an error and no results. still need to return something
	send_ok();
      } 

      fflush(log);

    }
    else if (strncmp((const char *)ERL_ATOM_PTR(fnp), "sql_exec", 8) == 0) {
      fprintf(log, "calling sqlite3_exec %s\n", erl_iolist_to_string(argp));

      result = 0;

      rc = sqlite3_exec(db, erl_iolist_to_string(argp), callback, 0, &zErrMsg);
      if (rc != SQLITE_OK) {
	send_error(zErrMsg);
	sqlite3_free(zErrMsg);
      }
      else if (result != 0)  {
	send_result();
      }
      else {
	// not an error and no results. still need to return something
	send_ok();
      } 

      fflush(log);
    }

    erl_free_compound(tuplep);
    erl_free_term(fnp);
    erl_free_term(argp);
  }

  fprintf(log, "******end log******\n");
  fclose(log);
  return 0;
}
开发者ID:avtobiff,项目名称:sqlite-erlang,代码行数:85,代码来源:sqlite_port.c


示例12: monotonic_clock


//.........这里部分代码省略.........
							ERR_CS << "Unrecognized admin reload argument: " << ctl[1] << '\n';
						}
					} else {
						LOG_CS << "Reloading all configuration...\n";
						need_reload = 1;
						// Avoid flush timer ellapsing
						continue;
					}
				} else if(ctl == "setpass") {
					if(ctl.args_count() != 2) {
						ERR_CS << "Incorrect number of arguments for 'setpass'\n";
					} else {
						const std::string& addon_id = ctl[1];
						const std::string& newpass = ctl[2];
						config& campaign = get_campaign(addon_id);

						if(!campaign) {
							ERR_CS << "Add-on '" << addon_id << "' not found, cannot set passphrase\n";
						} else if(newpass.empty()) {
							// Shouldn't happen!
							ERR_CS << "Add-on passphrases may not be empty!\n";
						} else {
							campaign["passphrase"] = newpass;
							write_config();

							LOG_CS << "New passphrase set for '" << addon_id << "'\n";
						}
					}
				} else {
					ERR_CS << "Unrecognized admin command: " << ctl.full() << '\n';
				}
			}

			const time_t cur_ts = monotonic_clock();
			// Write config to disk every ten minutes.
			if(force_flush || labs(cur_ts - last_ts) >= 10*60) {
				write_config();
				last_ts = cur_ts;
			}

			network::process_send_queue();

			sock = network::accept_connection();
			if(sock) {
				LOG_CS << "received connection from " << network::ip_address(sock) << "\n";
			}

			config data;

			while((sock = network::receive_data(data, 0)) != network::null_connection)
			{
				config::all_children_iterator i = data.ordered_begin();

				if(i != data.ordered_end()) {
					// We only handle the first child.
					const config::any_child& c = *i;

					request_handlers_table::const_iterator j
							= handlers_.find(c.key);

					if(j != handlers_.end()) {
						// Call the handler.
						j->second(this, request(c.key, c.cfg, sock));
					} else {
						send_error("Unrecognized [" + c.key + "] request.",
								   sock);
					}
				}
			}
		} catch(network::error& e) {
			if(!e.socket) {
				ERR_CS << "fatal network error: " << e.message << "\n";
				throw;
			} else {
				LOG_CS << "client disconnect: " << e.message << " " << network::ip_address(e.socket) << "\n";
				e.disconnect();
			}
		} catch(const config::error& e) {
			network::connection err_sock = 0;
			network::connection const * err_connection = boost::get_error_info<network::connection_info>(e);

			if(err_connection != NULL) {
				err_sock = *err_connection;
			}

			if(err_sock == 0 && sock > 0) {
				err_sock = sock;
			}

			if(err_sock) {
				ERR_CS << "client disconnect due to exception: " << e.what() << " " << network::ip_address(err_sock) << "\n";
				network::disconnect(err_sock);
			} else {
				throw;
			}
		}

		SDL_Delay(20);
	}
}
开发者ID:numo16,项目名称:wesnoth,代码行数:101,代码来源:campaign_server.cpp


示例13: process

int process(FILE *f)
{
  char buf[4096];
  char *method;
  char *path;
  char *protocol;
  struct stat statbuf;
  char pathbuf[4096];
  int len;

  if (!fgets(buf, sizeof(buf), f)) return -1;
  printf("URL: %s", buf);

  method = strtok(buf, " ");
  path = strtok(NULL, " ");
  protocol = strtok(NULL, "\r");
  if (!method || !path || !protocol) return -1;

  fseek(f, 0, SEEK_CUR); // Force change of stream direction

  if (strcasecmp(method, "GET") != 0)
    send_error(f, 501, "Not supported", NULL, "Method is not supported.");
  else if (stat(path, &statbuf) < 0)
    send_error(f, 404, "Not Found", NULL, "File not found.");
  else if (S_ISDIR(statbuf.st_mode))
  {
    len = strlen(path);
    if (len == 0 || path[len - 1] != '/')
    {
      snprintf(pathbuf, sizeof(pathbuf), "Location: %s/", path);
      send_error(f, 302, "Found", pathbuf, "Directories must end with a slash.");
    }
    else
    {
      snprintf(pathbuf, sizeof(pathbuf), "%sindex.html", path);
      if (stat(pathbuf, &statbuf) >= 0)
        send_file(f, pathbuf, &statbuf);
      else
      {
        DIR *dir;
        struct dirent *de;

        send_headers(f, 200, "OK", NULL, "text/html", -1, statbuf.st_mtime);
        fprintf(f, "<HTML><HEAD><TITLE>Index of %s</TITLE></HEAD>\r\n<BODY>", path);
        fprintf(f, "<H4>Index of %s</H4>\r\n<PRE>\n", path);
        fprintf(f, "Name                             Last Modified              Size\r\n");
        fprintf(f, "<HR>\r\n");
        if (len > 1) fprintf(f, "<A HREF=\"..\">..</A>\r\n");

        dir = opendir(path);
        while ((de = readdir(dir)) != NULL)
        {
          char timebuf[32];
          struct tm *tm;

          strcpy(pathbuf, path);
          strcat(pathbuf, de->d_name);

          stat(pathbuf, &statbuf);
          tm = gmtime(&statbuf.st_mtime);
          strftime(timebuf, sizeof(timebuf), "%d-%b-%Y %H:%M:%S", tm);

          fprintf(f, "<A HREF=\"%s%s\">", de->d_name, S_ISDIR(statbuf.st_mode) ? "/" : "");
          fprintf(f, "%s%s", de->d_name, S_ISDIR(statbuf.st_mode) ? "/</A>" : "</A> ");
          if (strlen(de->d_name) < 32) fprintf(f, "%*s", 32 - strlen(de->d_name), "");
          if (S_ISDIR(statbuf.st_mode))
            fprintf(f, "%s\r\n", timebuf);
          else
            fprintf(f, "%s %10d\r\n", timebuf, statbuf.st_size);
        }
        closedir(dir);

        fprintf(f, "</PRE>\r\n<HR>\r\n<ADDRESS>%s</ADDRESS>\r\n</BODY></HTML>\r\n", SERVER);
      }
    }
  }
  else
    send_file(f, path, &statbuf);

  return 0;
}
开发者ID:renjithrr,项目名称:htp,代码行数:81,代码来源:server.c


示例14: int

void *plmc_client_mgr(void *arguments)
{
	thread_entry *tentry;
	thread_data *tdata;
	char command[PLMC_CMD_NAME_MAX_LENGTH];
	char result[PLMC_MAX_TCP_DATA_LEN];
	char ee_id[PLMC_EE_ID_MAX_LENGTH];
	PLMC_cmd_idx cmd_enum;
	int sockfd, retval, bytes_received;
	struct timeval tv;
	int( *callback)(tcp_msg *);
	tentry = (thread_entry *) arguments;
	tdata = &(tentry->thread_d);
	command[0] ='\0';
	
	/* Adding 10 seconds to the plmc_cmd_timeout_secs in the 
	*  plmcd.conf file
	*/
	tv.tv_sec = config.plmc_cmd_timeout_secs + 10;
	tv.tv_usec = 0;
	tcp_msg tcpmsg;
	
	#ifdef PLMC_LIB_DEBUG
	fprintf(plmc_lib_debug, "plmc_client_mgr started up\n");
	fflush(plmc_lib_debug);
	#endif 
	
	/* Lock to get the socket */
	if (pthread_mutex_lock(&tdata->td_lock) != 0) {
		syslog(LOG_ERR, "plmc_lib: plmc_client_mgr encountered an "
				"error getting a lock for a client");
		send_error(PLMC_LIBERR_SYSTEM_RESOURCES,
				PLMC_LIBACT_EXIT_THREAD, NULL, PLMC_NOOP_CMD);
		pthread_exit((void *)NULL);
	}
	sockfd = tentry->thread_d.socketfd;
	strncpy(ee_id, tdata->ee_id, PLMC_EE_ID_MAX_LENGTH);
	ee_id[PLMC_EE_ID_MAX_LENGTH - 1] = '\0';
	
	/* 
	* There is a new command, copy it locally and return the 
	* lock 
	*/
	strncpy(command, tdata->command, PLMC_CMD_NAME_MAX_LENGTH);
	command[PLMC_CMD_NAME_MAX_LENGTH - 1] = '\0';
	cmd_enum = plmc_cmd_string_to_enum(tdata->command);
	/* Get the callback as well */
	callback = tdata->callback;
		
	/* Unlock */
	if (pthread_mutex_unlock(&tdata->td_lock) != 0) {
		syslog(LOG_ERR, "plmc_lib: encountered an "
			"error unlocking a client mutex");
		send_error(PLMC_LIBERR_SYSTEM_RESOURCES, 
				PLMC_LIBACT_UNDEFINED, ee_id, cmd_enum);
	}			
	
	#ifdef PLMC_LIB_DEBUG
	fprintf(plmc_lib_debug, "plmc_client_mgr got a new command %s for "
						"ee_id %s\n", command, ee_id);
	fflush(plmc_lib_debug);
	#endif 
	
	/* 
	* Change the socket option so that it waits for tv.tv_sec seconds 
	* for a respons 
	*/
	if (setsockopt (sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, 
							sizeof tv) < 0)  {
		syslog(LOG_ERR, "plmc_lib: encountered an error during "
				"a call to setsockopt() from client_mgr");
		syslog(LOG_ERR, "plmc_lib: errnor is %d", errno);
		syslog(LOG_ERR, "plmc_lib: Closing socket and exiting "
								"client_mgr");
		send_error(PLMC_LIBERR_SYSTEM_RESOURCES, 
				PLMC_LIBACT_EXIT_THREAD, ee_id, cmd_enum);
		if (close_socket(sockfd) !=0) {
			syslog(LOG_ERR, "plmc_lib: encountered an error "
					"during a call to close_socket");
		}
		pthread_exit((void *)NULL);
	}

	#ifdef PLMC_LIB_DEBUG
	fprintf(plmc_lib_debug, "plmc_client_mgr: Sending command to client\n");
	fflush(plmc_lib_debug);
	#endif 
	/* Send the command to PLMc */
	retval = send(sockfd, command, strlen(command), 0);
	if (retval <= 0) {
		syslog(LOG_ERR, "plmc_lib: Client Mgr encountered an error "
				"during a call to send(). Leaving cleanup for "
				"connection mgr");
		syslog(LOG_ERR, "plmc_lib: errnor is %d", errno);
		/* Connection MGR will send error to plmc_lib */
		pthread_exit((void *)NULL);
	}
		
	/* Get the response */
	bytes_received = recv(sockfd, result, PLMC_MAX_TCP_DATA_LEN, 0);
//.........这里部分代码省略.........
开发者ID:helioloureiro,项目名称:opensaf-fork,代码行数:101,代码来源:plmc_lib_internal.c


示例15: list_directory

int list_directory(int connfd, const char *dirname) {
    char *buf;
    DIR *d;
    struct dirent *dir;
    struct stat fs;
    const char *item_fmt;
    const char *filename;
    char *fullname;
    int len1, len2, nwritten = 0;
    int ret;

    d = opendir(dirname);
    if (d) {

        buf = (char *) malloc(MAXBUF);

        /* TODO: escape or quote dirname / filename */
        nwritten += snprintf(buf + nwritten, MAXBUF - nwritten,
                             "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\">\n"
                             "<html>\n"
                             "<title>Directory listing for %s</title>\n"
                             "<body>\n"
                             "<h2>Directory listing for %s</h2>\n"
                             "<hr>\n"
                             "<ul>\n", dirname + 1, dirname + 1);

        while ((dir = readdir(d)) != NULL) {
            filename = dir->d_name;

            if (strcmp(filename, ".") == 0 || strcmp(filename, "..") == 0) {
                continue;
            } else {
                len1 = strlen(dirname);
                len2 = strlen(filename);
                fullname = (char *) malloc(len1 + len2 + 1);
                strcpy(fullname, dirname);
                strcpy(fullname + len1, filename);
                fullname[len1 + len2] = 0;

                if (strcasecmp(filename, "index.html") == 0 || strcasecmp(filename, "index.htm") == 0) {
                    ret = fetch_file(connfd, fullname);
                    free(fullname);
                    free(buf);
                    closedir(d);
                    return ret;
                } else {
                    stat(fullname, &fs);
                    if (S_ISDIR(fs.st_mode)) {
                        item_fmt = "<li><a href=\"%s/\">%s/</a>\n";
                    } else {
                        item_fmt = "<li><a href=\"%s\">%s</a>\n";
                    }
                    nwritten += snprintf(buf + nwritten, MAXBUF - nwritten,
                                         item_fmt, filename, filename);
                }

                free(fullname);
            }
        }
        closedir(d);

        nwritten += snprintf(buf + nwritten, MAXBUF - nwritten,
                             "</ul>\n"
                             "<hr>\n"
                             "</body>\n"
                             "</html>\n");

        send_response(connfd, 200, NULL);
        send_header(connfd, "Content-Type", "text/html");
        send_header(connfd, "Content-Length", "%d", nwritten);
        end_headers(connfd);
        rio_writen(connfd, buf, nwritten);

        free(buf);

        return 1;
    }

    send_error(connfd, 404);

    return 0;
}
开发者ID:foreverbell,项目名称:playground,代码行数:82,代码来源:http-server.c


示例16: ms_scan_file


//.........这里部分代码省略.........
    // Check if this file is a shortcut and if so resolve it
    FollowLink(full_path, tmp_full_path);
  }
  else {
    strcpy(tmp_full_path, full_path);
  }
#elif defined(WIN32)
  if (strcasecmp(ext, ".lnk") == 0) {
    // Check if this file is a shortcut and if so resolve it
    parse_lnk(full_path, tmp_full_path, MAX_PATH_STR_LEN);
    if (PathIsDirectory(tmp_full_path))
      return;
  }
  else {
    strcpy(tmp_full_path, full_path);
  }
#endif

  // Check if the file has been recently scanned
  hash = HashFile(tmp_full_path, &mtime, &size);

  // Skip 0-byte files
  if (unlikely(size == 0)) {
    LOG_WARN("Skipping 0-byte file: %s\n", tmp_full_path);
    return;
  }

  // Setup DBT values
  memset(&key, 0, sizeof(DBT));
  memset(&data, 0, sizeof(DBT));
  key.data = (char *)full_path;
  key.size = strlen(full_path) + 1;
  data.data = &hash;
  data.size = sizeof(uint32_t);

  if ((s->flags & MS_RESCAN) || (s->flags & MS_FULL_SCAN)) {
    // s->dbp will be null if this function is called directly, if not check if this file is
    // already scanned.
    if (s->dbp != NULL) {
      // DB_GET_BOTH will only return OK if both key and data match, this avoids the need to check
      // the returned data against hash
      int ret = s->dbp->get(s->dbp, NULL, &key, &data, DB_GET_BOTH);
      if (ret != DB_NOTFOUND) {
        //  LOG_INFO("File %s already scanned, skipping\n", tmp_full_path);
        return;
      }
    }
  }

  LOG_INFO("Scanning file %s\n", tmp_full_path);

  if (type == TYPE_UNKNOWN || type == TYPE_LNK) {
    // auto-detect type
    type = _should_scan(s, tmp_full_path);
    if (!type) {
      if (s->on_error) {
        ms_errno = MSENO_SCANERROR;
        e = error_create(tmp_full_path, MS_ERROR_TYPE_UNKNOWN, "Unrecognized file extension");
        send_error(s, e);
        return;
      }
    }
  }

  r = result_create(s);
  if (r == NULL)
    return;

  r->type = type;
  r->path = strdup(full_path);

  if (result_scan(r)) {
    // These were determined by HashFile
    r->mtime = mtime;
    r->size = size;
    r->hash = hash;

    // Store path -> hash data in cache
    if (s->dbp != NULL) {
      memset(&data, 0, sizeof(DBT));
      data.data = &hash;
      data.size = sizeof(uint32_t);

      ret = s->dbp->put(s->dbp, NULL, &key, &data, 0);
      if (ret != 0) {
        s->dbp->err(s->dbp, ret, "Cache store failed: %s", db_strerror(ret));
      }
    }
    send_result(s, r);
  }
  else {
    if (s->on_error && r->error) {
      // Copy the error, because the original will be cleaned up by result_destroy below
      MediaScanError *ecopy = error_copy(r->error);
      send_error(s, ecopy);
    }

    result_destroy(r);
  }
}                               /* ms_scan_file() */
开发者ID:chincheta0815,项目名称:libmediascan,代码行数:101,代码来源:mediascan.c


示例17: handle_submit

static void handle_submit(Octstr *packet, Octstr *out, int sequence) {
	Octstr *dest_addr = eat_string_parm(packet, 21, 20);
	Octstr *orig_addr = eat_string_parm(packet, 23, 20);
	long DCS = eat_int_parm(packet, 30, 3);
	Octstr *UDH = eat_string_parm(packet, 32, 280);
	Octstr *text = eat_string_parm(packet, 33, 480);
	Octstr *textb = eat_string_parm(packet, 34, 280);
	long valid_rel = eat_int_parm(packet, 50, 3);
	Octstr *valid_abs = eat_string_parm(packet, 51, 12);
	long proto_id = eat_int_parm(packet, 52, 3);
	long delivery_rel = eat_int_parm(packet, 53, 3);
	Octstr *delivery_abs = eat_string_parm(packet, 54, 12);
	long reply_path = eat_int_parm(packet, 55, 1);
	long SRR = eat_int_parm(packet, 56, 2);
	long cancel = eat_int_parm(packet, 58, 1);
	long tariff_class = eat_int_parm(packet, 64, 2);
	long service_desc = eat_int_parm(packet, 65, 1);
	long priority = eat_int_parm(packet, 67, 1);
	List *other_dests = list_create();
	Octstr *tmp;

	while ((tmp = eat_string_parm(packet, 21, 20)))
		list_append(other_dests, tmp);

	if (logging == LOG_packets) {
		int i;
		printf("RCV: Submit to %s", octstr_get_cstr(dest_addr));
		for (i = 0; i < list_len(other_dests); i++) {
			printf(", %s",
				octstr_get_cstr(list_get(other_dests, i)));
		}
		printf("\n");

		if (orig_addr)
			printf("    From: %s\n", octstr_get_cstr(orig_addr));
		if (DCS > INT_MIN)
			printf("    Data coding: %ld\n", DCS);
		if (UDH)
			printf("    User data header: %s\n",
				octstr_get_cstr(UDH));
		if (text)
			printf("    Text: %s\n", octstr_get_cstr(text));
		if (textb)
			printf("    Text (binary): %s\n",
				octstr_get_cstr(textb));
		if (valid_rel > INT_MIN)
			printf("    Validity period: %ld (relative)\n",
				valid_rel);
		if (valid_abs)
			printf("    Validity period: %s (absolute)\n",
				octstr_get_cstr(valid_abs));
		if (proto_id > INT_MIN)
			printf("    Protocol ID: %ld\n", proto_id);
		if (delivery_rel > INT_MIN)
			printf("    First delivery: %ld (relative)\n",
				delivery_rel);
		if (delivery_abs)
			printf("    First delivery: %s (absolute)\n",
				octstr_get_cstr(delivery_abs));
		if (reply_path == 0)
			printf("    Reply path disabled\n");
		else if (reply_path == 1)
			printf("    Reply path enabled\n");
		else if (reply_path > INT_MAX)
			printf("    Reply path: %ld\n", reply_path);
		if (SRR > INT_MAX)
			printf("    Status report flags: %ld\n", SRR);
		if (cancel == 0)
			printf("    Cancel disabled\n");
		else if (cancel == 1)
			printf("    Cancel enabled\n");
		else if (cancel > INT_MAX)
			printf("    Cancel enabled: %ld\n", cancel);
		if (tariff_class > INT_MAX)
			printf("    Tariff class: %ld\n", tariff_class);
		if (service_desc > INT_MAX)
			printf("    Service description: %ld\n", service_desc);
		if (priority > INT_MAX)
			printf("    Priority: %ld\n", priority);
	}

	if (!dest_addr) {
		send_error(out, 53, sequence, "300", "no destination");
	} else if (list_len(other_dests) > 0) {
		send_error(out, 53, sequence, "301", "too many destinations");
	/* TODO: Report many other possible errors here */
	} else {
		unsigned char buf[TIMESTAMP_MAXLEN];

		make_timestamp(buf, time(NULL));
		if (logging == LOG_packets)
			printf("SND: Submit OK\n");
		send_packet(out, 53, sequence,
		            21, octstr_get_cstr(dest_addr),
			    60, buf,
			    0);
	}

	octstr_destroy(dest_addr);
	octstr_destroy(orig_addr);
//.........这里部分代码省略.........
开发者ID:armic,项目名称:erpts,代码行数:101,代码来源:test_cimd2.c


示例18: error_create

// Called by ms_scan either in a thread or synchronously
static void *do_scan(void *userdata) {
  MediaScan *s = ((thread_data_type *)userdata)->s;
  int i;
  struct dirq *dir_head = (struct dirq *)s->_dirq;
  struct dirq_entry *dir_entry = NULL;
  struct fileq *file_head = NULL;
  struct fileq_entry *file_entry = NULL;
  char tmp_full_path[MAX_PATH_STR_LEN];

  // Initialize the cache database
  if (!init_bdb(s)) {
    MediaScanError *e = error_create("", MS_ERROR_CACHE, "Unable to initialize libmediascan cache");
    send_error(s, e);
    goto out;
  }

  if (s->flags & MS_CLEARDB) {
    reset_bdb(s);
  }

  if (s->progress == NULL) {
    MediaScanError *e = error_create("", MS_ERROR_TYPE_INVALID_PARAMS, "Progress object not created");
    send_error(s, e);
    goto out;
  }

  // Build a list of all directories and paths
  // We do this first so we can present an accurate scan eta later
  progress_start_phase(s->progress, "Discovering");

  for (i = 0; i < s->npaths; i++) {
    LOG_INFO("Scanning %s\n", s->paths[i]);
    recurse_dir(s, s->paths[i], 0);
  }

  // Scan all files found
  progress_start_phase(s->progress, "Scanning");

  while (!SIMPLEQ_EMPTY(dir_head)) {
    dir_entry = SIMPLEQ_FIRST(dir_head);

    file_head = dir_entry->files;
    while (!SIMPLEQ_EMPTY(file_head)) {
      // check if the scan has been aborted
      if (s->_want_abort) {
        LOG_DEBUG("Aborting scan\n");
        goto aborted;
      }

      file_entry = SIMPLEQ_FIRST(file_head);

      // Construct full path
      strcpy(tmp_full_path, dir_entry->dir);
#ifdef WIN32
      strcat(tmp_full_path, "\\");
#else
      strcat(tmp_full_path, "/");
#endif
      strcat(tmp_full_path, file_entry->file);

     

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ send_error_response函数代码示例发布时间:2022-05-30
下一篇:
C++ send_data_cmd函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap